PHP has a ton of built-in functions (over 5700 as of this blog post),
almost 50 of which deal with MySQL database manipulation.
I don't think I normally use more than about 3 or 4 mysql_... functions, but one task I perform
often is gather all of the returned rows into an array.
// assume $conn is my database connection
$query = "SELECT * FROM someTable WHERE someField = 'Some Value'";
$result = mysql_query($q, $conn);
$rows = array();
while($row = mysql_fetch_assoc($r)) {
$rows[] = $row;
}
// $rows now holds all of my results
If I just have to do one query, that's fine. But on large projects I may have several queries on a single page. Any time I have to type something more than twice I quickly start looking for ways to abstract it into a reusable function, so here goes:
function mysql_fetch_all($query, $conn) {
$result = mysql_query($query, $conn);
$rows = array();
while($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
// all future queries become one-liners
$employees = mysql_fetch_all("SELECT * FROM Employees", $conn);
Nothing Earth-shattering, but fewer keystrokes means fewer chances for error. What's your favorite PHP or SQL shortcut?
I'm a Front-End Engineer at Yahoo! working on the Mail and Messenger teams. I blog about web design and development topics including accessibility, usability, performance, and developing HTML / CSS / JavaScript applications on Appcelerator Titanium and Adobe AIR.
If you're a web developer, you might enjoy Jelo, my JavaScript library.
All original work on this site is covered by a Creative Commons Attribution 3.0 license unless otherwise specified.
You may share or use any code or images from this site in any manner, for free, so long as reasonable effort has been made to give credit where due.
The views expressed in the posts and comments on this blog do not necessarily reflect the views of Yahoo!