-1

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?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 1
    Do not use the values from outside directly into your queries. Otherwise, you will be exposed to SQL Injection. – Chemaclass Apr 02 '20 at 09:36
  • @Chemaclass sorry i needed to add a code update as for some reason was not correct on display. Btw thank you for the advice. – Pedro Carvalho Apr 02 '20 at 09:38

3 Answers3

3

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.

Chemaclass
  • 1,933
  • 19
  • 24
  • 1
    This code returns me blank after testing in my localhost. However seems very direct and simple, but how can i add a value if the result from the query does not exist? – Pedro Carvalho Apr 02 '20 at 09:54
  • 1
    Even `0` is a number that represents nothing, but the query will return always a number. At least that one, because you're selecting the SUM of something, or am I missing something here? – Chemaclass Apr 02 '20 at 09:56
  • I understand that but i get no output from your code after testing its point blank to me.. :( – Pedro Carvalho Apr 02 '20 at 09:57
  • What is exactly blank? what does the log file say? what do you get if you `var_dump($row);`? – Chemaclass Apr 02 '20 at 10:40
  • I have no result on your code if the table is empty, should display a 0 but i get nothing and nothing is on my error log as well – Pedro Carvalho Apr 02 '20 at 10:44
  • Are you saying that you get `null` on `$row['value_sum']`? Can you be more precise on your statement of "should display a 0 but i get nothing"? – Chemaclass Apr 02 '20 at 10:45
  • I have a test page plain php code with your code inside and modified to match my database parameters, when i run the page to get the results, if the table of the database is empty the page is blank do not display any content, if records are found i get the number of records without an issue. – Pedro Carvalho Apr 02 '20 at 10:50
  • Ok. change the last two lines to `$all = $stmt->fetchAll(); var_dump($all);'. what do you see when there is no data in the DB? – Chemaclass Apr 02 '20 at 10:55
  • I get this value: array(1) { [0]=> array(2) { ["value_sum2"]=> NULL [0]=> NULL } } please note that i changed the value_sum to value_sum2 – Pedro Carvalho Apr 02 '20 at 10:58
  • all right. Then you're getting `null` instead of `0`. Well, that's easy to solve. Use "Null coalescing operator" (From PHP 7+) https://medium.com/sevensenders-techblog/modern-php-know-the-best-php-features-til-php-7-4-e3b2bf5916b2 – Chemaclass Apr 02 '20 at 11:23
  • Use this: ``` $row = $stmt->fetch(PDO::FETCH_ASSOC); echo $row['value_sum'] ?? 0; ``` – Chemaclass Apr 02 '20 at 11:23
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210799/discussion-between-chemaclass-and-pedro-carvalho). – Chemaclass Apr 02 '20 at 11:26
1

You are doing a SUM query which will always have a result row.

SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'

You might want to check the SUM(count) = 0 where you can do it in your while loop

while ($row = mysqli_fetch_array($request)) {
    if (!empty($row[0])) {
        echo $row[0]; // sum not 0
    } else {
        echo '0';
    }
}
Gihan
  • 4,163
  • 6
  • 31
  • 49
-1

Your are using mysqli_fetch_array which returns array with both numeric and associative indexes instead of just associative array. You should use mysqli_fetch_assoc or mysqli_fetch_array with 2nd parameter resulttype as mentioned in docs.

resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

https://www.php.net/manual/en/mysqli-result.fetch-array.php

https://www.php.net/manual/en/mysqli-result.fetch-assoc.php

As per OP's request. Here is your code with some changes.

<?php
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = mysqli_real_escape_string($systems, "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'");
$request = mysqli_query($systems, $query) or die(mysqli_error($systems)); // Added die for dev env. You can choose how you want to deal with db query error.
if (mysqli_num_rows($request) > 0) {
    // Just replaced mysqli_fetch_array with mysqli_fetch_assoc
    while ($row = mysqli_fetch_assoc($request)) {
        echo '' . $row["value_sum"] . '';
    }
} else {
    echo '0';
}

Also, as you are getting 0 it seems that your if (mysqli_num_rows($request) > 0) is not returning true. Might be due to some error in db query, you may want to check that again.

Edit 04-04-2020:

  1. Updated info about indexes of returned array by mysqli_fetch_array.
  2. Added mysqli_real_escape_string for $query.
Umair Khan
  • 1,684
  • 18
  • 34
  • Can you provide me a example using my code? Thank you in advance – Pedro Carvalho Apr 02 '20 at 10:09
  • Your code works perfectly but it does not show me the 0 on return after the query, however it does work, but if no results are found i am getting nothing in return – Pedro Carvalho Apr 02 '20 at 10:41
  • `mysqli_fetch_array()` returns associative array. – Dharman Apr 03 '20 at 19:09
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Apr 03 '20 at 19:11
  • @Dharman. As for `die`, I had added a comment that its for dev environment only. As for `mysqli_fetch_array`, you are right about that and I have updated my answer. As for `escaping` the `query`, its upto OP to decide about the techniques that He / She sees fit. Normally people only provide related code here to explain about the problem and seek its solution. – Umair Khan Apr 04 '20 at 05:32
  • @Dharman come on, the idea with `mysqli_real_escape_string($systems, "whole query goes here");` is much worse – Your Common Sense Apr 04 '20 at 09:29
  • 1
    @UmairKhan there is **no point** in doing the job twice, writing two versions of code, one for the dev environment and one for the production. – Your Common Sense Apr 04 '20 at 09:30