Armand Armand - 3 months ago 9
MySQL Question

SELECT statement returns first row instead of record that is looked up

I am trying to select a record from my database, and I am return instead the first one in the table. No matter what I try, the first one gets returned.

Here's the query:

$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = @mysqli_query($dbc, $query_task_owner);


Then I try a test to see the value that is returned as such:

echo $response or die(mysql_error());


This is where I see the user_id of the first row.

Even if I try to put a specific value in the query, as follow, I am getting the same result:

$query_task_owner = "select user_id from users where full_name = 'LeBron James'";


I do not understand because when I trying this query directly in PHPMyAdmin, I am getting the right result. So the query itself is correct.

Any idea?

Answer

Fetch $response using mysqli_fetch_array().

<?php
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = @mysqli_query($dbc, $query_task_owner);
$row = mysqli_fetch_array($response,MYSQLI_ASSOC);
echo $row['user_id'];
?>

If, users are more related to that full name. Then, use while loop to fetch all record.

<?php
$query_task_owner = "select user_id from users where full_name = '$c_task_owner_name'";
$response = @mysqli_query($dbc, $query_task_owner);
while($row = mysqli_fetch_array($response,MYSQLI_ASSOC))
{
  echo $row['user_id']."<br>";
}
?>
Comments