Two queries in one php file, one is not working - why? - php

In my code, there are two different queries. The first one is working - by which I mean it goes to the if path. The problem is with the second one which goes to the else path.
$adding_user_email=$arr[1];
$sessionuserid=$_SESSION['login_user_id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO modes (userid,modename) VALUES ('$sessionuserid','".$arr[0]."')";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='".$arr[1]."'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
if ($conn->query($sqlmodeid_uderid) === TRUE) {
echo "userid fetched successfully";
} else {
echo "Error: " . $sqlmodeid_uderid . "<br>" . $conn->error;
}
$conn->close();
Help me out. (query is working fine)

The condition is a problem:
$conn->query($sqlmodeid_uderid) === TRUE
If we consult the documentation for the query function we will see:
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.
As you are dealing with a SELECT query, this call will never return true. It will return a mysqli_result object on success, and false on failure.
Instead you could rewrite this condition in a number of ways.
Check the query does not return false.
if ($conn->query($sqlmodeid_uderid) !== FALSE) {
Use == instead of ===. The first will cast between two different types (and the mysqli_result object will equate to true when casted to bool) whereas === performs a typesafe comparison, meaning the condition will only be satisfied if both operands are of the same type and have the same value.
if ($conn->query($sqlmodeid_uderid) == TRUE) {
The same logic in point 2 can be wrote in a few different ways:
if ($conn->query($sqlmodeid_uderid)) {
if ((bool)$conn->query($sqlmodeid_uderid)) {
I would look at the php.net documentation on comparison operators for more info on this:
http://php.net/manual/en/language.operators.comparison.php

Use code like this...
$adding_user_email=$arr[1];
$sessionuserid=$_SESSION['login_user_id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO modes (userid,modename) VALUES ('$sessionuserid','".$arr[0]."')";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='".$arr[1]."'";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";

For the second query, I think you should do like this instead of doing "=== TRUE"
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
/* Select queries return a resultset */
if ($result = $conn->query($sqlmodeid_uderid)) {
echo "userid fetched successfully";
} else {
echo "Error: " . $sqlmodeid_uderid . "<br>" . $conn->error;
}
Look at the examples in the doc : http://php.net/manual/en/mysqli.query.php

Related

How to execute multiple mySQL queries in one PHP script

Currently, I have the following structure in my PHP script, I would like one query to execute and if successful the next one should execute.
The following is my current code, but how can I add a simple
conditional that would allow the second query to execute after the
delete query?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM Table1" ;
$sql = " INSERT INTO Table1 (tbcolm, , tbcolm2, tbcolm3)
SELECT `column1`, `column2`,`column3` FROM Table3 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You can use mysqli multi_query, as stated in PHP Manual:
https://secure.php.net/manual/en/mysqli.quickstart.multiple-statement.php
Be sure to add a ; at the end of your strings, and use the concatenating assignment operator (.=) on the second $sql variable.
It should look like this:
$sql = "DELETE FROM Table1;";
$sql .= "INSERT INTO Table1 (tbcolm, , tbcolm2, tbcolm3)
SELECT 'column1', 'column2','column3' FROM Table3;";
if ($mysqli->multi_query($sql)) {
/* success code here */
}
If the first argument fails, the next one won't be queried, as stated in:
https://www.php.net/manual/en/mysqli.multi-query.php

Unable to select data from MySQL database using PHP 7.2

Please I haven't quite figured out what's wrong with this code
<?php $servername = "blee.com";
$username= "free";
$password = "free";
$dbname = "one";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT * FROM users";
if ($conn->query($sql) === TRUE) {
echo "success";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close(); ?>
Somehow, if I try to insert anything into the database, it works perfectly, but if I try to select, it just shows "error creating table :" with no error being displayed...... I've searched all over but found no solution
I'm using php7.2 on my web server
For SELECT (as well as SHOW, DESCRIBE and EXPLAIN) queries mysqli::query returns a mysqli::result object if it succeeds, not a boolean. So your test
if ($conn->query($sql) === TRUE)
will always fail. What you should do instead is check that the query didn't fail (by comparing the return value with false), then you can use the returned object to fetch rows from the result set by using functions such as mysqli_result::fetch_assoc.
$result = $conn->query($sql);
if ($result !== false) {
// do something with results e.g.
// while ($row = $result->fetch_assoc()) { print_r($row); }
}

Why do we check both the value and type when check if a database query was successful?

While I was on w3schools learning about MySQL and PHP, I came across this when on the page about inserting data.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$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;
}
$conn->close();
?>
When checking the query was successful, why do we check if both are the same type and equal? Wouldn't it be fine if it was just this?
if ($conn->query($sql) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli::query() returns false on failure, another result will be always not false. You can write without equaling with true if you don't need to use special logic for mysqli_result. docs
if ($conn->query($sql))
{
//
} else
{
//
}
Php supports truthyness do if the function returned 1 then it would be true. It's explicitly checking that the result is the Boolean TRUE.
You do NOT need to check type in THIS case and could just have:
if ($conn->query($sql) == TRUE) {
The author is probably using a defensive programming technique which is to validate exactly what you are expecting.
According to: http://php.net/manual/en/mysqli.query.php
If this is a "SELECT, SHOW, DESCRIBE or EXPLAIN" then you would get an object back. If somebody updated the query to something unexpected, they would hit the error condition and know they had done something wrong. This particular scenario is a little off because it's sample code. In reality you would probably have a test to do the real validation.

How to know Update is done for in simple mysqli query , Updated at least one row

My Code is :
//Catch
$myotp=$_GET["myotp"];
$rowid=$_GET["rowid"];
//Constructing the updat esql query
$update= "update order set dsotp ='$myotp' WHERE fsotp='$myotp' and id_order=$rowid";
//Excecuting the query
$res=mysqli_query($conn,$update);
It is working fine. But the problem is how to know from PHP code that it is updated the table?
You can check this way:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
Refer:https://www.w3schools.com/php/php_mysql_update.asp
mysqli_query returns TRUE or FALSE. and also the result set.
So, you can try this:
print_r($res);
PS: Also for the second part you can use mysqli_affected_rows($conn); to get the number of affected rows.
If you want to test if the query executed succesfully you should use the if statements provided above, however these do not check if there was any value updated. If you want that, you should use affected_rows.
http://php.net/manual/en/mysqli.affected-rows.php
A basic example would be this:
if($result = $mysqli->query($sql)){
var_dump($mysqli->affected_rows);
if($mysqli->affected_rows == 1){
return TRUE;
} else{
return FALSE;
}
}

how to add a MySQL Command to every page

I have a code I would like to run on every page, however it doesn't seem to work at all.
<?php
include 'db.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "User";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE users SET login_time=NOW() WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I have also tried the line
$sql = "UPDATE users SET login-time='NOW()' WHERE id='$id'";
It comes back saying Record updated successfully But doesn't acctually update.
Thank you
This will never work:
if ($conn->query($sql) === TRUE) {
query() calls either return a statement handle/object (success), or a boolean FALSE (failure). They will never return a boolean TRUE, meaning that this comparison can never ever succeed. You should never have gotten a "success" message, only the "failed" one.

Categories