2

I am trying to print out some topic information, but it is not going so well. This is my query:

SELECT * FROM topics WHERE id='$read'

This doesn't work. I've echo'ed the $read variable, it says 1. So then if I do like this:

SELECT * FROM topics WHERE id='1'

It works perfectly. I don't get what is the problem. There's no hidden characters in $read or anything else like that.

the_marcelo_r
  • 1,847
  • 22
  • 35
finst33
  • 141
  • 1
  • 3
  • 11

7 Answers7

1

Try like this:

$query = "SELECT * FROM topics WHERE id='" . $read . "'"
Danilo Radenovic
  • 1,019
  • 1
  • 11
  • 23
0

ID is normally a numeric field, it should be

$id = 1;
$query = "SELECT * FROM topics1 WHERE id = {id}"

If you are using strings for some reason, fire a query like

$id = '1';
$query = "SELECT * FROM topics1 WHERE id = '{$id}'"
Akash
  • 4,956
  • 11
  • 42
  • 70
0
SELECT * FROM topics WHERE id=$read

it consider it as string if you put i single quotes

Sivagopal Manpragada
  • 1,554
  • 13
  • 33
0

I wonder why all the participants didn't read the question that clearly says that query with quotes

SELECT * FROM topics WHERE id='1'

works all right.

As for the question itself, it's likely some typo. Probably in some other code, not directly connected to $read variable

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
0

try

$query = sprintf("SELECT * FROM topics WHERE id='%s';",$read);

Also remember to escape the variable if needed.

Lars
  • 615
  • 1
  • 4
  • 13
0

Looks like you might have an issue with the query generation as everyone else is pointing to as well. As Akash pointed out it's always good to build your query in to a string first and then feed that string to the MySQL API. This gives you easy access to handy debugging techniques. If you are still having problems try this.

$id = 1;
$query = "SELECT * FROM `topics1` WHERE `id`={$id}";
echo ": Attempting Query -> {$query}<br />";

$res = mysql_query($query, $dblink);
if($res <= 0)
    die("The query failed!<br />" . mysql_error($dblink) . "<br />");

$cnt = mysql_num_rows($res);
if($cnt <= 0)
{
    $query = "SELECT `id` FROM `topics1`";
    echo "No records where found?  Make sure this id exists...<br />{$query}<br /><br />";

    $res = mysql_query($query, $dblink);
    if($res <= 0)
        die("The id listing query failed!<br />" . mysql_error($dblink) . "<br />");

    while($row = mysql_fetch_assoc($res))
        echo "ID: " . $row['id'] . "<br />";
}

This will at least let you monitor between calls, see what your query actually looks like, what mysql says about it and if all else fails make sure that the ID you are looking for actually exists.

-1

try with this : SELECT * FROM topics WHERE id=$read

haffane hatim
  • 474
  • 5
  • 30