PHP与MySQL通信分为以下步骤
1.连接到MySQL服务器
2.发送SQL查询
使用mysqli_connect打开连接
$cxn = mysqli_connect("host","acct","password","dbname")
or die ("message");
$host="localhost";
$user="phpuser";
$password="";
$dbname = "Customer";
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die("Couldn't connect to server.");
$query = "SELECT * FROM Customer";
$result = mysqli_query($cxn,$query)
or die ("Couldn't execute query.");
对于不返回数据的查询,$result中包含查询语句是否执行成功的信息,true或false;
对于返回数据的查询,$result包含指明返回数据位置的标识符。
为减少出错,一般情况下按以下规则使用单双引号:
在字符串前后使用双引号;
在变量名前后使用单引号;
在字面量前后使用单引号。
例子:
$query = "SELECT firstName FROM Customer";
$query = "SELECT firstName FROM Customer WHERE lastName='Smith'";
$query = "UPDATE Customer SET lastName='$last_name'";
使用mysqli_multi_query可以同时执行多个查询语句
$query = "SELECT * FROM Cust;SELECT * FROM OldCust";
mysqli_multi_query($cxn,$query);
但是使用多个语句会导致不安全。如果使用外部数据创建查询语句,一定要进行验证。例如让用户输入一个查询的表明,如果用户输入Friend,则$query = "SELECT * FROM Friend";但是如果用户恶意输入Friend;DELETE TABLE Friend,则$query = "SELECT * FROM Friend;DELETE TABLE Friend";这就会删除数据表全部数据。
关闭连接
mysqli_close($cxn);
选择一个数据库
mysqli_select_db($cxn,"databasename")
or die ("message");
当mysqli_query()失败时会返回错误信息,但是默认不显示,需通过mysqli_error($cxn)显示错误。
例子:
$query = "SELECT * FROM Cust";
$result = mysqli_query($cxn,$query)
or die ("Error: ".mysqli_error($cxn));
获取返回记录个数
$query = "SELECT * FROM ValidUser
WHERE acct = '$_POST[userID]'
AND password = '$password'";
$result = mysqli_query($cxn,$query);
$n = $mysql_num_rows($result);
if($n < 1)
{
echo "User name and password are not valid";
exit();
}
获取最后一个记录的auto_increment字段
$query = "INSERT INTO CustomerOrder (customerID,orderDate) VALUES ($customerID,$date)";
$result = mysqli_query($cxn,$query);
$orderID = mysqli_insert_id($cxn);
$query = "INSERT INTO OrderItem (orderID,color,size,price) VALUES ($orderID,$color,$size,$price)";
$result = mysqli_query($cxn,$query);
获取影响的行数
$query = "UPDATE Student SET status='pass' WHERE score > 50";
$result = mysqli_query($cxn,$query);
$passed = mysqli_affected_rows($cxn);
echo "$passed students passed";
字符转义
php.ini中magic_quotes_gpc在PHP4和PHP5中被默认开启,但在PHP6中不再支持。建议关闭。
$lastName = mysqli_real_escape_string($lastName);
$lastName = mysqli_real_escape_string($_POST['lastName']);