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); }
}
Related
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.
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;
}
}
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.
I have this extremely weird issue with mysql. I can insert into, and create tables. However I cannot select anything and it does not display any error when I try, it just echos my line "Error: "
getDiff("validTable");
function getDiff($regNr) {
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//todo
$sql = "SELECT * FROM $regNr ORDER BY id LIMIT 1";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "done";
} else {
$error = $result->error;
echo "Error: " . $error;
}
$conn->close();
}
But when I insert to the DB using this
$query = "CREATE TABLE IF NOT EXISTS $regNr ( `id` MEDIUMINT NOT NULL AUTO_INCREMENT, `mail` INT NOT NULL , `price` INT NOT NULL , `views` INT NOT NULL , `the_date` DATE NOT NULL , `time` VARCHAR(5) NOT NULL, PRIMARY KEY (id) )";
runQuery($query);
function runQuery($todo) {
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//todo
$sql = $todo;
if ($conn->query($sql) === TRUE) {
echo "done";
} else {
echo "Error: " . $conn->error;
}
$conn->close();
}
It works just fine and dandy. WHAT HAVE I DONE WRONG?! This is driving me crazy!
It shows only "Error" because your query succeeds and returns a mysql object which is not equal to True and therefore it does not echo done
See (http://php.net/manual/en/mysqli.query.php)
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.
Change your code with the code below to make it work:
if ($conn->query($sql) === FALSE) {
echo "Error: " . $conn->error;
} else {
echo "done";
}
Basically turning the if around such that it checks for FALSE or not FALSE.
Most probably you also want to store the result in a variable like:
if ($result = $conn->query($sql) === FALSE) {
And later on use $row = $result->fetch_array() or $row = $result_fetch_assoc() to get the data.
mysqli_query
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 per this condition
if ($conn->query($sql) === TRUE) {
You get mysqli_result from your query and this is not equal to TRUE and you always goes into error condition
To fetch data from query use fetch_array
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0]);
To get error form query we use $conn->error not $result->error it need your connection variable not your result variable
Read http://php.net/manual/en/mysqli.error.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