Php MySQLI statement skips the 'if' statement to 'else' without any possible mistake in database

685

I m trying to get the existing values from "useravailedlockedcoupons" table and update it to the "usercouponunlock" table.

But unfortunately the update 'if' statement gets skips to 'else' without showing any error. (shows only 'none' which i have kept for 'else' statement) then executes the redirected php.page

The code follows:

<?php include('userdeleteunlocked.php'); ?>
<?php
$servername  = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "";

$mobile = $_SESSION['mobile'];
$date = date('M-d,Y H:i:s');
$date2 = date('M-d,Y');

$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM useravailedlockedcoupons WHERE mobile = '$mobile' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {  
        $amount = $row['amount'];
        $company = $row['company'];
        $sql2 = "UPDATE usercouponunlock SET amount = '$amount', company = '$company', date = '$date2'
                WHERE mobile = '$mobile'";

        if ($conn->query($sql2) === TRUE) {
            echo  '<a href="userdeleteunlocked"></a>';
        } else {
            echo "0";
        }
    }
} else {
    echo "None";
} 
$conn->close();
?>

Any Help is greatly appreciated..

568

Answer

Solution:

Your SELECT and the associated PHP code is completely redundant. All you need is an improved update statement.

$stmt = $conn->prepare("UPDATE userpaytoget SET usercouponinhand = usercouponinhand+?, date = ?, date2 = ? WHERE mobile = ?";

As you can see from the above, it's quite possible to update a table without selecting the rows first and iterating through it.

Notice how prepared statements are used here to protect against SQL injection.

$stmt->bind_param("ssss",$_GET["id"] , $date, $date2, $mobile);
$stmt->execute();

People are also looking for solutions to the problem: php - Mailchimp api v3 - can't create segment based on a TEXT merge field

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.