【php基础】pdo操作与mysql 增删改查基本语法

时间:2021-12-14 07:36:49

<?php

// $dsn = ‘数据库类型:host=数据库主机名;dbname=默认数据库名称‘;
$db = [
	‘type‘    =>‘mysql‘,
	‘host‘    =>‘127.0.0.1‘,
	‘dbname‘  =>‘base‘,
	‘username‘=>‘root‘,
	‘password‘=>‘root‘
];
$dsn = $db[‘type‘].":host=". $db[‘host‘].";dbname=".$db[‘dbname‘];
try{
	$pdo = new PDO($dsn,$db[‘username‘],$db[‘password‘]);
}catch(PDOException $e){
	die( ‘链接失败:‘.$e->getMessage());
}

$data = [
	‘pid‘=>‘4‘,
	‘title‘=>‘人员列表‘,
	‘controller‘=>‘Admins‘,
	‘method‘=>‘admin_lists‘,
	‘ishidden‘=>‘0‘,
	‘status‘=>0
]; 


//1.创建数据库
$sql = ‘CREATE DATABASE `base`‘;
//2.创建数据表
$sql = "CREATE TABLE `admins` (
`id`       INT(10) unsigned NOT NULL  COMMENT‘用户ID‘ AUTO_INCREMENT,
`username` CHAR(20) NOT NULL COMMENT‘用户名‘,
`email`    CHAR(30) NOT NULL COMMENT‘邮箱‘,
`password` CHAR(30) NOT NULL COMMENT‘密码‘,
`status`   TINYINT(1) NOT NULL DEFAULT‘0‘ COMMENT‘状态:0正常,1禁用‘, 
`add_time` DATETIME NOT NULL COMMENT‘创建时间‘,
PRIMARY KEY (`id`)
) ENGINE= InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";

//3.增删改查
//3.1 新增
$sql = "INSERT INTO `admins`(username,email,password,status,add_time) VALUES(‘wangbin‘,‘[email protected]‘,‘".md5(123456)."‘,‘0‘,NOW())";
//3.2 删除
$sql = "DELETE FROM `admins` WHERE username=‘wangkai‘ AND id=4";

//3.3 更新
$sql = "UPDATE `admins` SET username=:name,status=:status WHERE id=1";

//3.4 查
$sql = "SELECT * FROM `admins`";

$stmt = $pdo->prepare($sql);
//参数绑定
// if($stmt->execute([‘name‘=>‘wangxin‘,‘status‘=>1])){
if($stmt->execute()){
	// 1.新增时可调用
	// echo "执行成功,新增记录ID:".$pdo->lastInsertId();

	// 2.增删改,可用
	// echo "执行成功,手影响条数:".$stmt->rowCount();

	//3.查询(一条) PDO::FETCH_ASSOC 关联部分
	// echo "<pre>".print_r($stmt->fetch(PDO::FETCH_ASSOC),true);
	
	//4.查询(全部)二维数组
	echo "<pre>".print_r($stmt->fetchAll(PDO::FETCH_ASSOC),true);
}else{
	$err = $stmt->errorInfo();
	print_r($err);
}

  总结:创建PDO对象 链接数据库 new PDO("mysql:host=主机地址;dbname=数据表名");

     PDO执行操作:1.$stmt = $pdo->prepare($sql)  2.$stmt->execute();

     PDO执行后返回值:操作执行后成功返回true ,查失败返回false ;

     PDO常用操作:

      1.新增返回ID:$pdo->lastInsterId();

      2.增删改返回受影响记录条数:$pdo->rowCount();

      3.查操作返回单条结果集:$result->fetch() 默认返回一条数据,指向下一位,默认返回(索引 关联数组)FETCH::ASSOC 关联数组

      4.查操作返回全部结果集:$result->fetchAll();

     mysql 常用语句: 创建库 CREATE DATABASE `database name`;

               创建表 CREATE TABLE `table name`(

                `id` NOT NULL COMMENT‘备注‘ AUTO_INCREMENT ,

                `status` NOT NULL DEFAULT‘默认值‘,

                .....

                PRIMARY KEY (`id`);

                ) ENING = InnoDB AUTO_INCREMENT=1  DEFAULT CHARSET=utf8;

      增:INSERT INTO `table_name`(field_name1,....)  VALUES(values1,...);

      删:DELETE FROM `table_name` WHERE field_name=value;

      改:UPDATE `table_name` SET field_name=value,field_name=value;

      查:SELECT `field_name`,... FROM `table_name`;

      当前使用到的数据库函数:NOW() 当前时间