PHP, MYSQL error? - php

i recently started working with PHP and MYSQL, everything was going fine till I starter to get this error. Code works when I insert it into the query window at phpMyAdmin, but it doesnt work inside php code when i open it with a browser. Im already connected to database, so thats not the problem.
this is the error i get:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''fatmam' (user,
messageid) VALUES ('ayihan', '5')' at line 1
try
{
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO :tablename (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->bindValue(':tablename', $alicengiz);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error 1qqq. '. $e->getMessage();
include 'error.php';
exit();
}

No. You cannot prepare table names, field names and sql keywords.
Problem is, that prepare() will add single quotes around the input, but table names and field names require backticks around them when you want to escape them.
This time you need to escape manually (*real_escape_string doesn't help here):
$sql = 'INSERT INTO `'.addcslashes($alicengiz, "\\'").'` (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
P.s.: but really, this is a bad idea. I'd use a whitelist instead of escaping, because when $_POST["actor"]."m" isn't a table name, a PDOException will be thrown.

How about this?
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO messages (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->execute();

Related

MySQL Error in SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
I am trying to insert a sample blog post into my 'posts' table in MySQL (using PHP) however I receive a syntax error whenever a large character post is submitted. If I submit content of say 20 characters it works but something like 500 characters will throw the following error:
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 ''uid', 'username', 'p_date', 'title', 'content') VALUES('1','Mark Twain', '2014-' at line 1
The 'content' is to be inserted into the database via a varchar(1000) variable. The table is defined in mysql as:
CREATE TABLE posts
(
pid int NOT NULL AUTO_INCREMENT,
uid int NOT NULL,
username varchar(100) NOT NULL,
p_date date NOT NULL,
title varchar(225) NOT NULL,
content varchar(10000) NOT NULL,
PRIMARY KEY(pid),
FOREIGN KEY(uid) REFERENCES users(uid)
);
The actual content I am trying to submit is this:
Secondly, these missionaries would gradually, and without creating suspicion or exciting alarm, introduce a rudimentary cleanliness among the nobility, and from them it would work down to the people, if the priests could be kept quiet. This would undermine the Church. I mean would be a step toward that. Next, education -- next, freedom -- and then she would begin to crumble. It being my conviction that any Established Church is an established crime, an established slave-pen, I had no scruples, but was willing to assail it in any way or with any weapon that promised to hurt it. Why, in my own former day -- in remote centuries not yet stirring in the womb of time -- there were old Englishmen who imagined that they had been born in a free country: a "free" country with the Corporation Act and the Test still in force in it -- timbers propped against men's liberties and dishonored consciences to shore up an Established Anachronism with.
The insert statement for this is the following:
$sql = "INSERT INTO posts ('uid', 'username', 'p_date', 'title', 'content') VALUES('$uid','$uname', '$date', '$title', '$content')";
if(!mysql_query($sql,$con)){
echo "Oops! Something went wrong during the posting process. Please try again. ";
die('Error: ' . mysql_error($con));
header('Refresh: 1; URL=postingform.php');
}else{
// Now return the user to their post page
header('Refresh: 0; URL=postlist.php?uid='.$uid.'');
}
For some reason it is error-ing out during the INSERT process. The one thing strange I notice is that the date is cut off in the error. To call the date I am using. $date = date("Y-m-d");
I have used this same syntax before without issues.
****Edit
A few posters have pointed out that there are single quotations in my INSERT column statements. I have changed these to back tics and completely removed them but the error still results.
New Error:
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 's Court', 'Secondly, these missionaries would gradually, and without creating su' at line 1
There is something still wrong with my insert syntax but everything I am reading says it should be correct.
$sql = "INSERT INTO posts (`uid`, `username`, `p_date`, `title`, `content`) VALUES('$uid','$uname', '$p_date', '$title', '$content')";
Remove all the quotes in (for your columns)
('uid', 'username', 'p_date', 'title', 'content')
Those aren't the correct column identifiers
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
use
(uid, username, p_date, title, content)
or use backticks.
(`uid`, `username`, `p_date`, `title`, `content`)
However and as a quick FYI, backticks are mostly used for reserved keywords, or if a table/column contains spaces, hyphens.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
The error message was letting you know here
check the manual that corresponds to your MySQL server version for the right syntax to use near ''uid',
^--« right there
Notice the quote just before 'uid'? That's where the problem starts.
Edit:
Try the following using prepared statements and replace xxx with your own credentials.
This should take care of the quotes issue from your input values.
You will need to add the variables according to your inputs.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
$uid = ""; // replace with proper value
$uname = ""; // replace with proper value
$date = ""; // replace with proper value
$title = ""; // replace with proper value
$content = ""; // replace with proper value
$stmt = $conn->prepare("INSERT INTO posts (`uid`, `username`, `p_date`, `title`, `content`) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $uid, $uname, $date, $title, $content);
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else{
echo "Success";
}
$stmt->close(); // Statement
$conn->close(); // MySQLi
Footnotes:
In order to allow single and/or double quotes, based yourself on the following, while using the stripslashes() function.
$content = stripslashes($_POST['content']);
This will enter in DB properly:
Bob's sister was here today and said: "Bob, what lovely hair you have!".

PHP insert query gives syntax error but still writes into database

A query executes and writes into a database table and the field data is fetched and displayed in a WHILE loop so basically it works but I get a php error :
Error Inserting!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 \'1\' At Line 1
With line 1 being
<?php
I have tried playing around with commas and colons but I cannot get rid of the error. This is the query.
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
$query = mysql_query("INSERT INTO films VALUES ('0', '".($user)."','".($formValue["subject"])."',NOW(),'".($usercomments)."','".($formValue["rating"])."','action')");
if(mysql_query ($query, $Link)){
$message = "Thank you for your comments";
header("Location: films.php?message=$message");
}else{
$message = "Error Inserting!" . mysql_error();
header("Location: films.php?message=$message");
$query = "INSERT INTO films VALUES ('0', '$user','$formValue[subject]',NOW(),'$usercomments','$formValue[rating]','action')";
This may simplify the code and solve your error.

PHP Insert into MySQL Database using $_SESSION['user'] in WHERE clause

I'm trying to insert variables into my database where the user data comes from $_SESSION['user'].
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to Login");
}
$user = $_SESSION['user'];
~calculations done~
$query = "INSERT INTO db (role,rolesub) VALUES ('$varRole','$varRoleSub') WHERE user = $user";
$query_params = array(
':role' => $varRole,
':roleSub' => $varRoleSub
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query 3: " . $ex->getMessage());
}
I keep getting this error:
Failed to run query 3: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'WHERE user = Array' at line 1
I can not see where my WHERE clause is failing on me.
Any help would be greatly appreciated!!!
You cannot have a WHERE clause in an INSERT statement.
You're either looking for:
UDPATE db SET role = '$varRole', rolesub = '$varRoleSub' WHERE user = $user
Or:
INSERT INTO db (role,rolesub,user) VALUES ('$varRole','$varRoleSub',$user)
Or if you're feeling extra saucy, and user is your PK:
INSERT INTO db (role,rolesub,user) VALUES ('$varRole','$varRoleSub',$user)
ON DUPLICATE KEY UPDATE role = '$varRole', rolesub = '$varRoleSub'
INSERT queries do not and can not have a WHERE clause. This is the cause of the MySQL syntax error. If you need to insert based on some condition, you need to do that logic before the INSERT query.
If you want to do an UPDATE query then you can use the WHERE clause, however, the MySQL error shows $_SESSION['user'] is an array, which can't be put directly into SQL, so you'll need to access one of its elements such as $_SESSION['user']['id'].
First of all, IF you could have a WHERE in the same query as an INSERT, variables need to be separate from the string (outside of the quotes). BUT you CANT put a where clause into an INSERT.
So you could change this line:
$query = "INSERT INTO db (role,rolesub) VALUES ('$varRole','$varRoleSub') WHERE user = $user";
to:
$query = "INSERT INTO db (role,rolesub) VALUES (" . $varRole . ", " . $varRoleSub . ")";

SQL syntax error, I just can't see it

Here is my code:
<?php
$con = mysql_connect("localhost","solidarity","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$sql="INSERT INTO show_reviews (username, date, content, show) VALUES (".addslashes($_POST[username]).",".addslashes($_POST[date]).",".addslashes($_POST[content]).",".addslashes($_POST[show]).")";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
So I have used fsprint and now I have just used the w3schools code and this is my output with both pieces of code:
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 'show) VALUES (Solidarity, 17:02 - Wed, 1st Aug 2012,Testing,kr1971)' at line 1
I use a very similar syntax for a commenting system and do not have this problem. If it helps also, I have tried on a local sql server and remote also, still no luck.
Please help me :(.
Put the values inside of single quotes:
$sql=" INSERT INTO show_reviews (username, date, content, show)
VALUES ('".addslashes($_POST[username])."','".addslashes($_POST[date])."','".addslashes($_POST[content])."','".addslashes($_POST[show])."')";
Additionally, as others have said show is a reserved keyword in MySQL. You can see the full list of reserved keywords for MySQL 5.5 at http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You can quote reserved words using the backtick in order to be able to use them:
INSERT INTO show_reviews (username, date, content, `show`)
Quoting Identifiers:
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
And finally, to summarize the comments about using addslashes() for escaping. I will let Chris Shiflett explain why it is bad: http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string
You really should be jumping aboard the prepared statements/parameterized queries bandwagon with PDO or at minimum, MySQLi. Here is an example of how you query could look:
$dbh = new PDO($connection_string);
$sql = "INSERT INTO show_reviews (username, date, content, show) VALUES (?, ?, ?, ?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_POST['username'],
$_POST['date'],
$_POST['content'],
$_POST['show']
));
while ($row = $stmt->fetch()) {
print_r($row);
}
This is purely an example, it is still a good idea to do your sanitizing of $_POST variables and do your best to ensure the data you received is exactly what you were trying to get. These prepared statements take care of escaping for you properly and, if using PDO, the proper way for your specific database engine.
show is a mysql keyword. So, it cannot be a column name. You will have to escape it, if you want to use show as a column name.
show is a reserved keyword in SQL. You have to enclose it with backticks to use as a column name.
Please use this query
$sql= 'INSERT INTO show_reviews (username, date, content, show)
VALUES ("'.addslashes($_POST[username]).'",".'addslashes($_POST[date]).'","'.addslashes($_POST[content]).'","'.addslashes($_POST[show]).'")';
Your values need to be wrapped in quotes.
$sql="INSERT INTO show_reviews (username, date, content, show) VALUES ('".addslashes($_POST[username])."','".addslashes($_POST[date])."','".addslashes($_POST[content])."','".addslashes($_POST[show])."')";
Also show is a reserved word, so you need to encase it in backticks.
To elaborate on Sebastian's comment, use PDO: it is more resilient (or immune?) to SQL injection attacks. The code will look something like this:
<?php
try {
$handle = new PDO('mysql:host=localhost;dbname=myDatabaseName', 'username','password');
$prepared = $handle->prepare("INSERT INTO show_reviews (username, date, content, show) VALUES (?,?,?,?)");
if($prepared->execute(array($_POST['username'], $_POST['date'], $_POST['content'], $_POST['show']))) {
echo "1 record inserted...";
}else {
echo "insert failed...";
}
}catch(PDOException $ex) {
// error connecting to database
}
?>

Cannot submit form to database

I am working with WordPress and I made a form in the admin section. I am trying to submit it to another database (not the default wp one) so I switch databases successfully and do an insert query but I keep getting an error.
This is my code:
$selected = mysql_select_db( 'petracms', $serverAccess );
if (!$selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$query = "INSERT INTO `petra_customers` (`FirstName`, `LastName`, `Email`, `Phone`) VALUES ($fName, $lName, $email, $phone)";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
I keep getting this error:
Invalid query: 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 '#gmail.com, 5859475566)' at line 1
This is my input: (Adam, Page, bofumme#gmail.com, 5859475566)
I have no idea what I am doing wrong
Values in INSERT statements need to be enclosed in quotes (except "numbers"):
INSERT INTO `foo` (`a`,`b`,`c`) VALUES("foo","bar",1)
This is how you would (safely) construct a variable for use in query string interpolation (this is frowned upon, though):
$email = sprintf('"%s"', mysql_real_escape_string($_POST['email']));
$query = "INSERT INTO `foo` (`email`) VALUES($email)";
A more elegant way (and far more secure, too), is to use prepared statements (example uses PDO):
# Prepare the statement
$sth = $dbh->prepare('INSERT INTO `foo` (`email`) VALUES(:email)');
# Substitute placeholders in query and execute it
$sth->execute(array(
'email' => $_POST['email']
));
I guess you forgot to add quotes ' to your INSERT query. Check out any tutorial on the web on how to do simple inserts, eg here: http://www.w3schools.com/php/php_mysql_insert.asp

Categories