如何使用 LIKE 子句在 PHP 指令碼中匹配 MySQL 表中的資料?


我們可以將 WHERE...LIKE 子句的類似語法應用到 PHP 函式 mysql_query() 中。此函式用於執行 SQL 命令,之後可以使用另一個 PHP 函式 mysql_fetch_array() 獲取所有選定的資料(如果 WHERE...LIKE 子句與 SELECT 命令一起使用)。

但是,如果 WHERE...LIKE 子句與 DELETE 或 UPDATE 命令一起使用,則不需要進一步呼叫 PHP 函式。

為了說明這一點,我們提供以下示例:

示例

在這個示例中,我們編寫了一個 PHP 指令碼,它將返回名為 ‘tutorial_tbl’ 的表中的所有記錄,其中作者姓名包含 ‘jay’

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   $sql = 'SELECT tutorial_id, tutorial_title,
      tutorial_author, submission_date
      FROM tutorials_tbl
      WHERE tutorial_author LIKE "%jay%"';
     
   mysql_select_db('TUTORIALS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }
   
   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Tutorial ID :{$row['tutorial_id']} <br> ".
         "Title: {$row['tutorial_title']} <br> ".
         "Author: {$row['tutorial_author']} <br> ".
         "Submission Date : {$row['submission_date']} <br> ".
         "--------------------------------<br>";
   }
   echo "Fetched data successfully
";    mysql_close($conn); ?>

更新於: 2020-06-22

322 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.