Error with PDO INSERT statement - php

I've been staring at this statement and its error message for about half an hour without being able to see what's wrong with it.
Here is my statement:
try{
$stmt = $conn->prepare("INSERT INTO dashboardsearchdates (userID, from, to) VALUES (?,?,?)");
$result = $stmt->execute(array($userID, $frmFrom, $frmTo));
}
catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
$queryString = $stmt->queryString;
$page = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
mail(ADMIN_EMAIL, 'SQL ERROR: ' . $page, 'Error Page: ' . $page . ' // Error: ' . $e->getMessage() . ' // Query String: ' . $queryString);
}
And this is the table structure i'm trying to insert the values into:
Table structure for table `dashboardsearchdates`
--
CREATE TABLE IF NOT EXISTS `dashboardsearchdates` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(11) NOT NULL,
`from` datetime NOT NULL,
`to` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Here is the exception i'm seeing:
ERROR: 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 'from, to) VALUES ('9','2012-12-12','2013-01-01')' at line 1
As you can see from the exception, the three values i'm trying to insert into the DB are present at runtime (otherwise they wouldn't be shown in the exception)
Things i've tried:
I have other queries using $conn above this in the code, so i know $conn is present and working.
I've rewritten the statement as so:
$stmt = $conn->prepare("INSERT INTO dashboardsearchdates (userID, from, to) VALUES (:userID,:from,:to)");
$stmt->bindParam(':userID', $userID);
$stmt->bindParam(':from', $frmFrom);
$stmt->bindParam(':to', $frmTo);
$result = $stmt->execute();
I've tried backquotes around the table name, all the field names, only the integer field name, and only the date fields.. All with the same error message shown above - as far as i can see there's nothing wrong with the construction of the SQL.
I'd be really grateful for any suggestions of other things to try.

'from' is a key word you need to enclose it in backticks
`from`
'to' is a keyword as well
Note: this problem has nothing to do with PDO. A developer ought to test their query in mysql client before starting for build it dynamically.

From is a reserved word for SQL, so if you want to use it you have to use before and after back ticks.
INSERT INTO dashboardsearchdates (userID, `from`, to) VALUES (?,?,?)"

Related

PHP PDO REPLACE works in phpadmin but not in php

Trying to update the record (timestamp) if it exists or insert a new record if it doesn't exist.
Table is:
id = int 12 primary key, auto increment
userid = int 12
viewerid = int 12
viewDateTime = TIMESTAMP
This sql works in phpmyadmin but not in php
SELECT #id := id FROM `profileViews` WHERE `userid` = 31 AND `viewerid` = 30 LIMIT 1;
REPLACE INTO `profileViews`(id, `userid`, `viewerid`, `viewDateTime`)
VALUES (#id, 31, 30, now());
Here is the php version:
$INSERTViewSQL = "SELECT #id := id FROM `profileViews` WHERE `userid` = ? AND `viewerid` = ? LIMIT 1;
REPLACE INTO `profileViews`(id, `userid`, `viewerid`, `viewDateTime`)
VALUES (#id, ?, ?, now());";
try{
$DBConnection->prepare($INSERTViewSQL)->execute([$profileid, $_SESSION["id"], $profileid, $_SESSION["id"]]);
} catch(PDOException $e) {
file_put_contents($ErrorLogFileForPDO, 'update view : ' .$e->getMessage()."\n", FILE_APPEND);
}
Here is the error message:
update view : 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 'REPLACE INTO profileViews(id, userid, viewerid, viewDateTime)
VALUES (#i' at line 2
Thanks‼️
MySQL document says:
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).
So you need to fetch id value first, execute replace statement after that.
$stmt = $DBConnection
->prepare("SELECT id FROM ...");
$stmt->execute([$profileid, $_SESSION["id"]]);
$id = $stmt->fetchColumn();
$DBConnection
->prepare("REPLACE INTO ...");
->execute([$id, $profileid, $_SESSION["id"]]);

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!".

Something mysterious with PHP, PDO (probably not MySQL) SQLSTATE[42000](1064)

Something really strange is happening with the following query, when I try it on PhpMyAdmin it works flawlessly, but when I run it from PHP I get the following error.
I'm using PDO...
Maybe I'm blind, or maybe it's the fact that I've been working for so many hours, the thing is that I don't see anything wrong.
Error message
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 'INSERT INTO downsync (id, signature) VALUES ('1','b01c0d494aca29162d815346d0de5f' at line 2
The query... Highlighted version (http://pastebin.com/dkYRJCS1)
CREATE TEMPORARY TABLE IF NOT EXISTS downsync (`id` int(11) NOT NULL, `signature` VARCHAR(250) NOT NULL);
INSERT INTO downsync (id, signature) VALUES ('1','b01c0d494aca29162d815346d0de5fd3'),
('2','bc3d25e2a527a20779914f5c7dc181e5'),
('3','89bc5c4e013aea0b28e61561ada05770'),
('4','8ce1daecd2a20c23b1c3344dac07880a'),
('6','0a679dc54c3654933329fc7bbf01c401'),
('7','40e6af407141ab652a4cad01f2f30a05'),
('9','331e12d5136a24483a12a0610f0ecd80'),
('10','570e68fd6cccd91aaf1173845739d9ab'),
('11','603e6a77d56a21597563119b319aaf67'),
('12','7649d3e71223cf543994189fe4053670'),
('14','825d0a186fd938eb0417a1bf3e30d9c3'),
('15','4a66d12f56b9ff93332b7c841c986751'),
('16','7de9d51199cdd316d869510fe97f584c'),
('17','7ef58d702ea43e02398f3f983c8292f3'),
('18','430c864532d3352691c76a9517f54498'),
('19','11a0e5cd2497166b0f85f3e318e6ff2f'),
('20','9771222ec70e55722e2582f3238f4e44'),
('21','bffd7ce7a4b59bb439a98ae898e3a703'),
('22','daf986c8682f856b1828cd4b1c8888b7'),
('23','3fecc9e7e6291b0ea12bbe60c46d361b'),
('24','41e49696971f00648f3a3e5971ea765d'),
('25','0f58aa0ffa8fd6efeb3bb4ccee590d44');
SELECT `downsync.id`,
IF(MD5(CONCAT(
customers.id,
IFNULL(customers.full_name,0),
IFNULL(customers.phone,0),
IFNULL(customers.mobile,0),
IFNULL(customers.email,0),
IFNULL(customers.address,0),
IFNULL(customers.zipcode,0),
IFNULL(customers.city,0),
IFNULL(customers.state,0),
IFNULL(customers.country,0),
IFNULL(customers.gmaps_addrs,0)
)) = signature,1,0) as unchanged
FROM downsync
INNER JOIN customers ON downsync.id = customers.id;
The Code...
"Here's the PHP source, I'm a little slow right now, sorry for forgetting it... ;)"
$query = "
CREATE TEMPORARY TABLE IF NOT EXISTS downsync (`id` int(11) NOT NULL, `signature` VARCHAR(250) NOT NULL);
INSERT INTO downsync (id, signature) VALUES ('1','b01c0d494aca29162d815346d0de5fd3'),
('2','bc3d25e2a527a20779914f5c7dc181e5'),
('3','89bc5c4e013aea0b28e61561ada05770'),
('4','8ce1daecd2a20c23b1c3344dac07880a'),
('6','0a679dc54c3654933329fc7bbf01c401'),
('7','40e6af407141ab652a4cad01f2f30a05'),
('9','331e12d5136a24483a12a0610f0ecd80'),
('10','570e68fd6cccd91aaf1173845739d9ab'),
('11','603e6a77d56a21597563119b319aaf67'),
('12','7649d3e71223cf543994189fe4053670'),
('14','825d0a186fd938eb0417a1bf3e30d9c3'),
('15','4a66d12f56b9ff93332b7c841c986751'),
('16','7de9d51199cdd316d869510fe97f584c'),
('17','7ef58d702ea43e02398f3f983c8292f3'),
('18','430c864532d3352691c76a9517f54498'),
('19','11a0e5cd2497166b0f85f3e318e6ff2f'),
('20','9771222ec70e55722e2582f3238f4e44'),
('21','bffd7ce7a4b59bb439a98ae898e3a703'),
('22','daf986c8682f856b1828cd4b1c8888b7'),
('23','3fecc9e7e6291b0ea12bbe60c46d361b'),
('24','41e49696971f00648f3a3e5971ea765d'),
('25','0f58aa0ffa8fd6efeb3bb4ccee590d44');
SELECT `downsync.id`,
IF(MD5(CONCAT(
customer.id,
IFNULL(customer.name,0),
IFNULL(customer.email,0),
IFNULL(customer.gmaps_addrs,0)
)) = signature,1,0) as unchanged
FROM downsync
INNER JOIN commerces ON downsync.id = commerces.id;
";
echo '<pre>';var_dump($query);echo '</pre>';
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->query($query);
//> I tried to commet this and use the query method but it didn't work
//$stmt->setFetchMode(PDO::FETCH_ASSOC);
//$stmt->execute($params);
$results = $stmt->fetchAll();
}
catch(Exception $e) {
echo 'Exeption:<pre>';var_dump($e->getMessage());echo '</pre><hr>';
echo 'Error Obj.: <pre>';var_dump($e);echo '</pre>';
}
Solution:
Separating the 3 queries did the trick
$query1 = 'CREATE TEMPORARY TABLE IF NOT EXISTS....';
$query2 = 'INSERT INTO downsync...';
$query3 = 'SELECT downsync.id...';
...
$stmt = $pdo->query($query);
$stmt = $pdo->query($query2);
$stmt = $pdo->query($query3);
Thanks #lafor, #Prava - Mindfire Solutions, #Ravinder

Error in SQL INSERT INTO query

I have following code written in PHP:
$q = mysql_query("INSERT INTO logowania ('user','udane','ip') VALUES ($uid,0,'".ip()."')"); echo mysql_error();
Values of $uid and ip() are correct, you can trust me.
Structure of logowania table:
1 idlogowania int(11)
2 user int(11)
3 udane tinyint(1)
4 data timestamp on update CURRENT_TIMESTAMP CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
5 ip text utf8_polish_ci
I don't know where is the error in the statement. MySQL gives:
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 ''user','udane','ip') VALUES (1,0,'79.184.7.44')' at line 1
I tried to debug that, but without successful ending. I know that could be very simple mistake, but human's vision isn't infallible...
Use back ticks for column name,otherwise they are treated as strings.
(`user`,`udane`,`ip`)
Take out '' from the column names.
$q = mysql_query("INSERT INTO logowania ('user','udane','ip') VALUES ($uid,0,'".ip()."')"); echo mysql_error();
should be
$q = mysql_query("INSERT INTO logowania (user,udane,ip) VALUES ($uid,0,'".ip()."')"); echo mysql_error();
OR use back-tics for the col names
$q = mysql_query("INSERT INTO logowania (`user`,`udane`,`ip`) VALUES ($uid,0,'".ip()."')"); echo mysql_error();
Alternative version:
$q = mysql_query("INSERT INTO logowania SET `user` = '" . $uid . "', `udane` = 0, `ip` = '" . ip() . "'"); echo mysql_error();

mysql_insert_id not working

Apologies for the vague title, here's my problem:
The goal of my code is to insert a new row into a table that has an auto-increment field. After the insert, I want to get the value of the auto-increment field that has just been generated.
Here's my table defintion:
CREATE TABLE `EventComments` (
`CommentID` int(11) NOT NULL AUTO_INCREMENT,
`EventID` int(11) NOT NULL,
`OwnerID` int(11) NOT NULL,
`Comment` varchar(512) NOT NULL,
`DateTime` datetime NOT NULL,
PRIMARY KEY (`CommentID`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;
I'm trying to get the value of the CommentID field.
So, here is the php code that issues the insert query and then attempts to get the CommentID value.
<?php
session_start();
ob_start();
include_once 'lib/functions.php';
if(isset($_SESSION['uid'])) {
$eventID = $_GET['evid'];
$ownerID = $_SESSION['uid'];
$comment = $_GET['comment'];
$comment = trim($comment);
$dateTime = date('Y-m-d H:i:s');
$db_connection = database_connect();
if($eventID != null && !empty($comment)) {
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";
mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));
$id = mysql_insert_id();
$commentHtml = generateCommentFromData($db_connection, $ownerID, $comment, $dateTime, $id);
echo $commentHtml;
}
}
ob_end_flush();
?>
This code issues the following error in the php logs:
mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established...
I also tried explicitly passing the database link. But that gives the following error:
mysql_insert_id(): supplied argument is not a valid MySQL-Link resource...
As a final note, the insert query works. It is definitely inserting a new row with the expected data!
Any insight here would be appreciated!
Thanks
You are using the mysqli extension to connect and run your query, but then you use the mysql (notice the lack of i at the end) extension to get your inserted id, that can't work. While they are both extensions that provide access to mysql, they are also two very different libraries and can't share a connection between each other.
For the record, mysqli is the one you should be using, mysql is the "old" version that does not support new features of mysql >= 4.1
In other words, the solution is to use mysqli_insert_id()
Also, please escape your parameters properly, you can't put the content of $_GET and $_POST variables inside your query unsecured like that. At the very least use mysqli_real_escape_string()
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . mysqli_real_escape_string($eventID)." [...]
For more infos on this, have a look to the numerous questions on this subject, for example this one: How to properly escape a string via PHP and mysql
You probably want to use the mysqli extension equivalent: mysqli_insert_id()
It might work as it is by passing the connection resource but even if it did, it's not good to mix methods from two separate connection classes:
$id = mysql_insert_id($db_connection);
DATETIME is a Data Type in MySQL that's why INSERT query is not working. Use backtick ` instead.
$query = "INSERT INTO meetup.EventComments (`EventID`, `OwnerID`, `Comment`, `DateTime`)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";

Categories