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.
Related
I m trying to delete a row in php mysql. The row is deleted quiet ok but mysqli_affected_rows($conn) is not giving a response so I can confirm the deletion for the user.
$sql="DELETE FROM `users` WHERE `memberID`='$id'";
$res=mysqli_query($conn,$sql);
if(mysqli_affected_rows($conn) == 1){
echo 'success'
} else {
echo "The User could not be deleted due to some error";
echo mysqli_affected_rows($conn);
}
You don't need to check by boolean value 0 or 1. But if you want to do it that way, you will need to declare a flag before that and then change the flag value according to condition after that you can do it [as your way]
(mysqli_affected_rows($conn) == 1)
But as default a simple if() conditon will check and return true on pass and false on fail.
So, simply you can do:
if($res)
{
//your codes if query is done
} else
{
//your codes if query fails
}
By default, the mysqli_query() function will return you a true if all went well or a false if there is any error. You can check if your query did not return any error like so:
if($res) {
echo "Delete success";
} else {
echo "Delete error: " . mysqli_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.
I want to read from a MySQL table whether it is an admin. In the row "Status" there is a 1 or a 0. Is it greater than 0 then it is an admin.
PHP:
<?php
if($db->isUserAdmin() === TRUE) {
echo 'Admin';
} else{
echo 'Noadmin';
}
?>
MySQLi:
function isUserAdmin() {
$stmt = self::$_db->prepare("SELECT Status FROM users WHERE Session=:sid");
$stmt->bindParam(":sid", session_id());
$stmt->execute();
if($stmt->rowCount() < 1) {
return true;
} else {
return false;
}
}
Just to educate the great folks of Stack Overflow
function isUserAdmin()
{
$stmt = self::$_db->prepare("SELECT Status FROM users WHERE Session=?");
$stmt->execute([session_id()]);
return $stmt->fetchColumn(); // here is what you really need
}
if($db->isUserAdmin()) {
echo 'Admin';
} else{
echo 'Noadmin';
}
You are checking the number of rows returned by the query, not the value of the status.
If it's admin or user and have a session will always return true because there is an entry in users table. If no user exists will always return false.
You need to check the data returned by sql and check if the value of Status > 0
Or change the sql and add there an extra check that Status > 0
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.
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.