Mysqli Multi Query - php

So besides the DB connector that I haven't included what could cause me to get this 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 'UPDATE EventData SET deviceID = "631403956MB21" WHERE deviceID = "4631403956MB' at line 1"
This is my php mysqli multi query.
$sql = "UPDATE Device SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
$sql .= "UPDATE EventData SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
$sql .= "UPDATE NotifyQueue SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
$sql .= "UPDATE RuleTrigger SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
$sql .= "UPDATE RuleList SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
$result = mysqli_multi_query($db, $sql);
if ($result) {
echo 'true';
} else {
echo 'false';
echo mysqli_error($db);
}
mysqli_close($db);
Thanks,
Mike

Disable auto commit when inserting/updating multiple queries and use a loop:
$mysqli = dbConnect(); // Connect with database
$mysqli->autocommit(FALSE); // Set autocommit off
// You can prepare and bind outside the foreach loop, so you don't
// have to write and bind each query individually.
$sql = "UPDATE RuleList SET deviceID = ? WHERE deviceID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ii', $deviceID1, $deviceID2);
foreach($ids as $id):
$deviceId1 = $id;
$stmt->execute();
endforeach;
$stmt->close();
$mysqli->commit(); // Commit all queries
$mysqli->close();
The above is an example

Correct query:
UPDATE Device SET deviceID = '631403956MB21' WHERE deviceID = '4631403956MB2';
UPDATE EventData SET deviceID = '631403956MB21' WHERE deviceID = '4631403956MB2';
...
So, finally, you did not assign ";" at the end of each query. You assign only one ";" at the end of php code.
$sql = "UPDATE Device SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
$sql .= "UPDATE EventData SET deviceID = \"631403956MB21\" WHERE
deviceID = \"4631403956MB2\" ";
...
↓↓↓
$sql = "UPDATE Device SET deviceID = '631403956MB21' WHERE
deviceID = '4631403956MB2'; ";
$sql .= "UPDATE EventData SET deviceID = '631403956MB21' WHERE
deviceID = '4631403956MB2'; ";
...
Please try and hope it helps.

you should not have multiple UPDATE clauses in the same query. You're attempting to use mysqli_multi_query but you need to separate your queries with a semi-colon:
First create an array:
$queries = [
"UPDATE Device...",
"UPDATE EventData...",
"UPDATE NotifyQueue...",
];
From there you have two options. First is to loop through and execute the queries one at a time
foreach($queries as $sql):
$result = mysqli_query($db, $sql);
...
endforeach;
This isn't a great idea though because it requires many trips to the DB. The better option is what you're actually trying to do: execute a multi-query statement
$multi_query = implode('; ',$queries);
mysqli_multi_query($db, $multi_query);
...
Important Note
multi_query does not use prepared statements, so if you're not careful, you will be vulnerable to SQL-injection attacks. With this approach, be sure to escape your strings and to cast all numerical values as numbers (eg: $var = (int)$var) before you include them in the queries.
By the way, I notice that you're making the same change in deviceID on multiple tables. This may be a sign that your architecture is poorly designed. If you have InnoDB tables, you can use primary and foreign keys to indicate that deviceID in the EventData, NotifyQueue... tables is a foreign key linked to the primary key in the Device table. Then if you set changes to cascade on update, all you would need to do is change the ID in the Device table and the DB will take care of changing it everywhere else. Here is a quick intro to the concept.

Related

Update query works but not insert query

I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.

SQL Multiple Statements

I am using php and mysql to update rows in my DB. I have 4 update statements in a row, yet only the last one works. I have confirmed that the statements work if they are used alone, but when I have them executed one after another only the last one executed works. I am receiving no error messages. Any help? Thanks!
$sql = "UPDATE comlog SET name='$name1', message='$message1' WHERE id=1";
$sql = "UPDATE comlog SET name='$name2', message='$message2' WHERE id=2";
$sql = "UPDATE comlog SET name='$name3', message='$message3' WHERE id=3";
$sql = "UPDATE comlog SET name='$name', message='$message' WHERE id=4";
In the above code, only the row with id 4 is being updated.
The answer is simple.
You are declaring the same variable for EACH sql string.
You need to declare it something like:
$sql1 = "";
$sql2 = "";
$sql3 = "";
$sql4 = "";

PHP SQL Views counter using PDO prepare()

I have a variable $id which gives me the id of the current article and this can help me to make an update query in my database on current article.
This is my code:
$vizualizari = $current_views+1;
$sql1= "UPDATE detalii_cantari SET viz = viz WHERE id = {$id};";
$q1 = $dbh->prepare($sql1);
$q1->execute(array(':viz'=>$vizualizari));
I don't get any errors but my code is still not working...
Your correct code is here:
$vizualizari = $current_views+1;
$sql1= "UPDATE detalii_cantari SET viz = :viz WHERE id = {$id}";
$q1 = $dbh->prepare($sql1);
$q1->execute(array(':viz'=>$vizualizari));
; from the end of sql is not needed here and viz = viz must become viz = :viz because of PDO.
It seems you have to get rid of the previous query and make it in a single statement
$sql = "UPDATE detalii_cantari SET viz = viz + 1 WHERE id = ?";
$stm = $dbh->prepare($sql);
$stm->execute(array($id));

My PHP SQL query is throwing errors, even though it works in the SQL console

I'm trying to create a function for my forum that will increment my user's "Posts" attribute by 1. For whatever reason, the following PHP does not work.
function postCountIncrease($username) {
//get the connection variable
global $con;
//change to the users database (this function works correctly)
sqlconnect_users();
//get current post number (this is also working)
$getCurrentPosts = "SELECT Posts\n"
. "FROM users\n"
. "WHERE Username='".$username."'";
$query1 = mysqli_query($con, $getCurrentPosts) or die(mysqli_error($con));
$currentPosts = mysqli_fetch_array($query1);
//here is the problematic post. Assume that $username is a valid value, and that I've already done mysqli_real_escape_string() on it
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
$query2 = mysqli_query($con, $incrementPostsQuery) or die(mysqli_error($con));
//return the result
$result = mysqli_fetch_array($query2);
return $result;
}
I honestly don't see what I'm doing wrong, because the SQL works fine. If I use UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' in the console, it works with no errors. Help is much appriciated. Also, here is the error it is throwing at me:
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 WHERE Username='Lampitosgames''
You can not concatenate that way "toto ".$var+1, you have to surround with brackets "toto ".($var+1)
In your case, this is declaration of var $incrementPostsQuery which fails
Look at your errors, your syntax is off
$getCurrentPosts = "SELECT Posts
FROM users
WHERE Username='$username'";
The error is in the building of your query.
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
I'll suggest you some tips to create query like this:
"update table set field = value"; // you can write the value directly
"update table set field = ". $value; // easy
"update table set field = ". ($a+$b); // ...
"update table set field = {$value}"; // you can add a variable with curly braces
"update table set field = {$va[3]}"; // more compless way
"update table set field = {$a->b}"; // an object field

SQL error in php

Hey, I wrote some code for extracting some information out of the database and checking to see if it met the $_COOKIE data. But I am getting the 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 ')' at line 1
My code so far is:
$con = mysql_connect("XXXX","XXXXX","XXXXXXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXXXXX", $con);
$id = $_COOKIE['id'];
$ends = $_COOKIE['ends'];
$userid = strtolower($_SESSION['username']);
$queryString = $_GET['information_from_http_address'];
$query = "SELECT * FROM XXXXX";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if ($queryString == $row["orderid"]){
$sql="UPDATE members SET orderid = ''WHERE (id = $id)";
$sql="UPDATE members SET level = 'X'WHERE (id = $id)";
$sql="UPDATE members SET payment = 'XXXX'WHERE (id = $id)";
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
Any help would be appreciated,
Thanks.
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
should be
$sql="UPDATE members SET ends = '$ends'WHERE (id = '$id')";
(IE add the ' around $id)
I'm not sure if this is the error, but do you realize you're code only runs the last UPDATE? You're assigning $sql 4 time, and only running it after the fourth assignement...
If $_COOKIE['id'] does not have a value, then $id in your SQL statements will be blank, leaving your SQL looking like this:
UPDATE members SET ends = 'something' WHERE (id = )
which, of course, is invalid SQL.
Only one of the SQL statements will execute, and that's the last one. You need to add some whitespace before the WHERE clause, like this:
$sql="UPDATE members SET ends = '$ends' WHERE (id = $id)";
Also be wary of SQL injection attacks in the event that your cookie is altered by the end user. One other thing of note is your orderid column. Is it a VARCHAR or some other unique identifier? If it's an integer, then setting it to empty string will not work. You might want to rethink your schema a bit here.
EDIT: Another thing you need to do is check to make sure the cookies actually have values. If not, your SQL strings will be messed up. Have you though about using parameterized queries through PDO so you don't have to worry about SQL injection at all?
first of all you keep overwriting $sql variable so only the
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
is being executed.
And I would say that $id variable is not what you think it is (maybe empty as query like the one above without id:
$sql="UPDATE members SET ends = '$ends'WHERE (id = )";
would throw such error back.
Try
$id = NULL;
before
$id = $_COOKIE['id'];
if the error is gone that means that $id is not what you think it is

Categories