SQLProNews This is an iEntry Publication

Advertising, Headlines, Signup
SQLProNews
SecurityProNews
ITmanagement








Advanced MySQL In PHP

By Bryan Young
Expert Author
Article Date: 2011-05-05

Let's face it, we all know the basics of connecting to a MySQL database in PHP. That's development 101. But how many times have you looked at your code and wondered "there must be a better way to do this" to yourself? These are a couple PHP functions that I have found to be indispensable as my career as a web developer have progressed.

mysql_result()

This function gives you the result from one cell of a mysql result. I found that when I needed a one time value from my database, such as a COUNT(*), I would use something like this.

$result = mysql_query($query);
$row = mysql_fetch_row($result);
$count = implode($row);


mysql_result() combines the last two lines into one simpler solution.

$count = mysql_result($result, 0);


$result is the same as above, and the 0 signifies that we want the first row from the result.

mysql_insert_id()

This is one of my favorites. It is a shorthand method for calling the SELECT LAST_INSERT_ID(); query wrapped up in a single PHP function. After an INSERT statement into an auto-incremented table, this gives you the id of the inserted row. This is useful when you are inserting into a table where the id is the foreign key in a dependent table, and is much easier than re-querying the database using a WHERE clause.

mysql_query("INSERT INTO my_table (colA, colB) VALUES ('foo', 'bar')");
mysql_query("INSERT INTO related_table (my_table_id, colC) VALUES (" . mysql_insert_id() . ", 'baz')");


There are obviously many more functions that I could include in a article such as this, but I have found that by far, these two are the ones I use the most (outside of the required mysql_connect(), mysql_query(), mysql_fetch_*()). I hope that you find them as useful as I do.


About the Author:
Bryan Young is a staff writer for WebProNews.




SQLProNews is an iEntry, Inc. ® publication - All Rights Reserved Privacy Policy and Legal
Advanced MySQL in PHP