0

I'm looking to label a string based on database results. I have the following code:

$loc1 = "A";
$query  = "SELECT loc FROM User where nick='".$users[$j]."'";
    $loc = mysql_query($query);
    if($loc == 1)
        $loc1 = "A";
    if($loc== 2)
        $loc1 = "B";

The loc1 location is always "A". I've confirmed that the query works in MySQL and I'm having a difficult time understanding why this simple case is not working. I would appreciate your help!

2
  • 2
    $loc is mysql resource and not mysql data Commented Feb 22, 2012 at 13:18
  • Check out the usage examples in the mysql_query() docs. Commented Feb 22, 2012 at 14:00

3 Answers 3

4

The function mysql_query does not return the value of the column fetched, instead it returns a MySQL resource which you use to extract the column value returned by the query.

Change:

$loc = mysql_query($query);

to:

$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
    $loc = $row["loc"];
}
Sign up to request clarification or add additional context in comments.

Comments

2

You are storing mysql_query() return value in $loc which is a resource.

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

So, $loc is not 1 or neither equals to 2.

You need to use mysql_fetch_array / mysql_fetch_object, etc to manipulate the resource.

Comments

1

You must fetch the recordset with, in example mysql_fetch_row

Example #1 Fetching one row with mysql_fetch_row()

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

But, be careful with SQL injection attacks!

http://es.php.net/manual/en/security.database.sql-injection.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.