php MySQL
作者:互联网
php MySQL
全是面向过程的
连接connect
MySQLi 面向过程
使用mysqli_connect($servername, $username, $password)
通过mysqli_connect_error()报错
使用mysqli_close()关闭连接
$servername="localhost";
$username="root";
$password="654321";
$con=mysqli_connect($servername,$username,$password);
if(!$con)
die('Unable to connect:'.mysqli_connect_error());
echo "连接成功";
创建MySQL数据库
使用mysqli_query($connect,$sql)创建数据库
//创建数据库
$sql="create database myDB";
if(mysqli_query($con,$sql)){
echo "Insert successfully!";
}else{
echo "Unable to insert!".mysqli_error($con);
}
mysqli_close($con);
创建表
mysqli_query() 函数执行某个针对数据库的查询。
//连接数据库要改成以下
$servername="localhost";
$username="root";
$password="654321";
$dbname="myDB";
$con=mysqli_connect($servername,$username,$password,$dbname);
//创建表
$sql2="create table MyGuests(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if(mysqli_query($con,$sql2)){
echo "插入表成功";
}else{
echo "插入失败 : ".mysqli_error($con);
}
插入数据
//插入数据
//Student(Sno,Sname,Sage,Ssex)学生表
$sql="insert into student values (1,'网购用',21,'男');";
if(mysqli_query($con,$sql)){
echo "插入成功";
}else{
echo "插入失败".mysqli_error($con);
}
插入多条数据
使用mysqli_multi_query()函数执行多条SQL语句
//插入多条数据
$sql="insert into student values (2,'狗吠',21,'男');";
$sql="insert into student values (3,'张海',19,'男');";
if(mysqli_multi_query($con,$sql)){
echo "插入成功";
}else{
echo "插入失败";
}
读取数据
先写好查询语句 , 然后将结果赋值给变量$result
通过函数mysqli_num_rows()判断返回的数据
如果是多条数据 , 通过函数fetch_assoc()将结果放到关联数组中并循环输出
$sql="select * from student";
$result=mysqli_query($con,$sql);
//Student(Sno,Sname,Sage,Ssex)学生表
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result)){
echo "Sno : ".$row['Sno']." , Sname : ".$row['Sname']." , Sage : ".$row['Sage']." , Ssex : ".$row['Ssex'];
echo "<br>";
}
}else{
echo "没有结果";
}
标签:MySQL,echo,query,connect,sql,mysqli,php,con 来源: https://www.cnblogs.com/yyyStudy/p/15550947.html