Php MySQLI statement skips the 'if' statement to 'else' without any possible mistake in database
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..
Answer
Solution:
Your SELECT and the associated PHP code is completely redundant. All you need is an improved update statement.
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.