Monday, June 13, 2011

PHP helper function for making SQL queries easy

Go get this function called mysql_magic at:
http://www.php.net/manual/en/ref.mysql.php#100626
This function listed in PHP's manual looks very promising for making query's easy to use but just passing the query plus the parameters to a function that uses php's mysql_bind function plus the function returns a resultset if its a select and will also work for a delete or update statement which exits the function sooner than normal.
to use the function use these:
$nb_affected = mysql_magic('delete from users');
$nb = mysql_magic('select count(*) from users');
$one_row = mysql_magic('select * from users limit 1');
$all_rows = mysql_magic('select * from users where name = ?', 'John');
$id = mysql_magic('insert into users(name,rank) values(?,?)', 'Vincent', 3);
http://www.php.net/manual/en/ref.mysql.php#100626


To make the function work with the example below make this change to the function.
global $con, $con_server, $con_username, $con_password, $con_database;

if (!$con)
{
$con = mysql_connect( $con_server, $con_username, $con_password );
@mysql_select_db( $con_database, $con );
}
I will show you how to use it next. Make a table called data in mysql.

CREATE TABLE data (age INT,name VARCHAR(50));

Next insert a couple rows.
INSERT INTO data VALUES(20,'Bill');
INSERT INTO data VALUES(18,'Mark');

I put the function mysql_magic in a file called mysql_helper.php into the include path, but you can put it in the same folder as your webpage that will be doing mysql queries. This is all I did to make it work:
include "helper_mysql.php";
$con_server = "localhost";
$con_username = "username";
$con_password = "password";
$con = @mysql_connect($con_server,$con_username,$con_password);
if (!$con){
die('Could not connect to Database');
}
$con_database = "test";
mysql_select_db($con_database, $con);
$all_rows = mysql_magic('select * from data');
echo "<br /><pre>".print_r($all_rows,true)."</pre>";


Now you will see the result will show all the rows from the table:
Array
(
[0] => Array
(
[age] => 20
[name] => Bill
)

[1] => Array
(
[age] => 18
[name] => Mark
)
)

Then you can use the following to insert more data into the table.
$insert = mysql_magic("INSERT INTO data VALUES(15,'Ron')");

Now for a more useful example. Use ?'s to signify a parameter to bind variables to.
$age = 25;
$name = "Sally";
$insert = mysql_magic("INSERT INTO data VALUES(?,?)",$age, $name);
//after inserting use the following to see what the table looks like now.
echo "<br /><pre>".print_r($all_rows,true)."</pre>";

In the next post I will show how to make a stored procedure or function in MySQL and call it using the magic_mysql function when you want to insert data into the data table.

No comments: