跳到主要内容

PHP连接MySQL

危险

php7新版,不再兼容mysql.dll 而是推荐使用mysqli.dll 和pdo_mysql.dll

因此,像mysql_escape_string此类的函数都不再支持,需要注意

思路:连接服务器 => 创建数据库 => 连接数据库 => 创建数据表

在 php 文件中设置 Content-Type 类型和 字符集 charset (一般是 utf-8)

创建连接

$conn = mysqli_connect('localhost', 'root', '') 
// 参数对应 服务器名字、账号、密码

检测连接

if(!$conn) {
die('连接服务器失败:' . mysqli_error());
// 连接服务器失败退出程序
}

创建数据库

$sql_database = 'create database studentInfo';
if (!mysqli_query($sql_database,$conn)){
echo "数据库创建失败:" . mysqli_error() . "</br>";
}
echo "数据库创建成功</br>";

连接数据库 studentInfo

$sele = mysqli_select_db('studentInfo');
if (!$sele) {
die("连接数据库失败:" . mysql_error());
// 连接数据库失败退出程序
}

创建数据表 student,主键为 id(不为 null int),变量名为 name( 255 位不为 null string ),变量名为 Chinese( 4 位不为 null int),变量名为 English ( 4 位不为 null int),变量名为 Math( 4 位不为 null int)

$sql_table = "create table student(" . 
"id int not null auto_increment, " .
"name char(255) not null, " .
"Chinese int(4) not null, " .
"Math int(4) not null, " .
"primary key ( id ));";
$retval = mysqli_query ( $sql_table, $conn );
if (! $retval) {
echo '数据表创建失败:' . mysqli_error() . "</br>";
}
echo "数据表创建成功</br>";
mysqli_query('set name utd8');
mysqli_close($conn); // 关闭连接