Confirming deletion of record in mysql php - php

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

Related

PHP isUserAdmin function

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

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.

php: How will I know if the sql query is successfully executed

For example:
$qrInsert = "INSERT INTO DBASE1.DBO.TABLE1 VALUES ('sampVal','sampVal','sampVal')";
odbc_exec($msCon,$qrInsert);
if( 'the query if successfully executed' ){
//then do this
//if not then
}else{
//then do this
}
Is there an easy way to know if it is successfully inserted, or in other cases, updated, and deleted succesfully?
Thanks
Try like
if(odbc_exec($msCon,$qrInsert))
{
echo 'Executed Successfully';
} else {
echo 'Error in execution';
}
odbc_exec only will return true if the query executed successfully,or else return false if it is not
if (odbc_exec($msCon,$qrInsert)){
// do this
}
else{
// do that
}
just replace your code with
$qrInsert = "INSERT INTO DBASE1.DBO.TABLE1 VALUES ('sampVal','sampVal','sampVal')";
if( odbc_exec($msCon,$qrInsert); )
{
//then do this
//if not then
}
else
{
//then do this
}
It Return 0 or 1 depends on failure or success of your query.You Can store result of "odbc_exec" in a variable & compare it in 'If','Else' condition.Benefit of storing in a variable is ,you can use it where ever you want .
i.e.
$query_result = odbc_exec($msCon,$qrInsert);
if($query_result)
echo 'Executed Successfully';
else
echo 'Execuion Error';

How to tell when query executed successfully in PHP PDO? [duplicate]

This question already has answers here:
PDO mysql: How to know if insert was successful
(7 answers)
Closed 6 years ago.
How can I test to see if the following query executed successfully?
$STH = $this->_db->prepare("UPDATE UserCreds SET
VerificationString=:newVerificationString, ExpiryDate=:expiryDate
WHERE UserID = :userID;");
$STH->execute($params);
I know I can use lastInsertId() when I'm adding new rows, but what about UPDATEs and SELECTs?
The execute returns true on success and false on failure.
From Docs:
Returns TRUE on success or FALSE on failure.
So you can make sure query ran successfully like:
if ($STH->execute($params))
{
// success
}
else
{
// failure
}
execute() returns true/false based on success/failure of the query:
$status = $STH->execute($params);
if ($status) {
echo 'It worked!';
} else {
echo 'It failed!';
}
One note: a select query which returns no rows is NOT a failure. It's a perfectly valid result that just happens to have NO results.
simply i can count the number of row effected:
$stmt->execute();
$count = $stmt->rowCount();
if($count =='0'){
echo "Failed !";
}
else{
echo "Success !";
}
This is best way to verify Doctrine query result return success or failed
result and same way as per above suggest to check weather query
returns Success on True and Failed on false.
public static function removeStudent($teacher_id){
$q = Doctrine_Query::create()
->delete('Student s')
->where('s.teacher_id = ?');
$result = $q->execute(array($teacher_id));
if($result)
{
echo "success";
}else{
echo "failed";
}
}

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