📜  PHP | MySQL WHERE 子句

📅  最后修改于: 2022-05-13 01:55:29.094000             🧑  作者: Mango

PHP | MySQL WHERE 子句

WHERE子句用于仅过滤由用户给出的特定条件满足的那些记录。换句话说,SQL WHERE 子句用于限制受 SELECT、UPDATE 或 DELETE 查询影响的行数。

句法 :
where 子句的基本语法是——
选择 Column1 , Column2 ,...。
FROM 表名
WHERE 条件

WHERE 子句的实现:

让我们考虑下表“数据”,其中包含“名字”、“姓氏”和“年龄”三列。


要选择“Firstname”为“ram”的所有行,我们将使用以下代码:

使用程序方法的 Where 子句:

 0){
        echo "";
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        while($row = mysqli_fetch_array($res)){
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        }
        echo "
FirstnameLastnameage
" . $row['Firstname'] . "" . $row['Lastname'] . "" . $row['Age'] . "
";         mysqli_free_result($res);     } else{         echo "No Matching records are found.";     } } else{     echo "ERROR: Could not able to execute $sql. "                                  . mysqli_error($link); }    mysqli_close($link); ?>

输出 :

代码说明:

  1. “res”变量存储函数mysql_query()返回的数据。
  2. 每次调用mysqli_fetch_array()时,它都会返回res()集中的下一行。
  3. while 循环用于循环遍历表“数据”的所有行。

使用面向对象方法的 Where 子句:

connect_error);
}
  
$sql = "SELECT * FROM Data WHERE Firstname='ram'";
if($res = $mysqli->query($sql)){
    if($res->num_rows > 0){
        echo "";
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        while($row = $res->fetch_array()){
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        }
        echo "
FirstnameLastnameAge
" . $row['Firstname'] . "" . $row['Lastname'] . "" . $row['Age'] . "
";         $res->free();     } else{         echo "No matching records are found.";     } } else{     echo "ERROR: Could not able to execute $sql. "                                      . $mysqli->error; }    $mysqli->close(); ?>

输出 :

使用 PDO 方法的 Where 子句:

setAttribute(PDO::ATTR_ERRMODE, 
                        PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " 
                    . $e->getMessage());
}
  
try{
    $sql = "SELECT * FROM Data WHERE Firstname='ram'"; 
    $res = $pdo->query($sql);
    if($res->rowCount() > 0){
        echo "";
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        while($row = $res->fetch()){
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        }
        echo "
FirstnameLastnameAge
" . $row['Firstname'] . "" . $row['Lastname'] . "" . $row['Age'] . "
";         unset($res);     } else{         echo "No records matching are found.";     } } catch(PDOException $e){     die("ERROR: Could not able to execute $sql. "                                     . $e->getMessage()); }    unset($pdo); ?>

输出 :