PHP | MySQL选择查询

SQL 选择 语句用于从数据库表中选择记录。

null

语法: select子句的基本语法是—— 图片[1]-PHP | MySQL选择查询-yiteyi-C++库

要从表中选择所有列,请  * 使用字符。 图片[3]-PHP | MySQL选择查询-yiteyi-C++库

Select查询的实现: 让我们考虑下表“数据”,有三列“FiestNeX”、“LaSTNED”和“AGE”。 图片[4]-PHP | MySQL选择查询-yiteyi-C++库

要选择“数据”表中存储的所有数据,我们将使用下面提到的代码。

选择“使用过程方法查询”:

<?php
$link = mysqli_connect( "localhost" , "root" , "" , "Mydb" );
if ($link == = false ) {
die( "ERROR: Could not connect. "
.mysqli_connect_error());
}
$sql = "SELECT * FROM Data" ;
if ($res = mysqli_query($link, $sql)) {
if (mysqli_num_rows($res) > 0) {
echo "<table>" ;
echo "<tr>" ;
echo "<th>Firstname</th>" ;
echo "<th>Lastname</th>" ;
echo "<th>age</th>" ;
echo "</tr>" ;
while ($row = mysqli_fetch_array($res)) {
echo "<tr>" ;
echo "<td>" .$row[ 'Firstname' ]. "</td>" ;
echo "<td>" .$row[ 'Lastname' ]. "</td>" ;
echo "<td>" .$row[ 'Age' ]. "</td>" ;
echo "</tr>" ;
}
echo "</table>" ;
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);
?>


输出: 图片[4]-PHP | MySQL选择查询-yiteyi-C++库

代码说明:

  1. “res”变量存储函数返回的数据 mysql_query() .
  2. 每次 mysqli_fetch_array() 调用时,它将从 res() 设置
  3. while循环用于循环表“data”的所有行。

选择使用面向对象方法进行查询:

<? php
$ mysqli = new mysqli("localhost", "root", "", "Mydb");
if ($mysqli == = false) {
die("ERROR: Could not connect. "
.$mysqli->connect_error);
}
$sql = "SELECT * FROM Data";
if ($res = $mysqli->query($sql)) {
if ($res->num_rows > 0) {
echo "< table >";
echo "< tr >";
echo "< th >Firstname</ th >";
echo "< th >Lastname</ th >";
echo "< th >Age</ th >";
echo "</ tr >";
while ($row = $res->fetch_array())
{
echo "< tr >";
echo "< td >".$row['Firstname']."</ td >";
echo "< td >".$row['Lastname']."</ td >";
echo "< td >".$row['Age']."</ td >";
echo "</ tr >";
}
echo "</ table >";
$res->free();
}
else {
echo "No matching records are found.";
}
}
else {
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
?>


输出: 图片[4]-PHP | MySQL选择查询-yiteyi-C++库

选择使用PDO方法查询:

<? php
try {
$ pdo = new PDO(" mysql:host = localhost ;
dbname = mydb ", "root", "");
$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 "< table >";
echo "< tr >";
echo "< th >Firstname</ th >";
echo "< th >Lastname</ th >";
echo "< th >Age</ th >";
echo "</ tr >";
while ($row = $res->fetch()) {
echo "< tr >";
echo "< td >".$row['Firstname']."</ td >";
echo "< td >".$row['Lastname']."</ td >";
echo "< td >".$row['Age']."</ td >";
echo "</ tr >";
}
echo "</ table >";
unset($res);
}
else {
echo "No matching records are found.";
}
}
catch (PDOException $e) {
die("ERROR: Could not able to execute $sql. "
.$e->getMessage());
}
unset($pdo);
?>


输出: 图片[4]-PHP | MySQL选择查询-yiteyi-C++库

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享