Tomasz Siemiński Tomasz Siemiński - 7 months ago 13
PHP Question

Query gives one indexed array with many elements

I have code like this:

$ch = @new mysqli ($config['db']['host'],$config['db']['user'],$config['db']['password'],$config['db']['database']);
if($result = $ch->query("SELECT pid FROM posts"))
{
while($pids = $result->fetch_assoc())
{
var_dump($pids);
}


var_dump gives me:

array(1) { ["pid"]=> string(1) "1" } array(1) { ["pid"]=> string(1) "2" } array(1) { ["pid"]=> string(1) "3" } array(1) { ["pid"]=> string(1) "4" }


I have two problems:


  1. In database column 'pid' is an int type but the query yields an array of strings

  2. All records from database (4) are saved in one row in an array (got only one index)



Because of that I can't use max(), because it gives me all records (4321).

Answer

You have got 4. Check correctly. The var_dump() executes four times, returning a single array (column - row values):

array(1) {
  ["pid"]=> string(1) "1"
}
array(1) {
  ["pid"]=> string(1) "2"
}
array(1) {
  ["pid"]=> string(1) "3"
}
array(1) {
  ["pid"]=> string(1) "4"
}

If you want everything to be in a single variable, use:

$allPids = array();
while (false != ($pids = $result->fetch_assoc())) {
  $allPids[] = $pids;
}
var_dump($allPids);
Comments