Page 1 of 1

Need code to fetch a row and put into variables

Posted: Wed May 26, 2004 3:43 pm
by ghank
Can't find the code anywhere. I am trying to pull a row of data from MySql and put 5 of the fields into separate variables. Any help would be appreciated! Thanks in advance.

Posted: Wed May 26, 2004 4:02 pm
by kettle_drum

Code: Select all

$result = mysql_query("SELECT * FROM my_table WHERE blah = 'blah'");
$row = mysql_fetch_assoc($result);

echo $row['field1'];
echo $row['blah'];
echo $row['this'];
$test = $row['test'];
if the results are from more than one row, then use "while($row = mysql_fetch_assoc($result))".

Posted: Wed May 26, 2004 4:13 pm
by ghank
Thanks! That worked perfectly! Now I just have to figure out how. I have a lot to learn.

Posted: Wed May 26, 2004 5:14 pm
by tim
learn 'how' to what?

:?:

Posted: Wed May 26, 2004 5:21 pm
by ghank
Now I just have to understand why it works. I am new to php.

Posted: Wed May 26, 2004 5:25 pm
by tim
lol do you have a specific question?

and for tips, never use mysql_assoc

use mysql_fetch_array, it does both number / string forms of data that it pulls form the DB table

the while() function is a loop. It can be used to display ALL the data in a table by assign it a parameter. ie:

Code: Select all

<?php
$result = mysql_query("SELECT * FROM my_table WHERE blah = 'blah'"); 
// display all the usernames
while ($row = mysql_fetch_array($result)) {
$name = $row['username'];
echo $name;
}

// this while loop would go thru each row and grab the usernames/display them.
?>
that help?

Posted: Wed May 26, 2004 5:30 pm
by ghank
I ended up changing it to array. My bud used it so I changed it and it seemed to work the same. Thanks for letting me know the difference. Don't really have any specific questions. I believe I understand it now. After 5 hours and 4 coffees, by brain is a little overloaded though. Thanks everybody for your help!