PHP与MySQL的连接有三种API接口,分别是:
- PHP的MySQL扩展
- PHP的mysqli扩展
- PHP数据对象(PDO)
实例 (MySQLi - 面向过程)
<?php
$con = mysql_connect("localhost","root","");
$select_db = mysql_select_db('test');
if (!$select_db) {
die("连接数据库失败" . mysql_error());
}
//查询代码
$sql = "select * from db_table";
$res = mysql_query($sql);
if (!$res) {
die("could get the res:\n" . mysql_error());
}
while ($row = mysql_fetch_assoc($res)) {
print_r($row);
}
//查询代码
//关闭数据库连接
mysql_close($con);
?>
实例 (MySQLi - 面向对象)
1.连接数据库,检测是否连接成功,关闭连接
//连接mysql数据库
//new 实例化对象
//使用面向对象的mysqli
$mysqli= @new mysqli("localhost","root","","myschool");
//检测是否连接成功
if($mysqli->connect_error){
die('连接数据库失败: ' . $mysqli->connect_error);
}
//关闭连接
$mysqli->close();
2.设置编码格式
$mysqli ->set_charset('utf8');
3.执行sql
$sql="insert into user(id,user,pwd,create_time) values(null,'张三','123456',$time)";
$res=$mysqli->query($sql);