简单的mysqli解决方案:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT * FROM table WHERE 1');
while ( $rows = $resource->fetch_assoc() ) {
print_r($rows);//echo "{$row['field']}";
}
$resource->free();
$db->close();
错误处理:如果出现致命错误,脚本将终止并显示错误消息。
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
使用迭代器: PHP 5.4 添加了支持
$db = new mysqli('localhost','user','password','database');
foreach ( $db->query('SELECT * FROM table') as $row ) {
print_r($row);//echo "{$row['field']}";
}
$db->close();
获取单个记录:此代码不需要循环。
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();