views:

251

answers:

1

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?

+2  A: 

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)

blazer
Well I had already fixed it, but it is funny how this turns up after [another similar incident](http://joshuakehn.com/blog/index.php/basic/view/39/One-line-of-code).
Josh K