Error: "You have an error in your SQL syntax"

Asked

Viewed 34,761 times

3

I am getting the following error when time to perform a query to insert data into a table in the database:

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 ''name','quantity','code') VALUES ('Refined Sugar', '2','')' at line 1

My code:

<html>
<head>
    <title>Teste</title>
    <meta charset="UTF-8"/>
</head>
<body>
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbnm = "carrinho";

$con = mysql_connect($host, $user, $pass) or die (mysql_error());
$banco = mysql_select_db($dbnm,$con) or die(mysql_error());
if (!$banco)
    die ("Erro de conexão com banco de dados, o seguinte erro ocorreu -> <br> ".mysql_error());

$nome = 'Açúcar Refinado';
$quantidade = '2';

$query = "INSERT INTO orcamento('nome','quantidade','codigo') 
VALUES ('$nome', '$quantidade','')";

mysql_query($query,$con) or die ("Não foi Possivel inserir <br>". mysql_error());

echo "Seu cadastro foi realizado com sucesso!<br>Agradecemos a atenção.";
?>
</body>
</html>

3 answers

9

Field names do not need or can carry quotes, only VALUES:

$query = "
INSERT INTO orcamento (nome, quantidade, codigo) 
VALUES ('$nome', '$quantidade', '')";

If you need to use a reserved name, then use Operator backticks ` instead of single quotes:

$query = "
INSERT INTO orcamento (`nome`, `quantidade`, `codigo`) 
VALUES ('$nome', '$quantidade', '')";
  • Vlw, thank you for your reply.

5

You don’t use quotes ' simple in the names of the fields and yes crase ``

When some field has the name as a reserved word like for example a product’s Decription field be called only desc, in this case the use of crase is mandatory.

Your Insert should look like this

INSERT INTO orcamento(`nome`, `quantidade`,`codigo`) VALUES ('$nome', '$quantidade','')";

Remember that mysql_* functions have been discontinued it is highly recommended that you use PDO or mysqli and preparedStatements to avoid sql Injection.

I recommend reading this question

  • Solved, thank you very much!

5

You can also do as follows:

$query = "INSERT INTO orcamento SET nome='$nome', quantidade='$quantidade' ";

Do not place the code field if it is auto increment.

Browser other questions tagged

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