Compaing a method with True - php

I have a question about this code.
$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;
}
As far as a I know $conn -> query()call a method query attached to the object $conn. How can we compare a method with ===True?

From query command documentation:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
In other words it will return TRUE if insert was successful and FALSE otherwise. So we are comparing function return value after its execution with TRUE to see if it has successfully executed.
You can rewrite this as:
$query_sucessfully_executed = $conn->query($sql);
if ($query_sucessfully_executed) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
It has the same meaning. I hope this clears things up a bit.
You can learn more about this in query documentation.

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')"

php mysqli command cannot be executed now error

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;
}
}

Error produced from mysql select

I'm currently learning MySql, but ive hit this problem.
the following code should just query the db for everything in the users table. but it returns this error. Error: SELECT * FROM users which helps me not at all. I am able to successfully insert an item into the database, but I am unable to select from it. I've also tried $sql = "SELECT * FROM ama.users"; my DB structure is
ama
|-users
any help would be much appreciated.
$conn = new mysqli($_ENV['OPENSHIFT_MYSQL_DB_HOST'],$_ENV['OPENSHIFT_MYSQL_DB_USERNAME'], $_ENV['OPENSHIFT_MYSQL_DB_PASSWORD'], 'ama');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = "Doe";
$password = "johnexample";
$sql = "SELECT * FROM users";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
From the PHP Manual:
mysqli::query will return object in success and return false in failure.
So you can use it without checking data type (===):
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
For more better understanding you can use var_dump() and check what are you getting like:
var_dump($conn->query($sql));
Documentation says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So, do something like
$result= $db->query($sql);
and then check the rows in $result

MYSQli select not working

I am not actually very good at it, but I never got this kind of error. I am trying to select GB entries and I can't get it working.
gb.php
<?php
$conn = new mysqli('localhost','ab','somepassword','gb');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
else {echo 'connected';}
$sql = "SELECT * FROM `posts`";
if ($conn->query($sql) === TRUE) {
echo 'done';
}
else{echo 'sql not working';}
?>
Table snapshot
Result:
connectedsql not working
One more thing the INSERT & UPDATE statements are working from same folder.
The return value of MySqlI->query() is defined like:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
So you must check for not equal to false
if ($result !== false) {
you can also check on this condition
$res=$conn->query($sql);
if($res)
{
}
else
{
}
mysqli_query/ $mysqli->query does not return True if the query executed succesfully but return false if not executed..Try with -
$result = $conn->query($sql);
if ($result !== false) {
echo 'done';
}
else{echo 'sql not working';}

Categories