MySQLi 绑定结果并获取多行
我正在尝试使用 MySQLi 和绑定/获取来循环一组结果。
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;
}
上面是getConnection()函数。它位于该类继承的 ModelBase 类中。
$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();
然而,我得到的只是最后的结果,而且只有一次。应该有多个结果,当我在 phpMyAdmin 中或在提示符下检查以下查询时,我会得到多行。
SELECT name FROM cities WHERE name LIKE %d% LIMIT 150
如果我改变就不会出现这个问题
$query->bind_result($tmp);
到
$query->bind_result(&$tmp);
语法还有其他问题吗?
有没有更简单的方法来做到这一点?也许有一种获取对象的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
while 语句末尾有一个分号:(
当然,这会使 $query->fetch() 评估,直到它不为 true,而无需在每圈的大括号之间运行代码)
You have a semicolon at the end of your while-statement:
(Which of course, makes the $query->fetch() evaluate until it is not true without running the code between the curly brackets for each lap)