I am trying to create a page where I can get the record values of a Database. My query is like this:
So I need to get the number of the values 1 on status (as count) from the tableexample if they exist and count them, if they do not exist, I need to get the value as 0 from it. To get the values I use this code and it works great, but I cannot seem to have the value return 0 on my PHP code if no results are found. I am a bit lost.
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'";
$request = mysqli_query($systems, $query);
if (mysqli_num_rows($request) > 0) {
while ($row = mysqli_fetch_array($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
So this code gets the values without any issue, but when I place "else" it should give me value 0 but does not give me anything.
Any idea on how I can solve this without changing my code so far as much?
解决方案
Using PDO would it be something like this:
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$pdo = new PDO($dsn, "username", "password", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare('
SELECT SUM(count)
FROM `table_example`
WHERE `user` = :user
AND `status` = "1"'
);
$stmt->bindParam(':user', $_SESSION["user"], PDO::PARAM_STR);
$stmt->execute();
$sum = $stmt->fetchColumn();
echo $sum;
You don't need to write any loop or previous check in order to get the SUM value.