Moaz  Mabrok Moaz Mabrok - 5 months ago 7
SQL Question

while loop does not work in function php , global fix of ather

The while loop works fine in this example.

$query="SELECT * FROM `ex`";
$result=mysqli_query($link, $query);

$Q_X='Q1';
$res=array(0,0,0,0,0);
while($report=mysqli_fetch_array($result)){
print_r($report[$Q_X].'<br>');

if($report[$Q_X]=='X1'){
$res[0]=$res[0]+1;

}elseif($report[$Q_X]=='X2'){
$res[1]=$res[1]+1;

}elseif($report[$Q_X]=='X3'){
$res[2]=$res[2]+1;

}elseif($report[$Q_X]=='X4'){
$res[3]=$res[3]+1;

}elseif($report[$Q_X]=='X5'){
$res[4]=$res[4]+1;
}
}
list($Q1_1,$Q1_2,$Q1_3,$Q1_4,$Q1_5) = $res;

echo $Q1_1.',';
echo $Q1_2.',';
echo $Q1_3.',';
echo $Q1_4.',';
echo $Q1_5;


but when I try to put it in a function in doesn't work

$query="SELECT * FROM `ex`"; //new
$result=mysqli_query($link, $query);

function count_vote($Q_X) {
$cont=0;

global $result; //new

$res=array(0,0,0,0,0);
while($report=mysqli_fetch_array($result)){

if($report[$Q_X]=='X1'){
$res[0]=$res[0]+1;

}elseif($report[$Q_X]=='X2'){
$res[1]=$res[1]+1;

}elseif($report[$Q_X]=='X3'){
$res[2]=$res[2]+1;

}elseif($report[$Q_X]=='X4'){
$res[3]=$res[3]+1;

}elseif($report[$Q_X]=='X5'){
$res[4]=$res[4]+1;
}
}
if(mysqli_num_rows($result)==$cont){
return $res;
}
}


count_vote("Q1");
list($Q1_1,$Q1_2,$Q1_3,$Q1_4,$Q1_5) = $res;

echo $Q1_1.',';
echo $Q1_2.',';
echo $Q1_3.',';
echo $Q1_4.',';
echo $Q1_5;


I using an array to get multiple values returned

and if to prevent the function from exiting before the while loop ending

I am trying to make it into a function to use it multiple times on Q1,Q2,..

can someone help me find the problem




Q1 . Q2 . Q3 . Q4





user1 | X1 . X3 . X5 . X4

user2 | X2 . X2 . X3 . X2

user3 | X1 . X1 . X1 . X1


I want to get this resort

Q1---> X1 >2
---> X2 >1
---> X3 >0
---> X4 >0
---> X5 >0

Q2---> X1 >1
---> X2 >1
---> X3 >1
---> X4 >0
---> X5 >0
Q3,Q4....


while loop does not work in function php

Answer

Try the following code:

function count_vote($result ,$Q_X)
{
    $res = array(0, 0, 0, 0, 0);
    while ($report = mysqli_fetch_array($result)) {
        if ($report[$Q_X] == 'X1') {
            $res[0] = $res[0] + 1;

        } elseif ($report[$Q_X] == 'X2') {
            $res[1] = $res[1] + 1;

        } elseif ($report[$Q_X] == 'X3') {
            $res[2] = $res[2] + 1;

        } elseif ($report[$Q_X] == 'X4') {
            $res[3] = $res[3] + 1;

        } elseif ($report[$Q_X] == 'X5') {
            $res[4] = $res[4] + 1;
        }
    }
    if (mysqli_num_rows($result) > 0) {
        return $res;
    }
}


$query = "SELECT * FROM `ex`"; //new
$result = mysqli_query($link, $query);

list($Q1_1, $Q1_2, $Q1_3, $Q1_4, $Q1_5) = count_vote($result ,"Q1");

echo $Q1_1 . ',';
echo $Q1_2 . ',';
echo $Q1_3 . ',';
echo $Q1_4 . ',';
echo $Q1_5;

I think the problem may be with the fact that the $result in the function was an empty global so we'll send that with the constructor as well.