Noreply Noreply Noreply Noreply - 3 months ago 11
SQL Question

Query Fails whenever I want to insert

Each time i submit a form through the code below, i get "Query failed" but i can't seems to find the 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 'order (pass, phone, fname, lname)
VALUES('test@yahoo.com','060606060606','James'' at line 1


Please someone help me.

<?php
//Start session
session_start();

//Include database connection details
require_once('../db/config.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}

//Sanitize the POST values
$pass = clean($_POST['pass']);
$phone = clean($_POST['phone']);
$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);

//Create INSERT query
$qry = "INSERT INTO order (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = @mysql_query($qry);

//Check whether the query was successful or not
if($result) {
header("location: success.php");
exit();
}else {
die("Query failed");
}
?>


I also tried to check if the user inputs are empty and it was okay but it doesn't insert.

Answer

The name 'order' is a MySQL reserved keyword.

Use backtick to enclose table name,

$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";

                      ^ enlcose table name with backtick

Backtick

enter image description here

Comments