brunobliss
brunobliss

Reputation: 366

why is this sql query only returning two results?

i have a MySQL database (testDB) containing one table (info) with a couple of columns, id and name. This table has 5 rows of data.

The goal is to retrieve the whole column name and store it's values into an array. Problem is, it's only storing two results in the $res variable (results of the query), and it's actually echoeing them twice ( ??? )

PS: Please ignore the $q for now, that will be a query string to the file generated by user input (on input box)

<?php

class engine {
  public function userInput() {
    $q = $_GET['q'];
    $con = mysqli_connect("localhost","root","","testDB");
    if(!$con) {
      echo "Impossible to connect: " . mysqli_errno();
    } else {
      $this->connectMe($con,$q);
    }
  }

  private function connectMe($con,$q) {
    $sql = "SELECT `name` FROM `info`"; // will select the entire column `name` on the `info` table
    $qry = mysqli_query($con,$sql); // parameter1 is the connection , parameter 2, the sql command
    $res = mysqli_fetch_array($qry); // stores the query results into an array
    foreach ($res as $value) { // loops through the array and assigns each element to $value
      $this->findMatches($value,$q); // parse each element of the array and $q to findMatches function 
    }
  }

  private function findMatches($value,$q) {
    echo "Array value: " . $value . " random query " . $q . "<br/>";
  } // WHY U NO output more than one result !!!???
}

$start = new engine(); // creates the object above
$start->userInput(); // calls the method userInput
?>

Upvotes: 0

Views: 195

Answers (3)

Marc B
Marc B

Reputation: 360682

mysqli_fetch_array() by default returns a dual-keyed array. e.g.

SELECT foo, bar FROM ...

will give you

$result = array(
   'foo' => 'foo value',
   0 => 'foo value',
   'bar' => 'bar value',
   1 => 'bar value'
 );

You can trivially verify this with var_dump($res) in your code.

You probably want

mysqli_fetch_array($qry, MYSQLI_ASSOC) // field name keys only
mysqli_fetch_array($qry, MYSQLI_NUM)   // numerica keys only

instead.

Upvotes: 1

Halil Bilgin
Halil Bilgin

Reputation: 513

change foreach with this:

while($res = mysqli_fetch_array($qry)) {
  $this->findMatches($value, $q)
}

Upvotes: 0

Ende Neu
Ende Neu

Reputation: 15783

This is not true:

$res = mysqli_fetch_array($qry); // stores the query results into an array

mysqli_fetch_array fetches one row, you have to put it in a loop:

while($res = mysqli_fetch_array($qry)){
  //doSomething
}

Upvotes: 3

Related Questions