Error "Undefined variable"

2

I'm trying to run this code but it's not working.

$sql    = "SELECT * FROM cliente WHERE id = $id ";
$limite = mysql_query("$sql");

while ($sql = mysql_fetch_array($limite)){

    $nome       = $sql["nome"];
    $telefone   = $sql["telefone"];

    $id         = $_GET['id'];

    echo "<div class='clientecelula'>" ;
    echo "$nome"; 
    echo "<span class='telcelula'> $telefone </span>";
    echo "<span class='semcelula'>  </span>";
    echo "</div>" ; 

}

I'm getting the error:

  

Notice: Undefined variable: id in   /Applications/XAMPP/xamppfiles/htdocs/ross/semana.php on line 7

     

Warning: mysql_fetch_array () expects parameter 1 to be resource,   boolean given in /Applications/XAMPP/xamppfiles/htdocs/ross/semana.php   online 12

What's the problem here?

    
asked by anonymous 27.02.2015 / 08:00

2 answers

2

Your problem is in the $id variable that is assigned after it is already being used in SQL.

If you change your site, you resolve this problem:

$id     = $_GET['id'];
$sql    = "SELECT * FROM cliente WHERE id = $id ";
$limite = mysql_query($sql);

while ($sql = mysql_fetch_array($limite))
{
    $nome       = $sql["nome"];
    $telefone   = $sql["telefone"];

    echo "<div class='clientecelula'>" ;
    echo "$nome"; 
    echo "<span class='telcelula'> $telefone </span>";
    echo "<span class='semcelula'>  </span>";
    echo "</div>" ; 

}

IMPORTANT: I recommend using mysqli_ functions. because functions like mysql_ will be discontinued as you might see #.

    
27.02.2015 / 12:40
1
  

Notice: Undefined variable

says that the variable does not exist and the code displayed in the $id question is set after the query has been executed and you need it beforehand, as it will be used as an argument in SQL be sure to check if its value is valid, force a cast to integer.

Prefer mysql_query($sql) or die(mysqsl_error()) instead of mysql_query($sql); the first form will display the error message of the database if the query which can range from a syntax error to some other more serious problem.

>>#a última linha do while deveria estar aqui<<

$sql    = "SELECT * FROM cliente WHERE id = $id ";
$limite = mysql_query("$sql");

while ($sql = mysql_fetch_array($limite)){
    $nome       = $sql["nome"];
    $telefone   = $sql["telefone"];
    $id         = $_GET['id'];    <----- essa linha deveria estar antes da atribuição de $sql
}

The corrected code looks like this:

$id = (isset($_GET['id'])) ? $_GET['id'] : 0;

$sql    = "SELECT * FROM cliente WHERE id = $id ";
$limite = mysql_query($sql) or die(mysql_error());

while ($sql = mysql_fetch_array($limite)){
    $nome       = $sql["nome"];
    $telefone   = $sql["telefone"];
    $id         = $sql['id'];
}

If the code is from a new project it is strongly recommended to use mysqli or PDO. Recommended Reading:

Why should not we use functions of type mysql_ *?

MySQL vs PDO - Which is the most recommended to use?

    
27.02.2015 / 12:06