Kyle Thomas
Kyle Thomas

Reputation: 11

You have an error in your SQL syntax PHP MySQL

I am making an order form using PHP that sends to my database but I am getting this error when I submit it:

Error: 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 'case, casel, processor) VALUES ('case1', 'casel1', 'processor1')' at line 1

here's my code

index.php:

<Form name ="pc" Method ="Post" ACTION ="cart.php">
<Input type = 'Radio' Name ='case' value= 'case1' />Case 1 <br />
<Input type = 'Radio' Name ='case' value= 'case2' />Case 2 <br />
<Input type = 'Radio' Name ='case' value= 'case3' />Case 3 <br /><br />

<Input type = 'Radio' Name ='casel' value= 'casel1' />Red<br />
<Input type = 'Radio' Name ='casel' value= 'casel2' />Green <br /><br />

<Input type = 'Radio' Name ='processor' value= 'processor1' />Intel&reg; Core&trade; i3 4130 3,4 GHz<br />
<Input type = 'Radio' Name ='processor' value= 'processor2' />Intel&reg; Core&trade; i5 4670K 3.40 Ghz <br />
<Input type = 'Radio' Name ='processor' value= 'processor3' />Intel&reg; Core&trade; i7 4770K 3.5 GHz <br />

<Input type = 'submit' Name ='submit' value= 'Submit' ><br />

</FORM>

cart.php

<?php
include("config.php");
if ( isset( $_POST['case'] ) && isset( $_POST['casel'] ) && isset( $_POST['processor'] ) ) {
$case = mysqli_real_escape_string($mysqli, $_POST['case']);
$casel = mysqli_real_escape_string($mysqli, $_POST['casel']);
$processor = mysqli_real_escape_string($mysqli, $_POST['processor']);

$sql="INSERT INTO products (case, casel, processor) 
    VALUES ('$case', '$casel', '$processor')";

if (!mysqli_query($mysqli,$sql)) {
  die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
} else {
echo "You didn't choose all the options! No record was added. Please choose one option from each category";
}
?>

Upvotes: 1

Views: 97

Answers (2)

Kevin
Kevin

Reputation: 41885

Remember that case is a reserved word and therefore should be inside backticks:

`case`
INSERT INTO products (`case`, casel, processor)

Here are the list of reserved words.

Note: A nice suggestion by fluffeh and is best to just use another column name instead.

By the way, since you're using mysqli_*, why not use prepared statements.

Upvotes: 4

David
David

Reputation: 218847

case is a reserved word in MySQL. In order to use syntax words as identifiers you need to enclose them in back ticks:

INSERT INTO `products` (`case`, `casel`, `processor`) 
VALUES ('$case', '$casel', '$processor')

In general:

  1. It's a good idea to explicitly enclose identifiers in back ticks anyway.
  2. It's not a good idea to use reserved words as identifiers.

Upvotes: 1

Related Questions