Php – MySQLi Binding results and fetching multiple rows

mysqliPHPprepared-statement

I'm trying to loop over a set of results using MySQLi and the bind / fetch.

static function getConnection() 
{
    if (!isset(self::$db_conn)) 
    {
        self::$db_conn = new mysqli(self::$DBSERVER,self::$DBUSER,self::$DBPASS, ModelBase::$DBNAME) or die(mysql_error(0)." Error handling database connection. ");
    }
    return self::$db_conn;
}

The above is the getConnection() function. It is in a ModelBase class which this class inherits.

$term = "%".$term."%";
$con = ModelBase::getConnection();
$sql = "SELECT name FROM cities WHERE name LIKE ? LIMIT ?";
$query = $con->prepare($sql) or die("Error preparing sql in City ".parent::$db_conn->error);
$query->bind_param("si", $term, $limit) or die("Error binding params in City ".parent::$db_conn->error);
$query->execute() or die("Error executing query in City");

$tmp = "";
$query->bind_result($tmp);
while($query->fetch());
{
    error_log($tmp);
    echo($tmp."\n");
}
$query->close();

However, all I'm getting is the very last result and only once. There should be more then one result, and when I check the following query in phpMyAdmin or at a prompt I get multiple rows.

SELECT name FROM cities WHERE name LIKE %d% LIMIT 150

This problem doesn't appear if I change

$query->bind_result($tmp);

to

$query->bind_result(&$tmp);

Is something else wrong with the syntax?

Is there an easier way to do this? Maybe a way to fetch the object?

Best Answer

You have a semicolon at the end of your while-statement:

while($query->fetch());

(Which of course, makes the $query->fetch() evaluate until it is not true without running the code between the curly brackets for each lap)

Related Topic