php mysqli command cannot be executed now error - php

I am trying to update my SQL table with the help of this php code:
$description = "Something about myself";
$insert = $con->prepare("INSERT INTO kys_write (Author, writing , Title , Description , Assets) VALUES (?,?,?,?,?)");
$insert->bind_param("ssssi",$author,$data,$title,$description, $ImageExist);
$insert->execute();
$statement = $con->prepare("SELECT id FROM kys_write WHERE Title=?");
$statement->bind_param("s",$title);
$statement->execute();
$statement->bind_result($lastId);
//Everything works fine if this whole part is removed
$sql = "UPDATE kys_essentials SET LastId=".$lastId;
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
I am getting a error:
Error updating records:Commands out of sync, you cannot run this command now.
What causes this, and how can I avoid it?

It clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.
You can simplify you code using one query . no use of extra select query
$sql = "UPDATE kys_essentials SET LastId = (SELECT id FROM kys_write WHERE Title='$Title')";
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}

Fetch your $lastId after the binding and put ' ' for value/s, like this:
//your codes
$statement->bind_result($lastId);
while ($statement->fetch()){
$sql = "UPDATE kys_essentials SET LastId='".$lastId."'";
if ($con->query($sql) === TRUE){
echo "Record updated successfully";
} else{
echo "Error updating record: " . $con->error;
}
}

Related

php does not return message:"Record dont exist" if recod does not exist

I made a form that will update table "Komentaar" if id "Telefoni_number" exist. But even if i enter non existing id, I still get echo "Record succesfuly updated".
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "client.id");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE clientid SET Komentaar='OK' WHERE
Tele foni_number=5207245";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
You are printing Records were updated successfully for if the query is executed. Ofcourse the query was executed, weather it made any change or not. You have to address your condition to, if any rows were affected using mysqli_affected_rows().
$sql = "UPDATE clientid SET Komentaar='OK' WHERE Telefoni_number=5207245";
$result = mysqli_query($link, $sql);
if(if (mysqli_affected_rows($link)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
The reason that happens is that the return for this function:
mysqli_query($link, $sql)
Is always going to be true, as long as you provide a valid SQL syntax. You have successfully updated every row with that phone number, which by the way, happens to be zero. To find out whether your code really affected any rows, you can use mysqli_affected_rows. See the documentation:
https://www.php.net/manual/en/mysqli.affected-rows.php
So your code could be something like:
if(mysqli_query($link, $sql)){
if(mysqli_affected_rows($link)) {
echo "Records were updated successfully.";
} else {
echo "ERROR: No records were found!";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

MySQL affected rows -1 when inserting data into database

I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"

Have php switch column value to either 1 or 0

I'm learning PHP and getting a little frustrated. I have an html form that is sending data to another php page $_POST["id"];.
On a 2nd php page I'm trying have the "available" column in the table either switch to 1 or 0. If it's already 1 go to 0, and if it's 0 go to 1.
I know my code is probably completely wrong and messy but please excuse me as I'm still learning.
if ($row["available"] == 1) {
//$row["available"] = 0;
$sql = "UPDATE check_in_out SET available=0 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
} else {
//$row["available"] = 1;
$sql = "UPDATE check_in_out SET available=1 WHERE id='".$_POST["id"]."'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
If you want to toggle the value you can use this:
$sql = "UPDATE check_in_out SET available = (1-available) WHERE id='".$_POST["id"]."'";
or
$sql = "UPDATE check_in_out SET available = IF(available = 0, 1, 0) WHERE id='".$_POST["id"]."'";

PHP SQL Query Fails to Execute

<?php
$db = new mysqli("localhost", "HIDDEN", "HIDDEN", "HIDDEN");
if ($db->connect_error) {
die("Failed to connect.");
}
if (isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["url"])) {
$title = $db->real_escape_string($_POST["title"]);
$description = $db->real_escape_string($_POST["description"]);
$url = $db->real_escape_string($_POST["url"]);
$sql = "INSERT INTO video (name, description, submission_date)
VALUES ('{$title}', '{$description}', CURDATE());
INSERT INTO video_source (video_id, url)
VALUES (LAST_INSERT_ID(), '{$url}');";
if ($db->query($sql) === TRUE) {
echo "Successfully added.";
} else {
echo "Query failed.<br><br>Data: {$title} {$description} {$url}";
}
} else {
echo "Data not set.";
}
$db->close();?>
Outputs "Query failed." with the data I entered. Replacing variables such as title with constants still has the same problem. I tried the query in PHPMyAdmin and it worked fine (with constants).
It seems to be unhappy with setting the value of video_id.
Anytime you're running multiple queries with MySQLi you should use multi_query():
$db->multi_query($sql)
In addition, LAST_INSERT_ID() in your second query is not returning any sort of value. If you're looking for the last inserted value of the 1st query you have to return that prior to running the second query.

Cant track error cause in PHP page updating a MS SQL database

Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!

Categories