0

I'm struggling with this simple line of SQL...

Running it keeps giving me the error: Error: Unknown column 'comics' in 'where clause'.

This would normally be an easy fix... just go check to make sure "comics" exists as an entry in column "table_name". But I've already checked that...

enter image description here

I don't see anything wrong with my SQL:

$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = $table AND imgid = $imgid";

EDIT:

Btw, I've already tried it with quotes:

    $sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = '$table' AND imgid = $imgid";

But that throws the error:

Fatal error: Call to undefined method mysqli_result::num_rows() in C:\wamp\www\HTwS\scripts\likecounter.php on line 40

Can anyone help?

Thanks!

4

1 回答 1

3

The value of table_name is a string, and must therefore be single-quoted in the query. Failing to quote it as a string value, MySQL assumes that the supplied unquoted $table is a column identifier.

$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = '$table' AND imgid = $imgid";
//------------------------------------------------------------------------------------^^^^^^^^^

If $imgid is also a non-numeric value you'll need to quote that one as well.

We assume it has already been properly filtered against SQL injection, if it is the result of user input. I'll note, since the update includes MySQLi-specific code, that you really ought to be doing this as a prepared statement rather than a constructed string call to mysqli::query().

// Recommended to do this with  a prepared statement.
$stmt = $mysqli->prepare("SELECT ip FROM votes WHERE ip = ? AND table_name = ? AND imgid = ?");
if ($stmt) {
  $stmt->bind_param('ssi', $_SERVER['REMOTE_ADDR'], $table, $imgid);
  $stmt->execute();
  // Bind results, fetch, etc...
}

Edit after question update and comment:

Call to undefined method mysqli_result::num_rows()

The error message implies that you have attempted to access the MySQLi result property num_rows as a method call with () rather than a property. You should be using:

$result->num_rows

... instead of

$result->num_rows()
于 2013-02-17T18:16:57.367 回答