Returning a value 0 from a database row in PHP/MySQL after a query

Pedro Carvalho :

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?

Chemaclass :

Using PDO would it be something like this:

$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$pdo = new PDO($dsn, "username", "password", $options = []);
$stmt = $pdo->prepare('
    SELECT SUM(count) AS value_sum 
    FROM `table_example` 
    WHERE `user` = :user 
    AND `status` = "1"'
);
$stmt->bindParam(':user', $_SESSION["user"], PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['value_sum'] ?? 0;

You don't need to write any loop or previous check in order to get the SUM value.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401902&siteId=1