So, if I want to pull some data from my database (PHP, MySql), whether I’m writing for a class or hard-coded, I’ve been doing something along the lines of:
$x = "SELECT <column(s)> FROM <table> WHERE <conditions>";
$y = mysql_query($x);
while($result = mysql_fetch_assoc($y))
{
echo $result['column']; // etc
}
Obviously I use a function or class (depending on design pattern) so pulling data like this is done in one line, I just wondered if I was doing ‘too much work’ and if there was a quicker way of doing this.
Thanks.
You can get tighter code by using a more up-to-date PHP module to access your database.
The
mysql_xxx()functions that you’re using have been superseded by themysqli_xxx()functions. This uses similar code, but provide more features and security than the older library:You can find out more about MySQLi (including how it differs from the old MySQL library) here: http://php.net/manual/en/book.mysqli.php
But for really concise code, you might consider looking into the PDO library. Your query could be expressed with PDO like this:
…and if you really wanted to, the first two lines of that code could be combined as well.
Find out more about PDO at the PHP manual site: http://www.php.net/manual/en/book.pdo.php