Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL not fetching correct data? (PHP)

Tags:

php

mysql

This is pretty straight forward. EDIT: Updated question and added fourth echo.

Here is PHP code:

<?php

$ratings="3";
$item="Inception";

$query="SELECT * FROM items WHERE item = '". $item ."' LIMIT 1";

echo $query;

echo "<br />";

$result=mysql_query($query);

echo $result;

echo "<br />";

while ($row = mysql_fetch_array($result)) { 
    $item_id = $row['item_id'];
    echo $item_id;
    echo "<br />";
 }  

  $query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";

  echo $query_two;
  $sql = mysql_query($query_two);
  mysql_close();
?>

Here is web output with all the echo's:

SELECT * FROM items WHERE item = 'Inception' LIMIT 1
Resource id #7


INSERT INTO ratings (rating, item_id), VALUES (' 3 ', ' ')

How come my $item_id is blank? (third row underneath Resource id)

like image 234
TheLettuceMaster Avatar asked Jun 20 '12 16:06

TheLettuceMaster


2 Answers

This part of code produces it:

$result=mysql_query($query);

echo $result;

It shows Resource... because it is of resource type, it's just a sort of special handler for query, it's not like normal type (string or int for example), so it has nothing readable to print.

If you want to print data from query then you must firstly fetch it.

Also note that those mysql_* functions are deprecated, it is discouraged to use them. Note from php manual:

Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_query()

PDO::query()

like image 178
Zbigniew Avatar answered Oct 27 '22 00:10

Zbigniew


This does not have anything to do with IDs from the database.

This (Result#7) says that this result resource is seventh resource to be created by your php script execution.

like image 24
poncha Avatar answered Oct 27 '22 01:10

poncha