Syntax error when running multiple queries through mysqli - php

I‘m trying to move rows from one table to another, when they‘re older than 6 hours. While my code works perfectly in PMA, I just get an error via PHP.
This is my PHP code:
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$timestamp6h = time() - 21600;
$sql="BEGIN;
INSERT INTO archiv6h SELECT * FROM links WHERE tweettimestamp < $timestamp6h
ON DUPLICATE KEY UPDATE archiv6h.tweetscount= archiv6h.tweetscount+ links.tweetscount, archiv6h.followerscount= archiv6h.followerscount + links.followerscount, archiv6h.tweettimestamp= archiv6h.tweettimestamp + links.tweettimestamp;
DELETE FROM links WHERE tweettimestamp < $timestamp6h;
COMMIT;";
if (!mysqli_query($conn, $sql)) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
$result = mysqli_query($conn, $sql);
$conn->close();
I then get the following error message:
Errormessage:
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 archiv6h SELECT * FROM links WHERE tweettimestamp < 1521038638 ON ' at line 1
When I use this as a query in PMA, it works like intended:
BEGIN;
INSERT INTO archiv6h SELECT * FROM `links` WHERE tweettimestamp < 1521038638
ON DUPLICATE KEY UPDATE archiv6h.tweetscount= archiv6h.tweetscount+ links.tweetscount, archiv6h.followerscount= archiv6h.followerscount + links.followerscount, archiv6h.tweettimestamp= archiv6h.tweettimestamp + links.tweettimestamp;
DELETE FROM `links` WHERE tweettimestamp < 1521038638;
COMMIT;
Has someone an idea how to get the query running in PHP?

With BEGIN; and COMMIT; that are four statements. You can't run multiple statements in one mysqli_query() call. If you need a transaction, use mysqli::begin_transaction(). And only use one statement per mysqli_query() call:
$conn->begin_transaction();
$conn->query("INSERT ...");
$conn->query("DELETE ...");
$conn->commit();
Note that you should also configure mysqli to throw exceptions. I would write your script the following way:
// set connection variables
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$timestamp6h = time() - 21600;
$conn->begin_transaction();
$conn->query("
INSERT INTO archiv6h SELECT * FROM links WHERE tweettimestamp < $timestamp6h
ON DUPLICATE KEY UPDATE
archiv6h.tweetscount = archiv6h.tweetscount + links.tweetscount,
archiv6h.followerscount = archiv6h.followerscount + links.followerscount,
archiv6h.tweettimestamp = archiv6h.tweettimestamp + links.tweettimestamp
");
$conn->query("DELETE FROM links WHERE tweettimestamp < $timestamp6h");
$conn->commit();
If anything fails, $conn->commit(); will never be executed, and the script will output an error message. Threre is not even a need to close the conection, since it will be closed when the script ends.

Related

Inconsistency of MySQL syntax errors depending on whether query made from command line or mysqli_connect

A simple MySQL query is returning a syntax error over mysqli_connect, but the identical, copy-pasted query is successful in both the CLI and phpMyAdmin.
Consider this example for MySQL 8.0:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "USE aTable; INSERT INTO aTable (`aColumn`) VALUES ('aValue');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
When the PHP runs it prints an error:
USE aTable; INSERT INTO aTable (aColumn) VALUES ('aValue');
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 'INSERT INTO aTable (aColumn) VALUES ('aValue')' at line 1
However when the same query is pasted into phpMyAdmin it tells me:
1 row inserted.
Inserted row id: 6 (Query took 0.0063 seconds.)
USE aTable; INSERT INTO aTable (aColumn) VALUES ('aValue');
Why are they different?
Remove the USE from the PHP code because the database is already selected in the mysqli_connect method.
$sql = "USE aTable; INSERT INTO aTable (`aColumn`) VALUES ('aValue');";
Should be:
$sql = "INSERT INTO aTable (`aColumn`) VALUES ('aValue');";
Also, make sure that you're not using the database name in the INSERT query.

How to get the value of expression from LAST_INSERT_ID(`my_column`+1)?

DB Type: MariaDB
Table Engine: InnoDB
I have a table where inside it has a column with a value which is being incremented (not auto, no inserting happens in this table)
When I run the following SQL query in phpMyAdmin it works just fine as it should:
UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc';
SELECT LAST_INSERT_ID();
The above returns me the last value for the my_column table when the query happened. This query was taken directly from the mysql docs on locking: https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html (to the bottom) and this seems to be the recommended way of working with counters when you don't want it to be affected by other connections.
My PDO:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc';
SELECT LAST_INSERT_ID();";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
$result = $stmt->fetchColumn(); // causes general error
$result = $stmt->fetch(PDO::FETCH_ASSOC);// causes general error
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Exact error SQLSTATE[HY000]: General error, If I remove the lines where I try to get the result, it updates the column, but I still do not have a return result... how do I perform that update query and get the select result all in one go like I do when I run it in phpMyAdmin? This all needs to happen in one go as specified by the MySQL docs so I don't have issues where two connections might get the same counter.
There is no need to perform SELECT LAST_INSERT_ID();. PDO will save that value automatically for you and you can get it out of PDO.
Simply do this:
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4", $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$sql = "UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc'";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
$newID = $conn->lastInsertId();
lastInsertId() will give you the value of the argument evaluated by LAST_INSERT_ID().

MySQLi cannot create new table in PHP

I'm getting frustrated with running basic SQL statements in PHP. I keep running into syntax errors that ask me to refer to the current server version of MySQL.
I'm trying to run the follow SQL query:
CREATE DATABASE mc_todo_app;
use mc_todo_app;
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT,
task VARCHAR(255) NOT NULL,
completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
In PHP I then try to run this script.
require "config.php";
// Create connection
$conn = mysqli_connect($host, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = file_get_contents('data/init.sql');
$result = mysqli_query($conn, $sql);
if (false === $result) {
printf("Error: %s\n", mysqli_error($conn));
} else {
echo "DB and Table successfully created!";
}
mysqli_close($conn);
This produces the following error message:
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 'use mc_todo_app;
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT,
tas' at line 3
Here are the details of my Database server:
I'm even trying basic Table creation statements from W3Schools without success.
What am I doing wrong?
mysqli_query() can only execute one query at a time, while you are attempting to execute multiple queries. You can use mysqli_multi_query() instead.
$sql = file_get_contents('data/init.sql');
$result = mysqli_multi_query($conn, $sql);
http://php.net/mysqli.multi-query

Escape strings/ inserting in php script

I'm trying to finish a script that connects to two databases, each on a different server, and preforms an update. Basically, the tables being selected from and inserted to are identical: I did a dump/import the other day. The script needs to keep my local table up to date from the remote once since there will be daily records inserted into the remote one and I need to keep it up to date locally.
The key here is that I'm determining the new rows on the remote server by looking at the Auto-incremented Primary key that the tables share, SESSIONID . I'm trying to get my loop below to say, if the id exists in remote server and not local, then insert those records in local server.
I run the below script in powershell by typing php 'filename', and I get both of my successful connection messages, and then I get this message: Incorrect datetime value: '' for column 'ALERTINGTIMESTAMP' at row 1. In this record it's trying to insert, the datetime value is NULL, which the table allows for, however I'm worried it's an issue with escaping characters or something.
How can I modify this to escape properly, or get these records inserted.
Note: Replication and large dump/import/table recreations are not an option for us in this situation. We have several similar scripts to this running and we want to keep the same process here. I'm merely looking to resolve these errors or have someone give me a more efficient way of coding this script, perhaps using a max id or something along those lines.
Here's the script:
ini_set('memory_limit', '256M');
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
$latest_result = $conn2->query("SELECT MAX(`SESSIONID`) FROM `ambition`.`session`");
$latest_row = $latest_result->fetch_row();
$latest_session_id = $latest_row[0];
//Select All rows from the source phone database
$source_data = mysqli_query($conn, "SELECT * FROM `cdrdb`.`session` WHERE `SESSIONID` > $latest_session_id");
// Loop on the results
while($source_item = $source_data->fetch_assoc()) {
// Check if row exists in destination phone database
$row_exists = $conn2->query("SELECT SESSIONID FROM ambition.session WHERE SESSIONID = '".$source_item['SESSIONID']."' ") or die(mysqli_error($conn2));
//if query returns false, rows don't exist with that new ID.
if ($row_exists->num_rows == 0){
//Insert new rows into ambition.session
$conn2->query("INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES ('".$source['SESSIONID']."' ,
'".$source['SESSIONTYPE']."' ,
'".$source['CALLINGPARTYNO']."' ,
'".$source['FINALLYCALLEDPARTYNO']."',
'".$source['DIALPLANNAME']."',
'".$source['TERMINATIONREASONCODE']."',
'".$source['ISCLEARINGLEGORIGINATING']."',
'".$source['CREATIONTIMESTAMP']."',
'".$source['ALERTINGTIMESTAMP']."',
'".$source['CONNECTTIMESTAMP']."',
'".$source['DISCONNECTTIMESTAMP']."',
'".$source['HOLDTIMESECS']."',
'".$source['LEGTYPE1']."',
'".$source['LEGTYPE2']."',
'".$source['INTERNALPARTYTYPE1']."',
'".$source['INTERNALPARTYTYPE2']."',
'".$source['SERVICETYPEID1']."',
'".$source['SERVICETYPEID2']."',
'".$source['EXTENSIONID1']."',
'".$source['EXTENSIONID2']."',
'".$source['LOCATION1']."',
'".$source['LOCATION2']."',
'".$source['TRUNKGROUPNAME1']."',
'".$source['TRUNKGROUPNAME2']."',
'".$source['SESSIONIDTRANSFEREDFROM']."',
'".$source['SESSIONIDTRANSFEREDTO']."',
'".$source['ISTRANSFERINITIATEDBYLEG1']."',
'".$source['SERVICEEXTENSION1']."',
'".$source['SERVICEEXTENSION2']."',
'".$source['SERVICENAME1']."',
'".$source['SERVICENAME2']."',
'".$source['MISSEDUSERID2']."',
'".$source['ISEMERGENCYCALL']."',
'".$source['NOTABLECALLID']."',
'".$source['RESPONSIBLEUSEREXTENSIONID']."',
'".$source['ORIGINALLYCALLEDPARTYNO']."',
'".$source['ACCOUNTCODE']."',
'".$source['ACCOUNTCLIENT']."',
'".$source['ORIGINATINGLEGID']."',
'".$source['SYSTEMRESTARTNO']."',
'".$source['PATTERN']."',
'".$source['HOLDCOUNT']."',
'".$source['AUXSESSIONTYPE']."',
'".$source['DEVICEID1']."',
'".$source['DEVICEID2']."',
'".$source['ISLEG1ORIGINATING']."',
'".$source['ISLEG2ORIGINATING']."',
'".$source['GLOBALCALLID']."',
'".$source['CADTEMPLATEID']."',
'".$source['CADTEMPLATEID2']."',
'".$source['ts']."',
'".$source['INITIATOR']."',
'".$source['ACCOUNTNAME']."',
'".$source['APPNAME']."',
'".$source['CALLID']."',
'".$source['CHRTYPE']."',
'".$source['CALLERNAME']."',
'".$source['serviceid1']."',
'".$source['serviceid2']."')");
}
}
Like Pankaj said, try something like this:
//Insert new rows into ambition.session
$statement = $conn2->prepare('INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES (?, ?, ?, ...);');
$statement->bindParam(1, $source['SESSIONID']);
$statement->bindParam(2, $source['SESSIONTYPE']);
$statement->bindParam(3, $source['CALLINGPARTYNO']);
//...
$statement->execute();
You have to use prepare() function to use parameterized query. Here I have taken example of your query with few parameters you can add yourself with other variables.
$stmt = $conn2->prepare("INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO) VALUES (:SESSIONID ,:SESSIONTYPE ,:CALLINGPARTYNO ,:FINALLYCALLEDPARTYNO)");
$stmt->bindParam(':SESSIONID', $source['SESSIONID']);
$stmt->bindParam(':SESSIONTYPE', $source['SESSIONTYPE']);
$stmt->bindParam(':CALLINGPARTYNO', $source['CALLINGPARTYNO']);
$stmt->bindParam(':FINALLYCALLEDPARTYNO', $source['FINALLYCALLEDPARTYNO']);
$stmt->execute();
You can checkout this link for more understanding. http://php.net/manual/en/mysqli.prepare.php

problems with processing my insert query in php

Hello i have a problem with my query ill keep getting errors from my query
this is my error;
Error: BEGIN; INSERT INTO our_work (id) VALUES ('6'); INSERT INTO
our_work_portf_img (portf_id, img_id) VALUES ('6', '7'); INSERT
INTO our_work_images (img_id, image) VALUES ('7', 'adawd.jpg');
COMMIT; 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 our_work (id) VALUES ('6'); INSERT INTO `our_wo'
at line 3
i've tried many things but i noticed one thing if i copy the $query string and i posted the query directly in mysql the problem will not accorded and it works just how i hoped it would.
Does anyone noticed the problem in my query cause im literal out of ideas.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit_new_img'])){
$pjt_dtls = $_POST['project_details'];
$categories = $_POST['categories'];
$link = $_POST['link'];
$image_path = "adawd.jpg";//$_POST['file']; //$_POST['image'];
$row_id ='6';//++$num_rows['i'];
$image_id ='7'; //++$num_rows['ii'];
$sql = "
BEGIN;
INSERT INTO `our_work`
(`id`)
VALUES
('{$row_id}');
INSERT INTO `our_work_portf_img`
(`portf_id`, `img_id`)
VALUES
('{$row_id}', '{$image_id}');
INSERT INTO `our_work_images`
(`img_id`, `image`)
VALUES
('{$image_id}', '{$image_path}');
COMMIT;
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
$conn->query($sql) does not work with multi-query like yours
you need to use multi_query instead
also here is nice comment:
Please note that there is no need for the semicolon after the last
query. That wasted more than hour of my time...

Categories