error in mySQL syntax - php

What's wrong in this SQL query ?!
if(isset($_POST['submit'])){
$name = $_POST['name'];
$author = $_POST['author'];
$pub = $_POST['pub'];
$sibn = $_POST['sibn'];
$year = $_POST['year'];
$version = $_POST['version'];
$desc = $_POST['desc'];
$selected_db = mysql_select_db("bookstore",$con);
$query = "INSERT INTO introducebook (name, author, pub, sibn, year, version, desc) VALUES ('{$name}', '{$author}', '{$pub}', '{$sibn}', {$year}, {$version}, '{$desc}');" ;
$result = mysql_query($query,$con);
if(!$result){die('could not perform query'.mysql_error());}
echo mysql_affected_rows();
}
?>
the error is (I pass all inputs test):
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 'desc) VALUES ('test', 'test', 'test', 'test', test, test, 'test')' at line 1

You need to escape reserved words in MySQL like desc with backticks
INSERT INTO introducebook (name, ..., `desc`) VALUES ...

to pass plain text you need brackets, this will be correct
INSERT INTO introducebook (`name`, `author`, `pub`, `sibn`, `year`, `version`, `desc`) VALUES ('{$name}', '{$author}', '{$pub}', '{$sibn}', '{$year}', '{$version}', '{$desc}')
and yes, you also need backticks.

Related

php INSERT into column with variable name MySQL

Been looking around all over forums and found similarish issues like MySQL INSERT INTO with PHP $variable . But it's not quite getting to my question.
I want to use variables for the columns but I get errors with my MySQL insert statement
$columns = 'id, test';
$sql_store = "INSERT into test ('$columns') VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_error());
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''id, Storlek') VALUES (NULL, 1)' at line 1
Thankful for help!
Problem : Your $columns variable is string which is not true.
Try like this,
PHP
$columns_array = array('id','test');
$columns = implode(",",$columns_array);
$sql_store = "INSERT into test (".$columns.") VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_error());
It looks like your SQL command, after variable substitution, looks like
INSERT into test ('id, Storlek') VALUES (NULL, 1) /* wrong! */
It needs to say this ...
INSERT into test (id, Storlek) VALUES (NULL, 1)
or maybe this...
INSERT into test (`id`, `Storlek`) VALUES (NULL, 1)
So get rid of the quote marks surrounding your $columns variable.

Error: You have an error in your SQL syntax; near ')' at line 1

Im having a problem with my PHP code, it says the error is "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 ')' at line 1"
It connects to the database ok as it echos "Database Connection Successful" but it dosnt insert the data into the database. This worked fine before, but now all of a sudden its stopped working. Can anyone help?
<?php
$username = "student";
$password = "student";
$hostname = "localhost";
$db = "details";
$link = new mysqli($hostname, $username, $password, $db);
if ($link->connect_errno)
printf("Connect failed: %s\n", $link->connect_error);
else
echo "Database Connection Successful \n";
echo nl2br("\n");
$Urgency = "Urgency";
if(isset($_POST['submit'])){
$TypeOfProblem = $_POST['problemtype'];
$ProblemDescription = $_POST['problem'];
$RoomNo = $_POST['roomno'];
$Problem = $_POST['reporter'];
$Urgency = $_POST['Urgency'];
$Date = $_POST['date'];
//Insert into Database
$sql = "INSERT INTO `details`.`problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`,`Date` ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
if (!mysqli_query($link, $sql))
{
die('Error: ' . mysqli_error($link));
}
echo "\n Thank you. Your Helpdesk Call has been submitted.";
mysqli_close($link);
}//////// end isset submit if ////////
?>
Thanks
Try using this, the problem is the single quote ` should be '
$sql = "INSERT INTO 'details'.'problem' ('Type Of Problem', 'Problem Description', 'RoomNo', 'Urgency', 'UserIDProblem','Date' ) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')"
Or try to set an echo $sql and test the query directly on de dbms
The date '$Problem', $Date)"; needs single-quotes '$Problem', '$Date')";
First, it is a good idea to leave out the database name:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)";
Are you sure, that your column names have spaces in it? I mean this would work, but this is not a good idea, I think.
I cannot find another problem in your query, maybe you should quote the date:
$sql = "INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', '$Date')";
Otherwise, please provide us with the full query:
die("INSERT INTO `problem` (`Type Of Problem`, `Problem Description`, `RoomNo`, `Urgency`, `UserIDProblem`, `Date`) VALUES ('$TypeOfProblem', '$ProblemDescription', '$RoomNo', '$Urgency', '$Problem', $Date)");
And you SHOULD notice, that your code is exploitable with SQL-Injections! Use mysqli_real_escape_string.
For debugging this, output the actual SQL text that is being submitted to the database, using echo or vardump e.g.
$sql = "INSERT INTO ...";
echo "SQL=" . $sql ;
That will show you the actual statement that's going to be submitted to the database, and you can usually debug the problem from there.
If date isn't a numeric, if it represents a DATE datatype or a string, the value needs to be enclosed in single quotes. Otherwise, it's likely going to be interpreted in a numeric context.
Note that this code appears to be vulnerable to SQL Injection, because it includes potentially unsafe values in the SQL text. Consider what happens when a value contains "special" characters, like a single quote, or comma.
Potentially unsafe values must be properly escaped. With mysqli, you can use the mysqli_real_escape_string function.
A better pattern is to use a prepared statement with bind placeholders.
As an example of what that would look like (before it's cluttered up with code to checks for errors from the return of the mysqli_ function calls)
$sql = "INSERT INTO `details`.`problem`
(`Type Of Problem`,`Problem Description`,`RoomNo`,`Urgency`,`UserIDProblem`,`Date`)
VALUES (?,?,?,?,?,?)";
$sth = mysqli_prepare($link,$sql);
if (!$sth) {
echo "error:" . mysqli_error($link);
)
mysqli_stmt_bind_param($sth,"ssssss"
,$TypeOfProblem,$ProblemDescription,$RoomNo,$Urgency,$Problem,$Date);
mysqli_stmt_execute($sth);

You have an error in your SQL syntax Mysql

My sql query is :
"INSERT INTO
order customer_id = $customer_id
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
I get the error
Notice: 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 customer_id =1,firstname ='kuldeep',lastname
='pathak',email ='kuldeep.pat' at line 1 Error No: 1064
You didnt understand how to write SQLs as it seems.
$sql = 'INSERT INTO `order` (customer_id, firstname, blablabla) VALUES ('.$custormer_id.','.$firstname.','.$blablabla.')';
Please look at some basic tutorials about SQL.
"INSERT INTO
`order` SET customer_id = " . $customer_id . "
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
Should be alright. Don´t forget to escape your data though.
Try
"INSERT INTO `Order` (customer_id, firstname, lastname, email, telephone, fax, ip, date_added, date_modified)
VALUES ($customer_id, '$firstname', '$lastname', '$email', '$telephone', '$fax', '$ip', NOW(), NOW())"
The right syntax is : INSERT INTO tablename (columns) VALUES (values);
If you're likely to have user submitted fields in the dataset or appostrophes or anything else that could cause problems for any reason you'd want something more like
$query = sprintf("INSERT INTO `table` (`Name`, `Email`, `AnotherField`) VALUES ('%s', '%s', '%s'",
mysql_real_escape_string( $_POST['Name'] ),
mysql_real_escape_string( $_POST['Email'] ),
mysql_real_escape_string( $_POST['AnotherField'] )
);
This will sanitise your inputs as well
Use prepared statement to avoiding sql injection.
$custormer_id = "2000";
$firstname = "first name";
$etc = "some other values";
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare("INSERT INTO order(customer_id, firstname, etc) VALUES (?, ?, ?)");
$stmt->bind_param('iss', $custormer_id, $firstname, $etc);
// first parameter is corresponding variable type of inserting values,eg i=interger, s=string
$stmt->execute();
$stmt->close();
http://php.net/manual/en/mysqli-stmt.bind-param.php

simple mysql query

$to = '555';
$from = '555';
$message = 'stuff';
mysql_query("INSERT INTO `convo` (to, from, content)
VALUES ( '$to', '$from', '$message' )") or die(mysql_error());
I can't figure out what is wrong with my above simple query. What obvious thing am I missing?
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 'to, from, content) VALUES ( '555', '555', 'stuff' )' at line 1
It looks like to is a MySQL reserved word.
Try
mysql_query("INSERT INTO `convo` (`to`, `from`, `content`) VALUES ( '$to', '$from', '$message' )") or die(mysql_error());
TO is a MySQL keyword. To fix this, wrap backticks around your to field.

Why isn't my MySQL database insertion working?

$author = $_SESSION['username'];
$subject = $_POST['subject'];
$body = $_POST['body'];
$branched = $_POST['branched'];
$time = time();
$branchedFrom = $_POST['parent'];
$id = $_POST['parent'];
$next = 0;
$previous = 0;
$branchedTo = 0;
mysql_query(
"INSERT INTO offtopic
VALUES(
'',
'$author',
'$subject',
'$body',
'$time',
'$next',
'$previous',
'$branchedFrom',
'$branchedTo'
");
I've tried it lots of times, even tried changing some stuff, but it doesn't save the info into the database.
The blank space at the begining is where the index is in the database.
The SESSION and POST stuff I'm pretty sure gets passed properly.
"INSERT INTO offtopic VALUES('', '$author', '$subject', '$body', '$time', '$next', '$previous', '$branchedFrom', '$branchedTo'"
Missing closing ‘)’ inside the string. Pick up the error message using mysql_error() and simple syntax errors like this should be obvious.
Also you have SQL injection security holes you could drive a bus through. You need to be calling mysql_real_escape_string() over each string value you concatenate into the string, or use mysqli parameterised queries.
Maybe it is because that your query missing which fields to insert
"INSERT INTO offtopic(field1, field2, etc....) VALUES('', '$author', '$subject', '$body', '$time', '$next', '$previous', '$branchedFrom', '$branchedTo'");

Categories