next up previous contents
Next: Update 變更紀錄 Up: Query 紀錄詢問 Previous: Select 查詢資料表   Contents

Where 條件

  1. Where 條件運算子:
    = != > < >= <=
    
  2. 查詢 dyw_author='dywang' 的紀錄。
    [root@kvm8 html]# mysql -uroot -p123qwe \
    -e "use dyw; select * from dyw_tbl where dyw_author='dywang';"
    +--------+-----------+------------+-----------------+
    | dyw_id | dyw_title | dyw_author | submission_date |
    +--------+-----------+------------+-----------------+
    |      3 | MySQL     | dywang     | 2014-12-12      |
    +--------+-----------+------------+-----------------+
    
  3. 可用 AND 及 OR 結合多個條件。
    [root@kvm8 ~]# mysql -uroot -p123qwe \
    -e "use dyw; select * from dyw_tbl where dyw_author='dywang' OR dyw_id=1;"
    +--------+-----------+------------+-----------------+
    | dyw_id | dyw_title | dyw_author | submission_date |
    +--------+-----------+------------+-----------------+
    |      1 | PHP       | david      | 2014-12-24      |
    |      3 | MySQL     | dywang     | 2014-12-12      |
    +--------+-----------+------------+-----------------+
    
  4. 原 php 程式的查詢變數 $sql 加入 where 條件。
    [root@kvm8 html]# vim selectrecord.php 
    [root@kvm8 html]# cat selectrecord.php 
    <?php
    $dbhost = 'localhost:3306';
    $dbuser = 'root';
    $dbpass = '123qwe';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass);
    if(! $conn )
    {
      die('Could not connect: ' . mysql_error());
    }
    $sql = 'SELECT dywphp_id, dywphp_title, 
                   dywphp_author, submission_date
            FROM dywphp_tbl
            WHERE dywphp_author="dywang"';
    
    mysql_select_db('dywphp');
    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
      die('Could not get data: ' . mysql_error());
    }
    while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
    {
        echo "Dywphp ID :{$row['dywphp_id']}  <br> ".
             "Title: {$row['dywphp_title']} <br> ".
             "Author: {$row['dywphp_author']} <br> ".
             "Submission Date : {$row['submission_date']} <br> ".
             "--------------------------------<br>";
    } 
    mysql_free_result($retval);
    echo "Fetched data successfully\n";
    mysql_close($conn);
    ?>
    
  5. 開啟瀏覽器,連上網址 http://kvm8.deyu.wang/selectrecord.php,網頁上列出資料表 dywphp_tbl 中的紀錄,其中第一筆紀錄時間為 0000-00-00 ,因為在網頁以函數 NOW() 輸入時間,php 程式將其判斷為字串。
    Image selectrecord1



2018-06-19