PHP mysqli query() 函数
示例 - 面向对象的样式
执行针对数据库的查询:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// Perform query
if ($result = $mysqli -> query("SELECT * FROM Persons")) {
echo "Returned rows are: " . $result -> num_rows;
// Free result set
$result -> free_result();
}
$mysqli -> close();
?>
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// Perform query
if ($result = $mysqli -> query("SELECT * FROM Persons")) {
echo "Returned rows are: " . $result -> num_rows;
// Free result set
$result -> free_result();
}
$mysqli -> close();
?>
查看底部的程序样式示例。
定义和用法
query() / mysqli_query() 函数执行某个针对数据库的查询。
语法
面向对象的风格:
$mysqli -> query(query,
resultmode)
程序风格:
mysqli_query(connection, query, resultmode)
参数值
参数 | 描述 |
---|---|
connection | 必需。规定要使用的 MySQL 连接。 |
query | 必需,规定查询字符串。 |
resultmode | 可选。一个常量。可以是下列值中的任意一个:
|
技术细节
返回值: | 针对成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查询,将返回一个 mysqli_result 对象。针对其他成功的查询,将返回 TRUE。如果失败,则返回 FALSE。 |
---|---|
PHP 版本: | 5+ |
PHP 更新日志: | 在 PHP 5.3.0 中新增了异步查询的功能。 |
示例 - 程序样式
执行针对数据库的查询:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Perform query
if ($result = mysqli_query($con, "SELECT * FROM Persons")) {
echo "Returned rows are: " . mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Perform query
if ($result = mysqli_query($con, "SELECT * FROM Persons")) {
echo "Returned rows are: " . mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>