<?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);
?>
views:
36answers:
1
+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:
mysql_real_escape_string()
- Escapes special characters in a string for use in an SQL statementmysql_query()
- Send a MySQL querymysql_fetch_assoc()
- Fetch a result row as an associative array
Mike B
2010-06-20 00:35:25
He could omit "LIMIT 1" from his query if his identifier (id) is truly unique. :)
Mike
2010-06-20 00:40:20
@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
2010-06-20 00:42:42
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
2010-06-20 00:43:35
@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
2010-06-20 00:46:37
@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
2010-06-20 00:50:51
@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
2010-06-20 00:55:23
@Mike B Agreed.
alex
2010-06-20 01:05:06
@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
2010-06-20 08:42:23