Getting the UUID() after INSERT with PHP - 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

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

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

PDO insert not inserting

I am trying to insert using a prepare PDO statement but it doesn't seem to be working how I would like it to be. Heres my code:
$conn = new PDO('mysql:host=localhost;dbname=myDB', $username, $password);
$sql = "INSERT INTO posts (`text`,`name`) VALUES (:text,:username)";
$q = $conn->prepare($sql);
$q->bindParam(':text', $_GET['textField'], PDO::PARAM_STR);
$q->bindParam(':username', $_SESSION['myusername'], PDO::PARAM_STR);
$q->execute();
print_r($q->errorInfo());
The issue is that this doesn't do anything and I am not sure why, I am using following the guidelines here to help me do it.
Edit: When I use print_r I get the following MySQL error:
Array ( [0] => 42000 [1] => 1064 [2] => 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 ''text','name') VALUES ('a','user')' at line 1 )
Because text is a type in MySQL (look here), the query fails, because the syntax is wrong.
Add ticks around your text name and try again.
$sql = "INSERT INTO posts (text,name) VALUES (:text,:username)";
----
This is the error.

mysql error but works fine on mysql workbench

MySQL Query works fine using MySQL workbench but produces an error when I am executing it through PHP.
$sql = "INSERT INTO authors (submission_id, first_name, last_name, email, affiliation, country)
VALUES ('83', 'Chris', 'Hobbit', 'asfasf#gmail.com','Maryland', 'PK');
UPDATE articles
SET title='83',
abstract = 'Comp'
where article_id = '83';
";
$result = Model::getConnection()->query($sql) or die(mysqli_error(Model::getConnection()));
This is the error I get from PHP.
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 'UPDATE articles SET title='83', abstract = 'Comp' where
article_id = '8' at line 1
Yet this same SQL script works fine on MySQL workbench. Whats the problem?
You cannot execute multiple queries with mysql_query. Split your query into two (and get rid of the semicolons I think) and call mysql_query twice
Put your sql statement on two variables
$query = "INSERT INTO authors (submission_id, first_name, last_name, email, affiliation, country)
VALUES ('83', 'Chris', 'Hobbit', 'asfasf#gmail.com','Maryland', 'PK')";
$query1 = "UPDATE articles SET title='83', abstract = 'Comp' where article_id = '83'";
Then execute your queries:
$result = Model::getConnection()->query($query) or die(mysqli_error(Model::getConnection()));
$result = Model::getConnection()->query($query1) or die(mysqli_error(Model::getConnection()));

Error Uploading JPEG to MySQL

I am getting the error below when trying to upload an JPEG image to my MySQL database (Image is a BLOB):
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 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 id=57 (Image) VALUES ('ÿØÿà\0JFIF\0\0\0\0\0\0ÿá\0XExif\0\0MM\0*\0\0\' at line 1
I would really appreciate if you could tell me the problem in my code.
$sql = sprintf(
"INSERT INTO recipies WHERE id=$id (Image) VALUES ('%s')", mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])));
$results = mysql_query($sql) or die(mysql_error());
Its insert into or update where.
You might want this:
$sql = sprintf(
"UPDATE recipies SET Image = '%s' WHERE id=$id", mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])));
$results = mysql_query($sql) or die(mysql_error());
Maybe like this would be more correct syntax
$sql = sprintf(
"INSERT INTO recipies (Image) VALUES ('%s') ", mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])));
$results = mysql_query($sql) or die(mysql_error());
EDIT
It seems you're confused with SQL UPDATE syntax and MySQL particular mess. So correct syntax would be
INSERT
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
Or:
INSERT
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
So you friend is the MySQL::INSERT Syntax Manual.
Happy Querying!
Looks more like you are trying to update rather than insert
UPDATE recipes SET Image= ('%s') WHERE id = %d

Categories