0

I want to retrieve the values on some condition i have attach the my table image below you can check it, basically i have to account the all Brukt = '0' and group by Gruppe, with 2 more conditions which are Brukernr LIKE '1612%' AND Periode = '2014-2'

enter image description here

As you can see the table and all my condition. My results must be a single array which have 5 values from S1 to S5. The issue is with my current query is that when they did not get any value then it not add it in array, and in result my array only contain those values which give results.

$sq3 = "select Brukt,
               count(*)
        from Brukere_periode
        where Brukt = '0' AND Brukernr LIKE '1612%' AND  Periode = '2014-2'
        group by Gruppe";       
$ru3 = mysqli_query($sq3);  

while($sh = mysqli_fetch_array($ru3)){
    $val[] += $sh[1];
}

It give the results like

Array
(
    [0] => 28
    [1] => 6
    [2] => 2
)

in this array 0 contain S1 value, 1 contain S3 and 2 contain S4, i want my array must return S2 and S5 as well as a empty.

Sara Tariq
  • 27
  • 6
  • 1
    Hello, I'm just here to remind you that the mysql_* prototype is **deprecated** for many reasons (mainly security), hence I'm kindly recommending you to switch to other prototypes, like mysqli_* or PDO instead. Though your query is not exposed in any kind of way to the client itself, it is still recommended to upgrade such prototypes because they will soon become **unsupported**, please check http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php for further informations. – briosheje Sep 15 '16 at 10:58
  • @briosheje Deprecated means that the `MySQL_` DB protocol is already unsupported and has been **removed** in PHP7. Sara, please stop using it and update to MySQLi_ and/or PDO at the earliest opportunity. – Martin Sep 15 '16 at 11:03
  • @Martin: True, that's what I wanted to say using "unsupported", though it is **removed** indeed. – briosheje Sep 15 '16 at 11:04

1 Answers1

0

Init the result's array first:

$val = array( 'S1'=>0,'S2'=>0,'S3'=>0, 'S4'=>0, 'S5'=> 0 );

Add Gruppe field to result set:

$sq3 = "select Brukt, Gruppe, count(*)
        from Brukere_periode
        where Brukt = '0' AND Brukernr LIKE '1612%' AND  Periode = '2014-2'
        group by Gruppe
";

Then assign.

$val [ $sh[1] ] = $sh[2];

Your array will look like:

Array
(
    ['S0'] => 0,
    ['S1'] => 28,
    ['S2'] => 0,
    ['S3'] => 6,
    ['S4'] => 2,
    ['S5'] = 0
)
olegsv
  • 1,422
  • 1
  • 14
  • 21