利用php创建数据库(mysql),以及进行相关的增删改查操作

连接数据库服务器


//链接数据库服务器 此文件名拟为conn.php
$conn = new mysqli("localhost","root",'');
//测试
if($conn->connect_error){
	die("服务器连接失败".$conn->connect_error); //输出并结束
}
echo "连接成功";
?>

创建数据库


include "conn.php";//引入连接
//用sql语句 创建数据库
$sql = "create database myDB";
if($conn->query($sql)){
	echo "创建成功";
}else{
	echo "创建失败".$conn->error;
}
?>

创建表


include "conn.php";//引入连接
$conn->select_db("mydb");//选择数据库
//创建表的同时设置字段
$sql = "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 DEFAULT CURRENT_TIMESTAMP
)";
if($conn->query($sql)){
	echo "数据表创建成功";
}else{
	echo "数据表创建失败".$conn->error;
}

?>

添加信息


include "conn.php";//引入连接
$conn->select_db("mydb");//选择数据库
//增
$sql="insert into myguests (firstname,lastname,email) values ('lee','si','[email protected]'),('wang','wu','[email protected]')";
$conn->query($sql);
?>

删除信息


include "conn.php";//引入
$conn->select_db("mydb");//选择
//删
$sql = "delete from myguests where id=1";
$conn->query($sql);
?>

修改信息


include "conn.php";//引
$conn->select_db("mydb");//选
//改
$sql = "update myguests set firstname='zhao' where id=2";
$conn->query($sql);
?>

查找(取)信息


include "conn.php";//引
$conn->select_db("mydb");//选
//查
$sql = "select * from MyGuests";//选择所有信息
$sql = "select firstname from MyGuests";//选择所有数据的部分信息
$sql = "select * from MyGuests where id='1'";//选择部分数据的所有信息
$sql = "select firstname from MyGuests where id='1'";
//排序
$sql = "select * from MyGuests order by id desc";

$result = $conn->query($sql);/
$newarr = [];
if($result->num_rows){
    while($row=$result->fetch_assoc()){
        array_push($newarr,$row);
    }
}
//[["id"=>1,"firstname"=>""],[],[],[]]
$json = json_encode($newarr);
echo $json;
?>

你可能感兴趣的:(mysql,php)