以下我们将在 SQL SELECT 命令中使用 WHERE...LIKE 子句来从MySQL数据表 tutorials_tbl 中读取数据。
以下是我们将tutorials_tbl表中获取tutorial_author字段中以"jay"为结尾的的所有记录:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl
-> WHERE tutorial_author LIKE '%jay';
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
1 rows in set (0.01 sec)
mysql>
你可以使用PHP函数的mysql_query()及相同的SQL SELECT 带上 WHERE...LIKE 子句的命令来获取数据。
该函数用于执行SQL命令,然后通过 PHP 函数 mysql_fetch_array() 来输出所有查询的数据。
但是如果是DELETE或者UPDATE中使用 WHERE...LIKE 子句的SQL语句,则无需使用mysql_fetch_array() 函数。
以下是我们使用PHP脚本在tutorials_tbl表中读取tutorial_author字段中以"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\n";
mysql_close($conn);
?>