Page 1 of 1
Really newbie question about databases.
Posted: Wed Nov 26, 2003 1:05 pm
by lazersam
Hi all
I have one really newbie question....
I have a database of names. Each row has an ID number, first_name etc. If I want to retrieve the first_name for ID #2 for example - what is the syntax?
I already know the ID (primary) and want to retrieve just 1 record. I dont want to start a loop or anything. I cant seem to figure it out.
Thanks
Lawrence.
Posted: Wed Nov 26, 2003 1:09 pm
by d3ad1ysp0rk
Code: Select all
//connect to DB (you've probably already done this, so i won't type that part)
$sql = "SELECT `first_name` FROM `table_name` WHERE `ID` = '2'";
$name = mysql_result(mysql_query($sql), 0,0);
echo $name;
Posted: Wed Nov 26, 2003 1:31 pm
by lazersam
Thank you very much - That did it.
Regards
Lawrence.
Posted: Wed Nov 26, 2003 2:01 pm
by lazersam
Just 1 more thing
I actually want to retrieve more than one field, following your advice I am using the following syntax
їphp]
$sql = "SELECT `first_name` FROM `users` WHERE `ID` = '$sponsor'";
$sfname = mysql_result(mysql_query($sql), 0,0);
$sql = "SELECT `last_name` FROM `users` WHERE `ID` = '$sponsor'";
$ssname = mysql_result(mysql_query($sql), 0,0);
echo "$sfname "."$ssname";
ї/php]
I was just wondering if there was an easier way to request the data, maybe from using one mysql_query?
Regards
Lawrence.
?>
Posted: Thu Nov 27, 2003 2:09 am
by twigletmac
You can combine those two queries to:
Code: Select all
SELECT first_name, last_name FROM users WHERE ID = '$sponsor'
You could then continue to use mysql_result() or instead use [php_man]mysql_fetch_assoc[/php_man]():
Code: Select all
$result = mysql_query($sql) or die(mysql_error().'<p>'.$sql.'</p>');
$row = mysql_fetch_assoc($result);
echo $row['first_name'].' '.$row['last_name'];
Mac
Posted: Fri Nov 28, 2003 2:34 pm
by lazersam
Cool thanks alot

Posted: Fri Nov 28, 2003 3:34 pm
by mrvanjohnson
Or you can select everything for that record and just display the fields you want using this as your Select
Code: Select all
SELECT * FROM users WHERE ID = '$sponsor'
Posted: Mon Dec 01, 2003 3:13 am
by twigletmac
mrvanjohnson wrote:Or you can select everything for that record and just display the fields you want using this as your Select
Code: Select all
SELECT * FROM users WHERE ID = '$sponsor'
But this is not the preferred option for production code - much better IMO is to specifically name the fields you are trying to return as it makes it much easier to deal with changes to the database. Plus if you have 15 columns and only want to use data from 5 of them you it's a waste to return everything.
Mac