Tutorials MySQL Selecting a MySQL row

Selecting a MySQL row

Hello and welcome to PHP Trainee. Now that your database is set up, you will learn how to grab data from it.

How do you select data from a MySQL row?

After you access the database, you have to select and query your results. There are 3 fetch statements used by PHP to grab queries: mysql_fetch_assoc, mysql_fetch_row and mysql_fetch_array. These statements grab the data and turns it into an array.


What is the difference between the fetch functions?

mysql_fetch_assoc grabs the name of the column. mysql_fetch_row uses a number to grab the current location of your array relative to your select statement. mysql_fetch_array can grab either the number or the name. mysql_fetch_array is a bit slower due to grabbing both the name and number, but with todays computers it shouldn't make a difference.

Note: When using mysql_fetch_row or mysql_fetch_array with an integer, the count starts from 0.

How do I grab this thing?

Put it into a variable. It grabs the data as an array so you need to pick the right value.

$sql    = 'SELECT name FROM table';
$result = mysql_query($sql);
$array  = mysql_fetch_array($result);
$assoc  = mysql_fetch_assoc($result);
$row    = mysql_fetch_row($result);

// Produces Bob
echo $array['0'];
echo $assoc['name'];
echo $row['0'];

What's the point if I need to ask for every value?

It's the whole point of PHP in general; write code so you don't have to. There's no point in using a database if you plan on only having 1 row. Sometimes you need to spit out chunks of your database.

$result = mysql_query('SELECT * FROM table');

while ($array = mysql_fetch_array($result)) {
  echo $array['0'];

That's all for today folks. See you next week on PHP Trainee.

Posted by on . Category: MySQL


No comments posted yet

You need to register or login to post new comments.