Need code to fetch a row and put into variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ghank
Forum Commoner
Posts: 35
Joined: Tue Apr 06, 2004 3:21 pm

Need code to fetch a row and put into variables

Post 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.
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post 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))".
ghank
Forum Commoner
Posts: 35
Joined: Tue Apr 06, 2004 3:21 pm

Post by ghank »

Thanks! That worked perfectly! Now I just have to figure out how. I have a lot to learn.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

learn 'how' to what?

:?:
ghank
Forum Commoner
Posts: 35
Joined: Tue Apr 06, 2004 3:21 pm

Post by ghank »

Now I just have to understand why it works. I am new to php.
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post 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?
ghank
Forum Commoner
Posts: 35
Joined: Tue Apr 06, 2004 3:21 pm

Post 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!
Post Reply