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

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

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"]]);

Getting the UUID() after INSERT with PHP

I am trying to get the UUID that had just been inserted.
This works in phpMyAdmin. But throws an error in PHP.
$insert = $conn->query("
SET #usr_uuid = uuidToBin(UUID());
INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( #usr_uuid );
SELECT HEX(#usr_uuid) AS usr_uuid;
");
However I get this error:
[errno] => 1064
[sqlstate] => 42000
[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 'INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( #u' at line 3
How do I go about fixing this?
You have two options to do it.
The first of all, are using transactions. For example:
$conn->begin_transaction();
$insert = $conn->query("SET #usr_uuid = uuidToBin(UUID());";
$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( #usr_uuid );";
$insert = $conn->query("SELECT HEX(#usr_uuid) AS usr_uuid;";
$conn->commit();
This option only works if you're using mysqli and innodb storage engine.
Second option, doing two queries:
$insert = $conn->query("INSERT INTO `users` (`users`.`usr_uuid`) VALUES ( uuidToBin(UUID() );";
$insert = $conn->query("SELECT HEX(usr_uuid) AS usr_uuid FROM `users`;";
This option can fall in the problem of having a new insert while you're doing it. But, if the table users have an ID, you can use mysql-insert-id() as suggested by #user3783243

PHP, MYSQL error?

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();

PHP PDO update statement fails

The below sql UPDATE statement returns an error but I'm unable to see why:
Failed to run query: 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 ')' at line 6
I already did a vardump of the array that I pass to bind the parameters but I see nothing unusual. The correct values are passed and I double checked for typos.
What I try to accomplish is to auto-generate a username based on firstname - lastname and user_id after insertion into the database.
Perhaps additional question: do you see any harm in that and if so, what is your suggestion?
I'm still in PHP learning phase.
Thanks.
...
//Autogenerate user_name based on first name, last name and user_id (auto-increment)
$query_username = "
UPDATE user_tbl
SET
user_name = :username
WHERE
user_id = :userid
)
";
// The parameter values
$query_params_username = array(
':username' => $_SESSION['user']['first_name'].".".$_SESSION['user']['last_name'].$_SESSION['user']['user_id'],
':userid' => $_SESSION['user']['user_id']
);
try
{
// Execute the query against the database
$stmt_username = $db->prepare($query_username);
$stmt_username->execute($query_params_username);
}
catch(PDOException $ex)
{
//Not to be used in production
die("Failed to run query: " . $ex->getMessage());
}
$_SESSION['user']['username'] = $_SESSION['user']['first_name'].".".$_SESSION['user']['last_name'].$_SESSION['user']['user_id'];
You had a closing parentheses after user_id = :userid
Try the following:
$query_username = "
UPDATE user_tbl
SET
user_name = :username
WHERE
user_id = :userid
";
Try doing this:
$query_username = "
UPDATE `user_tbl`
SET `user_name` = :username
WHERE `user_id` = :userid
";
There seems to be a lost ) character in your code.

Error with PDO INSERT statement

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 (?,?,?)"

Categories