2

I simply want to define the variable "$read" as whatever its value is in the database. How can I do this?

$read =  "SELECT `read` FROM `users` WHERE `id` = '$id'";
Mike
  • 23
  • 1
  • 1
  • 3

6 Answers6

9
$read = mysql_result(mysql_query("SELECT read FROM users WHERE id = $id"),0);
Dan Grossman
  • 49,405
  • 10
  • 105
  • 95
  • @Mike in fact it's ugliest one – Your Common Sense Feb 08 '11 at 08:55
  • 1
    don't play fool, Dan. You know all the reasons yourself. You would never use it in your own code, that's enough. – Your Common Sense Feb 08 '11 at 08:59
  • 1
    I have done so, actually, it's useful to know that kind of shorthand exists when writing one-off scripts. – Dan Grossman Feb 08 '11 at 09:03
  • I've -1'ed your answer, as I find it irresponsible to present this code without a warning about potential SQL injection; especially to someone who you could reasonably assume not to know about such problems. Sure, you can assume that `$id` is safe, but please do so explicitly. Or even better, don't. – Sebastian Paaske Tørholm Feb 08 '11 at 09:07
  • I did not leave the same comment on other answers, as I left a general comment in my own answer. The other reason I particularily commented on yours is, you have high reputation with badges in PHP and MySQL, so your answer would more likely be weighted higher by a passer by. And no, I don't know that `$id` is user input, but do you feel it's safe to assume that someone who has trouble performing a simple SQL query has properly sanitized their inputs, without them explicitly saying so? – Sebastian Paaske Tørholm Feb 08 '11 at 09:26
  • Its amazing how people on this website have no decency. I have plus one'd this. Sometimes people use scripts that do not need such complicated composition because there are cases were we like to test things. "I choose to walk over driving a car because my house is really close by" – Shinji Dec 16 '14 at 16:33
6

Beware of the answers given using mysql_query, as they're vulnerable to SQL injection.

If $id is supplied by a user, you should never directly put it into the SQL query, but rather use a prepared statement.

One way of doing this, is by using PDO, in a manner similar to this:

$dbh = new PDO($connStr, $user, $pass);
$sql = "SELECT `read` FROM `users` WHERE `id` = :id";
$statement = $dbh->prepare($sql);
$statement->execute( array('id' => $id) );
$read = $statement->fetchColumn();

For more information on how to use PDO, see the following:

Community
  • 1
  • 1
Sebastian Paaske Tørholm
  • 45,185
  • 9
  • 92
  • 111
  • 1
    Alternatively, you could also use `mysqli`, which is preferred over the old `mysql` functions. – Lèse majesté Feb 08 '11 at 08:43
  • As a matter of fact, mysql is no more vulnerable than PDO or mysqli – Your Common Sense Feb 08 '11 at 09:00
  • 2
    @Col: Not unsafe per se, no, but by using the `mysql` functions, you have to manually ensure that all input is properly sanitized. By using a prepared query you avoid having to worry about sanitizing the input, which in general will leave your scripts safe, assuming you use them correctly. – Sebastian Paaske Tørholm Feb 08 '11 at 09:04
  • you're still worrying of binding it instead of sanitizing. Not that big difference as you all insists. and you all still suffer from injections, just because you don't understand PDO as well as you do not understand mysql. – Your Common Sense Feb 08 '11 at 09:14
  • 1
    @Col: SQL injections are caused by the database system understanding what you meant to be data as code. By binding data to a parameter, you're directly telling the database system that something is data, and thus an SQL injection cannot take place, if one uses prepared queries properly. See also [this question](http://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection). – Sebastian Paaske Tørholm Feb 08 '11 at 09:17
  • that's the point - if used properly. So, with mysql it's all the same. – Your Common Sense Feb 08 '11 at 09:20
  • and please, don't waste your time lecturing me. I know it all way better than you. And I **know** it, not believe, like you all, being stumbled when facing a query like SELECT * FROM table ORDER BY $sort – Your Common Sense Feb 08 '11 at 09:21
  • 1
    @Col. Shrapnel: How often do you need to pass direct user input as a sort parameter or other metadata? Unless you're writing a DB design/admin tool, that's unlikely to ever come up. And no one ever said that prepared statements was 100% protection against SQL injection, but it does prevent 99% of the SQL injection vulnerabilities you find in the wild. It's also pretty presumptuous to think that we are all suffering from SQL injections just because we prefer prepared statements. We get it, you've read SQL Antipatterns, so you're smarter than all of us. – Lèse majesté Feb 09 '11 at 22:24
  • @Lèse this very site, stackoverflow, has such a dynamical sorting feature, and it's not a DB design/admin tool. Parameterized search is also very common task. However, I am talking not of particular examples but of understanding. Just saying "PDO is safe" **misguiding** people. A fresh example: http://stackoverflow.com/questions/4945662/is-it-safe-to-let-the-user-specify-the-mysql-field-to-search/4945711#4945711 – Your Common Sense Feb 10 '11 at 04:17
5

One way to accomplish this is as follows:

// Run the query
$db_result = mysql_query("SELECT read FROM users WHERE id = $id");
// Get the first row (in this case you'll only get one row)
$row = mysql_fetch_array($db_result, MYSQL_NUM);
// Get the first column (you should only have one column anyway) and put it into your variable
$read = $row[0];

As pointed out below, I should add that if you don't trust $id to be properly escaped, you could be vulnerable to SQL injection. To overcome this, you should either make sure you properly escape and validate $id or use some kind of binding or prepared statement to do it for you, like in this question or in the example below.

Community
  • 1
  • 1
2

I know it's almost impossible to teach someone something, especially if they don't want to learn. But in hope it will be useful for someone else

All modern programming languages supports such a thing called "user defined functions".
A very handy feature.

A programmer, who wants to have their code real neat, can make a function out of some repetitive code and make calling this code REAL small, just almost as it was phrased in the OP:

$read = dbgetvar("SELECT `read` FROM `users` WHERE `id` = %d",$id);

another benefit from such an approach - your code could contain all necessary things, like parameter sanitization and error handling. And still calling this code would be shorter than all codes above, made ugly and unmantainable in pursue for shortness.

An example of such a function

function dbgetvar(){
  $args = func_get_args();
  $query = array_shift($args); 
  $query = str_replace("%s","'%s'",$query); 
  foreach ($args as $key => $val) { 
    $args[$key] = mysql_real_escape_string($val); 
  } 
  $query = vsprintf($query, $args);

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return FALSE;
  }
  $row = mysql_fetch_row($res)
  if (!$row) return NULL;
  return $row[0];
}
Your Common Sense
  • 152,517
  • 33
  • 193
  • 313
1

I would do the following:

// leave the single quotes around $id because it most probably is an INT
// LIMIT 1 will make the query a bit faster
$result = mysql_query("SELECT `read` FROM `users` WHERE `id` = $id LIMIT 1");

$row = mysql_fetch_row($result);
$read = $row[0];

Hope it works for you.

Anriëtte Myburgh
  • 12,127
  • 11
  • 47
  • 71
-3

Assuming there is only 1 result:

$read = mysql_fetch_array(mysql_query("SELECT read FROM users WHERE id = $id"));
$read = $read[0];
Or Weinberger
  • 6,901
  • 18
  • 66
  • 113