I have a table with 6 columns
Sort like:
Database -> kids
|CANDY | COLOR | DRINK | PET | SONG | TOY |
---------------------------------------------------
|cookie | blue | juice | dog | if | ball |
|cake | red | coke | cat | ask | doll |
I want to store
- all the candies in one
ArraycalledCandy[]; - all the colors on
color[]; - all the drinks on
drink[];etc....
I managed to create the arrays with the columns names with a FORLOOP with these lines, which works fine:
$fieldName = mysqli_fetch_field_direct($result, $i)->name; ${$fieldName} = array();
But when the code gets to the WHILE part, that is also inside the loop, to add the columns items inside the arrays[], it adds only the first element and returns to the FORLOOP, goes and adds one element to the next array[] and jumps to the next array[]....
while($row = mysqli_fetch_array($result)){
//inserts itens in the "$array" with columns name
${$fieldName}[] = $row[$i];
}
If I try to "echo" the arrays[] and don´t put a "BREAK" at the end of the WHILE, It returns an error
"Undefined offset: 0 in line..."
And when I put the "BREAK", it works for:
echo candy[0]; = cookie
but doesn't works for:
echo candy[1]; = Undefined offset: 1 in line...
Here is the whole code:
$sql="SELECT candy, color, drink, pet, song, toy FROM kids";
$result = mysqli_query($con,$sql);
$colNumber = mysqli_num_fields($result);
for($i=0;$i<=$colNumber -1;$i++){
$fieldName = mysqli_fetch_field_direct($result, $i)->name;
echo . $fieldName . "<br /><br />";
//Creates an Array with Coll Name from DB
//with dynamic-variable ${$fieldname}
${$fieldName} = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
//inserts the received itens into the array ${$fieldName}
${$fieldName}[] = $row[$i];
printf ("%s (%s)\n", $row[$i], $row[1]);
}
echo ${$fieldName}[0];
echo candy[0];
echo ${$fieldName}[1];
echo candy[1];
echo "<hr />";
}
The WHILE code works when it´s not inside a FORLOOP and if I make a query() like:
SELECT candy FROM kids.
But then, like that, I´d need like 600 lines of repeated code to get what I want and copy/paste again and again for each new coll on the DB table.
Any ideas?
I need it to put the arrays inside HTML
<SELECT><OPTION></SELECT> , then use mt_rand() to shuffle and get different "profiles". This won´t be used with kid stuff, that was just an example.
It will be a virtual crime creator that will shuffle the variables to create different crime hypothesis for law school students work on.
I already spent 3 days reading documentation on http://php.net/manual/pt_BR/mysqli-result.fetch-array.php
and "googling" it but couldn't find any answer.