"You have an error in your SQL syntax"

-1

I'm getting this error while accessing the page:

  

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

<html>
<head>
    <title>Extraindo dados de um BD</title>
</head>
<body>

<dl>

<?php 
    //Conectando com o BD...
    mysql_connect($host,$username,$pass) or die(mysql_error());
    //Selecionando o BD...
    mysql_select_db($db_name) or die(mysql_error());
    // Extrair dados de acordo com o id passado no URL
    $strSQL = "SELECT * FROM People WHERE id=" . $_GET["id"];
    $rs = mysql_query($strSQL) or die(mysql_error());

    // Loop pelo recordset $rs
    while($row = mysql_fetch_array($rs)) {
        // Escreve dados da pessoa
        echo "<dt>Nome:</dt><dd>" . $row["FirstName"] . " " . $row["LastName"] . "</dd>";
        echo "<dt>Telefone:</dt><dd>" . $row["Phone"] . "</dd>";
        echo "<dt>Data de nascimento:</dt><dd>" . $row["BirthDate"] . "</dd>";
    }

    //Encerra a conexão
    mysql_close();
 ?>

</dl>
<p><a href="list.php">Go back to name's list</a></p>

and the other code is:

<html>
<head>
<title>Extraindo dados de um BD</title>
</head>
<body>
<?php 

    //Catalogo de enderecos simples

    //Conectando com o BD...
    mysql_connect($host,$username,$pass) or die(mysql_error());
    //Selecionando o BD...
    mysql_select_db($db_name) or die(mysql_error());
    //Digitando a query SQL...
    $strSQL = "SELECT * FROM People ORDER BY FirstName DESC";
    //Executando a query e colocando seu resultado num Record Set, no caso $rs:
    $rs = mysql_query($strSQL);
    //Fazendo um loop pelo Record Set:
    while ($row = mysql_fetch_array($rs)) {
        //Nome da pessoa
        $strName = $row['FirstName'] . " " . $row['LastName'];
        // Cria link para o arquivo person.php com um valor de id no URL
        $strLink = "<a href = 'person.php?id = " . $row['id'] . "'>" . $strName . "</a>";
         // Lista de links
        echo "<li>" . $strLink . "</li>";
    }

    mysql_close();
 ?>

    
asked by anonymous 04.12.2014 / 22:55

1 answer

1

The error says that your sql query is not well formatted, probably it happens only the first time the page is accessed. Because $_GET['id'] does not exist on the first call. Add a if and check that $_GET has some value, if you run the query, if you do not display a message ex: no records:

<?php 
    if(isset($_GET['id']) && !empty($_GET['id']){
       mysql_connect($host,$username,$pass) or die(mysql_error());
       mysql_select_db($db_name) or die(mysql_error());
       $id = (int)$_GET["id"]; //força o valor para inteiro caso seja possivel 
       $strSQL = "SELECT * FROM People WHERE id=". $id;
       $rs = mysql_query($strSQL) or die(mysql_error());
    }else{
       echo 'sem registros';
    }

Recommended reading:

Why should not we use functions of type mysql_ *?

isset - php.net

empty - php.net

    
05.12.2014 / 01:28