View Full Version : Convert table rows to individual arrays

09-07-2011, 03:07 PM
Hello. I am still learning php & mysql. I am trying to pull data from a table for a sub shop. The table is called "subs". Each row in the table has a "name"(of a sub). I know how to use a loop and print out all of the rows, but would rather (gets complicated) like to pull each row, and save it as an array, pull the next row, save it as an array .. and so on, so I can refer to them later. I don't care what the names of the row arrays will be, but do not want to keep having to repeat the code that I have provided. I would greatly appreciate any advice. Thank you in advance, Buffmin.

// get results from database
$result = mysql_query("SELECT * FROM subs Where NAME='Ham'")
or die(mysql_error());

$Ham = mysql_fetch_row($result);

echo $Ham[0];
echo $Ham[1];
echo $Ham[2];
echo $Ham[3];

$result = mysql_query("SELECT * FROM subs Where NAME='Turkey'")
or die(mysql_error());

$Turkey = mysql_fetch_row($result);

echo $Turkey[0];
echo $Turkey[1];
echo $Turkey[2];
echo $Turkey[3];

09-07-2011, 04:46 PM
Fetch_row's purpose is to pull a single row out of a resultset and store it as an array.
Pulling and printing is pretty much the same as printing them:

$aSubs = array();
while ($row = mysql_fetch_assoc($result)) // Changed to assoc so you can target by keyname
$aSubs[] = $row;
// Or, you can do it on one line too, but I prefer the previous since its more readable.
while (($aSubs[] = mysql_fetch_assoc($result)) || array_pop($aSubs));

You can also name your subs if you stick with straight associatives:

while ($row = mysql_fetch_assoc($result))
$aSubs[$row['Name']] = $row;

So you can identify a sub under $aSubs['Ham']; for example.

09-07-2011, 05:50 PM
Ah, great! I now understand why you would use a fetch, and I will try implementing one of those methods now. I like the associative method. Excellent! I appreciate your time and knowledge very much. Buffmin