user1901142 user1901142 - 1 month ago 6
SQL Question

Loop while for array on php

Why this loop doesn't work? When I check with

echo vardump($tablesliders);
the array tablesliders only have inserted one element, the last element of the query. The query is correct.

while($row_Slider=mysql_fetch_array($Query_Sliders)){
$QuestionID=$row_Slider['QuestionIDFK'] ;
$AnswerID=$row_Slider['AnswerIDPK'] ;
$AnswerValue=$row_Slider['AnswerValue'] ;
$tablesliders = array (
"QuestionID" => array($k => $QuestionID),
"$AnswerID" => array($k => $AnswerID),
"$AnswerValue" => array($k => $AnswerValue)
);
$k=k+1;
}


How could I re-write the code using
foreach
loop ?
I am very tired with it because with
mysql_fetch_array($Query_Sliders)
syntax don't let me run.

Answer

You are resetting the $tablesliders variable on each loop.

Try making it into an array and incrementing it on each loop.

$tablesliders = array();

while($row_Slider=mysql_fetch_array($Query_Sliders)){
    $QuestionID=$row_Slider['QuestionIDFK'] ;
    $AnswerID=$row_Slider['AnswerIDPK'] ;
    $AnswerValue=$row_Slider['AnswerValue'] ;

    $tablesliders[] = array (
        "QuestionID"  => array([$k] => $QuestionID),
        "$AnswerID" => array([$k] => $AnswerID),
        "$AnswerValue"   => array([$k] => $AnswerValue)
    );
    $k=k+1;
}

Although actually looking at your script I can't imagine that is how you would want it to work (each array would only have the one question, answer and value rather than an array of them all).