-2

I am writing a PHP script in which i need to run a MySQL query. I opened the data connection and all such pleasantries are working fine. My only doubt is regarding the syntax of the following query, since it is not working. I have a php variable $post_id against which I am selecting from the database.

$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";

$result=mysql_query($query);

$req_id=$result[0];
Ashif Shereef
  • 454
  • 1
  • 8
  • 24

3 Answers3

0

You are not fetching the result.

So try this

<?php

$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";

$result=mysql_query($query);

while($row=  mysql_fetch_array($result))
{
    echo $row['needer'];//You can display your result like this. 
}

Also mysql is depricated learn Mysqli or PDO.

For Mysqli function check this link http://php.net/manual/en/book.mysqli.php

For PDO function check this link http://php.net/manual/en/book.pdo.php

arif_suhail_123
  • 2,509
  • 2
  • 12
  • 16
  • Thanks buddy. I mean, the syntax "SELECT needer FROM needer_blood WHERE value_id='$post_id'"; is right. isnt it? with the $post_id variable in it. – Ashif Shereef Oct 15 '14 at 05:06
0

try this one, its better approach if you user SQL INJECTION

<?php

$query1="SELECT needer FROM needer_blood WHERE value_id='".mysql_real_escape_string($post_id)."'";

$result=mysql_query($query) or die(mysql_error()); // die only used in development , remove when you live this

$data = mysql_fetch_array($result) or die(mysql_error());

echo $req_id = $data['needer']; // $req_id = $data[0];

?>
Zeeshan
  • 1,659
  • 13
  • 17
0

Firstly, notice that your query variable is called $query1 and your mysql_query is using a variable called $query (variable mismatch?).

You can use mysql_fetch_assoc() to get an associative array from your query.

Using the following code should work, though you should do some checking to make sure that the $result[0] exists.

// Query String
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
// Run the query
$result=mysql_query($query1) or die(mysql_error());
// Fetch Associative Array
$rows=mysql_fetch_assoc($result);
// Get result [0]: this could result in an error if your query result is empty.
$req_id=$rows[0];

Also, as others have pointed out, mysql is deprecated and you should update to MySQLi or PDO_MySQL if your server supports it. If not, change servers.

Also, as others pointed out, you should watch out for SQL injection. This StackOverflow answer adresses the issue well.

Community
  • 1
  • 1
Jonathan
  • 6,507
  • 5
  • 37
  • 47