1.普通连接
$mysql_server = 'localhost';
$mysql_username = '用户名';
$mysql_password = '用户密码';
$mysql_database = '数据库名';//建立数据库连接
$conn = mysql_connect($mysql_server, $mysql_username, $mysql_password) or die('数据库连接失败!');
//选择某个数据库
mysql_select_db($database, $conn);
//编码转化
mysql_query("set names 'utf8'");
//执行sql
$result = mysql_query(select * from database where id=1);
//提取数据
$row=mysql_fetch_row($result);
在提取数据的时候,我们使用mysql_fetch_row,还可以使用mysql_fetch_assoc和mysql_fetch_array
2.面向对象方法mysqli连接
$mysql_conf = array(
'host' => '127.0.0.1:3306',
'username' => 'root',
'password' => '123456',
'database' => 'test',
);
$db = new mysqli($mysql_conf['host'], $mysql_conf['username'], $mysql_conf['password'], $mysql_conf['database']);
if(mysqli_connect_error()){
die("could not connect to the database:\n" . $mysqli->connect_error);//诊断连接错误
}
$result = $db->query("select * from database where id=1");
$row = $result->fetch_array();
3、PDO方法连接
try {
//配置信息
$dsn = 'mysql:dbname=test;host=localhost';
$username = 'root';
$password = '123456';
$attr = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
//创建一个pdo对象
$pdo = new PDO($dsn, $username, $password, $attr);
//编码转化
$pdo->exec("set names 'utf8'");
//编写sql
$sql = "select * from user where name = :name";
//预处理
$stmt = $pdo->prepare($sql);
$data = [
':name' => 'john'
];
//执行
$stmt->execute($data);
// PDO::FETCH_ASSOC 关联数组形式
// PDO::FETCH_NUM 数字索引数组形式
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($res) {
die('查询成功');
} else {
die('查询失败');
}
$pdo = null;//关闭连接
} catch(PDOException $e) {
//异常
echo $e->getMessage();
}
还不快抢沙发