convert mysql_connect to joomla-based connect - database

I have been struggling with this for a couple days now, but can't get it to work.
I'm currently building a website in Joomla and added a puzzle-game page into it. What I want to do is, save the time-score and create a simple top-10 score list.
I got it to work by what I think is the hard way ;) by using a <form method="post" action="include/dbscore.php"> function. In the 'dbscore.php' file I got the following code:
<?php
$con = mysql_connect("localhost","[my db username]","[my db password]");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("[my db name]", $con);
$sql="INSERT INTO uhkbw_puzzel_score (fname, lname, time, date)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[time]','".date('d-M-Y')."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your score is succesfully saved";
mysql_close($con)
?>
This does the trick and posts the data I want into the database, but I feel there must be a much simpler and safer way, since Joomla already should know the db name/passw. However the puzzel-game index.php itself is located in a separate folder inside the joomla directory and loaded through an iframe into joomla and is not a standard joomla module or component...
I already tried using the $db = JFactory::getDBO(); methode, but I must do something wrong
Any ideas?

Related

Wordpress addon to add data to a database and then call the data

I know this question is probably going to get downvoted and I will probably get into trouble but I am hoping someone may be able to help me with my situation.
On my site I use json to download data from an external source, and then I style it beautifully.
Within the json data is an individual ID for each data set.
What I want to accomplish is to have a database where I can insert the ID and a url link.
I have created the table within the wordpress database via phpMyAdmin, but I want to create a page within the admin section where I can simply add the data in.
For displaying the json data I use a php insert addon, within that php clip i want to do a piece of code that checks the database for the id within my custom database and displays the link.
I will be honest I don't know where to start on this, even if its just a link to a source that shows me how to create an admin page and submit data to the database within wordpress dashboard.
I really appreciate any help given and like I say I know I should try harder, but when ever I do a search all I get is 100's of references to add an admin to the database manually.
Thanks,
Adam
Edit I just realized I never put any table information in my question.
The table name within wordpress is called: wp_home_tickets
within that are 3 fields: id (auto increasement), gameid (numeric) and ticketlink (text)
thanks.
For adding a custom settings page in your admin, use the Settings API https://codex.wordpress.org/Settings_API
Here is a nice tutorial using it https://deliciousbrains.com/create-wordpress-plugin-settings-page/#wp-settings-api
To fetch data from your custom table, use the wpdb class https://developer.wordpress.org/reference/classes/wpdb/. More specifically, you can use wpdb::get_results if you will have multiple rows sharing the same id https://developer.wordpress.org/reference/classes/wpdb/get_results/
Or wpdb::get_row if you will ever only have one https://developer.wordpress.org/reference/classes/wpdb/get_row/
Hope this helps you out!
For anyone wishing to see how it was done, here is how I did it.
I created a file in my theme called db_admin_menu.php and added the following to it:
<?php
function ticket_admin_menu() {
global $team_page;
add_menu_page( __( 'Tickets', 'sports-bench' ), __( 'Tickets', 'sports-bench' ), 'edit_posts', 'add_data', 'ticket_page_handler', 'dashicons-groups', 6 ) ;
}
add_action( 'admin_menu', 'ticket_admin_menu' );
function ticket_page_handler() {
$table_name = 'wp_home_tickets';
global $wpdb;
echo '<form method="POST" action="?page=add_data">
<label>Team ID: </label><input type="text" name="gameid" /><br />
<label>Ticket Link: </label><input type="text" name="ticketlink" /><br />
<input type="submit" value="submit" />
</form>';
$default = array(
'gameid' => '',
'ticketlink' => '',
);
$item = shortcode_atts( $default, $_REQUEST );
$gameid = $item['gameid'];
if ($wpdb->get_var("SELECT * FROM wp_home_tickets WHERE gameid = $gameid ")) { echo 'Ticket already exists for this game.'; goto skip; }
if (!empty($_POST)) { $wpdb->insert( $table_name, $item ); }
skip:
}
?>
I then put this code in my script that fetches and displays the json:
$matchid = $match['id'];
$ticket_url = $wpdb->get_var("SELECT ticketlink FROM wp_home_tickets WHERE gameid = '$matchid' ");
if ($ticket_url) { echo 'Get Tickets'; }
I hope someone does find it of use, i did have to use a wordpress plugin called `Insert PHP Code Snippet' by xyzscripts to be able to snippet the php to a shortcode, but that is not the purpose of this post.
Thanks again for your help.

I want to show some values stored in database in a Joomla article

Hello everyone I want to show some values from the database in a joomla article in the following manner how can I do it ???
I've created the database in the following manner
One way to include php code in your article is to use an extension like
http://extensions.joomla.org/extension/sourcerer
This will allow you to put some php code that will make a query. Doing this in a Joomla way it would look like:
$db = JFactory::getDbo();
$query = $db->getQuery(true)
$query
->select($db->quoteName(array('ques', 'options', 'ans')))
->from($db->quoteName('#__yourtablename'))
->where($db->quoteName('id') . ' = ' . $idOfQuestionYouWantToGrab);
$db->setQuery($query);
$result = $db->loadAssoc();
Now you can show your question:
<?php echo $result['ques']; ?>
then somehow you will need to visualize questions separating them them with some regular expression, since your fields aren't structured well :/
Same with the answers. Then you will need to make some validation with JavaScript to see if answer is the correct one.

CakePHP generate and save PDF

I am using CakePHP for an application that does auto generation of vouchers to a PDF file. But they work through user clicks. Now I wish to create it automatically and have the file written to the server hard disk. Then later on, these files will get zipped up and sent to an email of my choice.
For the PDFs I use Html2ps/Html2pdf component found in CakePHP. You can view it here http://bakery.cakephp.org/articles/Casmo/2010/06/26/creating-pdf-files-with-html2ps-html2pdf
One issue I have is the formatting doesn't look right. If I have links that look like this:
http://www.mydomain.com/this-is-my-perma-link
They will render this way in the generated PDF:
http://www.mydomain.com/this- is- my- perma- link
And that would be a broken link. I've tried to use other characters to replace the dash but it doesn't work. I am not sure why.
Another issue is, how can I write the generated PDF file to my server hard disk? Is there an option for me to do that and how do I define the destination. Any examples?
Maybe thanks in advance!
Hi you can to use FPDF library . and you can to save file in the server and then redirect to other function.
check the next code.
///Call to library
<?php
App::uses('AppController', 'Controller');
require_once APP . 'Vendor' . DS . 'fpdf17' . DS . 'fpdf.php';
class TestController extends AppController {
public function test(){
--Create fpdf.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Output('files/Report.pdf');
$pdf->text($x,$y,'Txt');
return $this->redirect(
array('controller' => 'Test', 'action' => 'test_new')
);
}
}

CakePHP model useTable with SQL Views

I'm in the process converting our CakePHP-built website from Pervasive to SQL Server 2005. After a lot of hassle the setup I've gotten to work is using the ADODB driver with 'connect' as odbc_mssql. This connects to our database and builds the SQL queries just fine.
However, here's the rub: one of our Models was associated with an SQL view in Pervasive. I ported over the view, but it appears using the set up that I have that CakePHP can't find the View in SQL Server.
Couldn't find much after some Google searches - has anyone else run into a problem like this? Is there a solution/workaround, or is there some redesign in my future?
First of all, which version of CakePHP are you using? I'll assume it's about CakePHP 1.2+.
The problem
I'm not familiar with SQL Server 2005 (nor any other versions), but after some investigation, I think the problem is in DboMssql::listSources() method, which selects available table names from INFORMATION_SCHEMA.TABLES and so it doesn't "see" any available views.
The solution
Change DboMssql::listSources() to select available table names from sys.tables or, if I'm wrong about sys.tables, to additionally select names from INFORMATION_SCHEMA.VIEWS.
So, not to mess with CakePHP core files, you'll have to create custom datasource, which extends DboMssql and overrides ::listSources() method. To do so, you'll have to:
Create <path/to/app>/models/datasources/dbo/dbo_custom_mssql.php:
<?php
App::import('Datasource', 'DboMssql');
class DboCustomMssql
extends DboMssql
{
public
function listSources()
{
$cache = DboSource::listSources();
if ($cache != null) {
return $cache;
}
$result = $this->fetchAll('SELECT TABLE_NAME FROM SYS.TABLES', false);
if (!$result || empty($result)) {
return array();
} else {
$tables = array();
foreach ($result as $table) {
$tables[] = $table[0]['TABLE_NAME'];
}
DboSource::listSources($tables);
return $tables;
}
}
}
Change config/database.php config: 'driver' => 'custom_mssql'
Test
NB: The worst thing is that DboMssql::listSources() interface is kinda broken (w/o optional $data argument (like Datasource::listSources() declares)) and doesn't provide any point of extension, so, in order to have source list caching, we're forced to call DboSource::listSources() instead of broken parent::listSources().
I have SQL Server views being happily displayed. The main difference that I have to you is that I am using the mssql driver rather than the odbc_mssql driver. Perhaps you should try switching to that and figure out whatever problems you have there first.

codeigniter image uploading mysql

I wanted to know if I was uploading an image in CodeIgniter to a database what would be my
$config['upload_path']
All the examples I have seen are using the filesystem. I have articles in a db and would like to store images relating to articles in the db as well. Can anyone help?
You can read this great article called Storing Images in Mysql.
The article covers the following:
Isn’t this a bad idea?
What is a BLOB?
Creating an image table
The upload form
Uploading the image
The upload() function
Display an image from the database
Displaying all the information
But not to leave you empty handed, look into Blob, it's a data-type for colums in MySQL ( and various other dbms ). This will let you store data such as Images and other binary file-types.
The idea of storing files and images in the database is in general the same as storing them on the filesystem, the layer in-between upload and having the actual file is just different.
You cannot just set your upload-path and hope everything is solved, you need to get some dirt on your hands aswell!
i posted here in hope this help someone since this is an old post and the answers are no help at all, this code works for me, also the model part is not here so you must figure it out reading codeigniter's docs , i think this will work if you put it in your controller, also it think the submit form must be pointing this function
function upload() {
$caption = $this->input->post('caption');
$codigo = $this->input->post('codigo');
//$imagen = $this->input->post('imagen');
$config['upload_path'] = 'uploads';// this is a directory with 777 permissions where you upload the file
$config['allowed_types'] = 'gif|jpg|jpeg|png|pdf';
//$config['max_size'] = '5000';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('imagen')) { // this is the input from the form
echo $this->upload->display_errors();
} else {
//here $file_data receives an array that has all the info
//pertaining to the upload, including 'file_name'
$file_data = $this->upload->data();
$fp = fopen($file_data['full_path'], 'r');
$content = fread($fp, filesize($file_data['full_path']));
//$content = addslashes($content);
fclose($fp);
$data = array( // this is the table i got in my db
'idBotones' => null,
'imagen' => $content, //blob image
'caption' => $caption,
'codigo' => $codigo
);
$this->load->model('generic_model');
$table = "botones";
$this->generic_model->insertar_datos($table, $data);
//print_r($content);
}
}
It seems like for most common use cases storing images in the database is not a great idea.
Please see these two previous SO threads:
To Do or Not to Do: Store Images in a Database
Storing Images in DB - Yea or Nay?

Resources