PHP | MySQL 选择查询
SQL SELECT语句用于从数据库表中选择记录。
句法 :
select 子句的基本语法是——
要从表中选择所有列, 使用字符。
选择查询的实现:
让我们考虑下表“数据”,其中包含“FirstName”、“LastName”和“Age”三列。
要选择存储在“数据”表中的所有数据,我们将使用下面提到的代码。
使用程序方法选择查询:
0) {
echo "";
echo "";
echo "Firstname ";
echo "Lastname ";
echo "age ";
echo " ";
while ($row = mysqli_fetch_array($res)) {
echo "";
echo "".$row['Firstname']." ";
echo "".$row['Lastname']." ";
echo "".$row['Age']." ";
echo " ";
}
echo "
";
mysqli_free_res($res);
}
else {
echo "No matching records are found.";
}
}
else {
echo "ERROR: Could not able to execute $sql. "
.mysqli_error($link);
}
mysqli_close($link);
?>
输出 :
代码说明:
- “res”变量存储函数mysql_query()返回的数据。
- 每次调用mysqli_fetch_array()时,它都会返回res()集中的下一行。
- while 循环用于循环遍历表“数据”的所有行。
使用面向对象的方法选择查询:
connect_error);
}
$sql = "SELECT * FROM Data";
if ($res = $mysqli->query($sql)) {
if ($res->num_rows > 0) {
echo "";
echo "";
echo "Firstname ";
echo "Lastname ";
echo "Age ";
echo " ";
while ($row = $res->fetch_array())
{
echo "";
echo "".$row['Firstname']." ";
echo "".$row['Lastname']." ";
echo "".$row['Age']." ";
echo " ";
}
echo "
";
$res->free();
}
else {
echo "No matching records are found.";
}
}
else {
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
?>
输出 :
使用 PDO 方法选择查询:
setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
die("ERROR: Could not connect. ".$e->getMessage());
}
try {
$sql = "SELECT * FROM Data";
$res = $pdo->query($sql);
if ($res->rowCount() > 0) {
echo "";
echo "";
echo "Firstname ";
echo "Lastname ";
echo "Age ";
echo " ";
while ($row = $res->fetch()) {
echo "";
echo "".$row['Firstname']." ";
echo "".$row['Lastname']." ";
echo "".$row['Age']." ";
echo " ";
}
echo "
";
unset($res);
}
else {
echo "No matching records are found.";
}
}
catch (PDOException $e) {
die("ERROR: Could not able to execute $sql. "
.$e->getMessage());
}
unset($pdo);
?>
输出 :