Why does my PHP script only return me Resource id #4?

Asked

Viewed 844 times

1

I am only trying to get the name of a column of a database table, and it always returns me only Resource id #4, I will send a part of my code.

<?php
    mysql_connect('localhost', 'root', '') or die ("Erro ao conectar!");
    mysql_select_db('agenda') or die ("Erro ao conectar!");
?>

<?php
   $iid = $_GET['id'];
   //echo $iid;
   $nomepessoa = "SELECT nome FROM pessoa WHERE id = $iid";

   $queryy = mysql_query($nomepessoa);

   echo $queryy;

?>

1 answer

4

mysql_query() returns a Resource or a false in case of an error. To extract the information from it you need to use the mysql_fetch_assoc() or other flavor of return. Three important things,

  • mysql_* functions have already been removed from php7 so it is best to use PDO or Mysqli.

  • mysql_fetch_assoc() or mysql_fetch_array() return only one row, if you want to return others you need a while.

  • Give significant names to your variables.

Your corrected code should stay that way:

$sql = "SELECT nome FROM pessoa WHERE id =" .mysql_real_escape_string($iid);
$query = mysql_query($sql);
$pessoa = mysql_fetch_assoc($query);
echo $pessoa['nome'];
  • 1

    Just complementing, you have to pass the parameter in the function mysql_fetch_assoc ( resource $result )

  • @Jefersonassis, thank you, corrected.

  • 2

    Yes it worked properly, thank you very much! And thanks for the tips rray.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.