I'm 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; VALUES ('Refined Sugar', '2', '') 'at line 1
I'm 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; 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>
Field names do not need and can not contain quotes, only VALUES
:
$query = "
INSERT INTO orcamento (nome, quantidade, codigo)
VALUES ('$nome', '$quantidade', '')";
If you need to use a reserved name, then use backticks operator '
instead of single quotes:
$query = "
INSERT INTO orcamento ('nome', 'quantidade', 'codigo')
VALUES ('$nome', '$quantidade', '')";
You can also do the following:
$query = "INSERT INTO orcamento SET nome='$nome', quantidade='$quantidade' ";
Do not put the code field if it is auto increment.
Do not use double quotation marks in the field names but rather '
When some field has the name as a reserved word like for example a field of description of a product to be called only ''
, in this case the use of crase is obligatory.
Your insert should look like this
INSERT INTO orcamento('nome', 'quantidade','codigo') VALUES ('$nome', '$quantidade','')";
Remember that the mysql_ * functions have been discontinued, it is highly recommended that you use the PDO or mysqli and preparedStatements to avoid sql injection.
I recommend reading this question