What's wrong in my code??? Update query not working - php

I'm posting this question after debugging it several times. Please have a look.
<?php
if(isset($_POST["g"]) && isset($_POST["c"]))
{
$g = preg_replace('#[^a-z]#i', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
//echo $g.$c.$log_username;
if($g == "" || $c == "")
{
echo "The form submission is missing values.";
exit();
}
else
{
$sql = "UPDATE users SET gender='$g',country='$c' WHERE username='$log_username'";
$query = mysqli_query($db_conx,$sql);
//echo $query;
$numrows = mysqli_num_rows($query);
//echo $numrows;
if($numrows > 0)
{
echo "success";
exit();
}
else
{
echo "failed";
exit();
}
exit();
}
}
?>
The error i'm getting is
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\sns2\root\account_config.php on line 36
I'm perfectly getting the values of $g,$c,$log_username (tested it using echo). I'm being connected to the database. I don't think there is something wrong with the query syntax because I have manually executed the same query using the values of $g,$c,$log_username. The query was executed. So could be wrong in this?? Please help!!

Citing the php documentation for 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.
So you're probably getting a TRUE return value and should use http://de3.php.net/manual/en/mysqli.affected-rows.php instead

Use mysqli_affected_rows in case of UPDATE queries.

Related

I am trying to run my website on an online host but i keep getting an error

Every time i am trying to run the following PHP code on 000Webhost, i keep getting this error
-- mysqli_num_rows() expects parameter 1 to be mysqli_result.
The same code had been run successfully without errors on my localhost, XAMPP, i have looked through many examples and only found out that this error is caused by an error in the query, but as mentioned, the query works perfectly on my localhost.
The error is indicated in the code.
Any help would be appreciated.
<?php
session_start();
//decalre variables
$DeviceID ="";
$productID ="";
//connect to database
$db = mysqli_connect('localhost','id5655845_grocerywatch1234','123456','id5655845_grocerywatch1234');
//validate product id and device id are avaliable
if(isset($_POST['validate_user'])){
$DeviceID = mysqli_real_escape_string($db,$_POST['DeviceID']);
$productID = mysqli_real_escape_string($db,$_POST['productID']);
$query = "SELECT * FROM configuration WHERE DeviceID='$DeviceID' AND productID='$productID'";
$result1 = mysqli_query($db,$query);
echo $query;
//error indicated on the following line.
if(mysqli_num_rows($result1) == 1){
$_SESSION['DeviceID'] = $DeviceID;
$_SESSION['success'] = "You are now logged in";
header('location: register.php');
}
else{
echo "Device Not registered";
echo "Product Doesnt Exist";
}
}
I think your query is likely failing. The return value for mysqli_query is False on failure, otherwise it is mysqli_result. See docs here
Fix by properly formatting string:
...
$query = "SELECT * FROM configuration WHERE DeviceID='".$DeviceID."' AND productID='".$productID."'";
$result1 = mysqli_query($db,$query);
echo $query;
if ($result1 == false){
echo "Error has occurred!";
}
elseif (mysqli_num_rows($result1) == 1){
$_SESSION['DeviceID'] = $DeviceID;
$_SESSION['success'] = "You are now logged in";
header('Location: register.php');
}
else{
echo "Device Not registered";
echo "Product Doesnt Exist";
}
The query either returned no rows or is erroneus, thus FALSE is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW,
DESCRIBE or EXPLAIN mysqli_query() will return a result object.

What does true false actually do in php

I have seen many php function & many php scripts, I always find
function check() {
if(isset($_POST['example'])){
return true;
} else {
return false;
}
}
What does this true & false do? does false stops the query from executing further?
Actually i have a login page where I want to stop the executing if user is not found in database like:
if(mysqli_num_rows($query) !=1) {
// if result is not 1 then executing must be stop here, hello should not be echo
}
echo "hello";
further down are more script that should be executed only when result is 1
According to http://php.net/manual/en/function.return.php
-for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.
So i tried a code at my localhost
$a = 1;
if($a == 0){
echo "Its 0"; }
else{ return; }
echo "hi";
after wring return false the word hi was not executed & when i removed return false then the hi word was executed
Now i will tell you what i really want to know
$query3 =mysqli_query($connecDB, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($query3) != 1)
{
$er1 = "Username doesn't exist";
}
else{
$query4 ="SELECT * FROM users WHERE email='$email'";
$result1=mysqli_query($connecDB, $query3);
if(mysqli_num_rows($result1) != 1)
{
$er1 = "Email doesn't exist";
} else {
// do this
}
}
Now you see above i have used if statement into else statement and more if statement into else which makes my php script very much complicated & very hard to understand
I just want to know what is the better way to execute script like shown below
$query3 =mysqli_query($connecDB, "SELECT * FROM users WHERE username='$username'");
if(mysqli_num_rows($query3) != 1)
{
$er1 = "Username doesn't exist";
}
else{ // stop the execution here & just print this $er1 on the page without exit or die }
i want to stop the execution because of below example
$a = 1;
if($a == 0){
echo "Its 0 "; }
else{ //if it's not 0 then it means user is not registered do not echo echo hi below }
echo "hi";
Now the hi is always executed
What makes the function stop executing is the Control Structure return, true or false are Boolean variables, also represented as 1 and 0 respectively.
if(function that returns a boolean !=1)
The if will only execute if function that returns a boolean is true (1)
Learn more about return and Boolean variables
Please note that mysql_* is now deprecated as of PHP7 because of security issues. It is suggested that you switch to mysqli_* or PDO extensions.

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given on line no 22 [duplicate]

This question already has an answer here:
Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, boolean given [duplicate]
(1 answer)
Closed 3 years ago.
I cannot find out what's wrong in this code. Since the query executes and insert also works but the error msg shows:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
boolean given on line no 22. I cannot solve this.
<?php
require_once('db_config.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$name = $_POST['Name'];
$mob = $_POST['Mob'];
$username = $_POST['Username'];
$password = $_POST['Password'];
$sql = "INSERT INTO user (name,phone,username,password) VALUES ('$name','$mob','$username','$password')";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
$check = mysqli_fetch_array($result);
if(isset($check)){
echo "sucess";
}else{
echo "error";
}
mysqli_close($con);
}
?>
As your SQL is an INSERT query, there will be no result set. The result will be the boolean TRUE if the insert was successful, or FALSE if not. So instead of $check = mysqli_fetch_array($result); you can simply say;
if ($result === TRUE) {
echo "success";
}
else {
echo "error";
}
mysqli_query manual page:
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.
Therefore $result is already what you want to check for TRUE/FALSE; and not something you want to pass to mysqli_fetch_*.
Please have read of PHP: SQL Injection and also consider using prepared statements+parameters
<?php
require_once('db_config.php');
if($_SERVER['REQUEST_METHOD']=='POST') {
if (!isset($_POST['Name'], $_POST['Mob'], $_POST['Username'], $_POST['Password']) ) {
die('missing POST parameter');
}
$name = $con->escape_string($_POST['Name']);
$mob = $con->escape_string($_POST['Mob']);
$username = $con->escape_string($_POST['Username']);
$password = $con->escape_string($_POST['Password']);
$sql = "INSERT INTO user (name,phone,username,password) VALUES ('$name','$mob','$username','$password')";
$result = mysqli_query($con,$sql);
if( $result ) {
echo "sucess";
}
else {
echo "error";
}
}
else {
// you should do something/print here....
}
Take
MySQL® Databases from Cpanel then click on the privilaged users. After that, ensure 'allow all privileges is checked'. Then execute your php.

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

How to test if a MySQL query was successful in modifying database table data?

I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false if the query fails, as I've below.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
$delRecord->close();
echo "true";
} else {
echo "false";
}
}
I would like to know what I have missed and the correct way to check if a query was successful or not.
You're currently only checking whether the SQL statement is correctly prepared, you're not checking whether it actually deleted the record.
Try:
...
echo ($delRecord->affected_rows > 0) ? 'true' : 'false';
$delRecord->close();
That doesn't address whether you're correctly checking the result string in your Javascript code - if that's a problem we'll need more information.
You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).
Taking your example, and modifying nothing but for the above:
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
if ($delRecord->affected_rows > 0) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
}
Use the return value of mysqli_stmt->execute() to see if the query was executed successful.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
$delRecord = $con->prepare($deleteQuery);
if ( $delRecord === false ) {
echo "false";
}
$delRecord->bind_param("s", $pk);
if ( $delRecord->execute() ) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
Checking prepare() could be left out because the query is fixed and should be working (unless there is an error on the server side). execute() returns true, if the query was executed successful. Using affected_rows() can be misleading because perhaps there was no item to delete and therefore affected_rows() whould return 0. Nontheless the query was successfully executed.
function run_query($query,$conn,$dbname){
$conn->select_db($dbname);
if($result = $conn->query($query)){
return $result;
}
else{
echo 'error ';
exit();
}
}
run_query() accepts three parameters, the query, connection, and DB. will through an error if the query was unsuccessful, else result object will be returned.

Categories