tags:

views:

36

answers:

1
<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';

if (!mysql_select_db('database'))
    die("Can't select database");


// choose id 31 from table users

echo $id; //31
echo $name; //id31's name
echo $surname //id31's surname
echo $blablabla //id31's blablabla

mysql_close($link);
?>
+7  A: 

Give this a shot:

$id = mysql_real_escape_string(31);
$result = mysql_query('SELECT * FROM `users` where `id` = ' . $id . ' LIMIT 1');

$row = mysql_fetch_assoc($result);

echo $row['id']; // 31
echo $row['name']; // name
// etc..

// If you wanted to output ALL the fields you could loop through
foreach($row as $field_name => $value) {
  echo $field_name . ': ' . $value . '<br />';
}

// The output would look something like
// id: 31
// name: John Smith
// ...

Functions Used:

Mike B
He could omit "LIMIT 1" from his query if his identifier (id) is truly unique. :)
Mike
@wb Very true. I like to keep it there so when others are reviewing the code they know for certain that this query, and surrounding code, is intended to fetch only one row. Personal preference I suppose.
Mike B
It seems `$id` will most likely be numeric, so you can probably get away with `(int) $id`, instead of `mysql_real_escape_string()`. But it is a good idea to get a beginner familiar with string escaping and SQL. :)
alex
@alex I had a rousing debate over that issue here http://stackoverflow.com/questions/2619295/how-to-know-when-escape-is-necessary-for-mysql/2619298#2619298. Shrapnel, et all, convinced me to always escape :p
Mike B
@Mike B I read from that question that *strings* should always be escaped. But an integer can't do anything unexpected I believe. Feel free to prove me wrong however :P
alex
@alex I don't think either of us are necessarily wrong. Your solution is certainly valid. I guess it's just easier to preach `mysql_real_escape_string()` all the time.
Mike B
@Mike B Agreed.
alex
@wb: I have read from some (My)SQL gurus, that leaving out LIMIT 1 has a performance drop even if there is only one unique result since the internals don't stop after they found the one row with the given id. Haven't tested that myself though
DrColossos