第一步,新增一个Php文件,连接pdo,并将数组中的数据写入Mysql中
实例
$arr_user = [['name' => 'wangdage', 'tximg' => 'images/tx1.jpg', 'time' => '2019-9-20 20:20:21', 'pl' => '真***', 'dz' => 102, 'hf' => 2, 'mov_id' => 1], ['name' => 'wangdage22', 'tximg' => 'images/tx2.jpg', 'time' => '2019-9-22 20:20:21', 'pl' => '真***。', 'dz' => 15, 'hf' => 12, 'mov_id' => 3], ['name' => 'xiaomei', 'tximg' => 'images/tx3.jpg', 'time' => '2019-9-22 20:15:21', 'pl' => '最喜欢张无忌了。', 'dz' => 55, 'hf' => 21, 'mov_id' => 1], ['name' => 'whz', 'tximg' => 'images/tx4.jpg', 'time' => '2019-9-23 20:20:21', 'pl' => '我喜欢赵敏。', 'dz' => 201, 'hf' => 53, 'mov_id' => 1], ['name' => '蓝色妖姬', 'tximg' => 'images/tx5.jpg', 'time' => '2019-9-15 8:20:21', 'pl' => '不怎么***。', 'dz' => 143, 'hf' => 26, 'mov_id' => 8], ['name' => '红***', 'tximg' => 'images/tx6.jpg', 'time' => '2019-9-15 8:20:21', 'pl' => '还行吧。', 'dz' => 143, 'hf' => 26, 'mov_id' => 6], ['name' => '找不到回家的路', 'tximg' => 'images/tx7.jpg', 'time' => '2019-9-15 8:20:21', 'pl' => '还行吧。', 'dz' => 13, 'hf' => 16, 'mov_id' => 2], ['name' => '采姑娘的小蘑菇', 'tximg' => 'images/tx8.jpg', 'time' => '2019-9-15 8:65:24', 'pl' => '还行吧。', 'dz' => 1, 'hf' => 6, 'mov_id' => 3] ]; $sql = "insert into `pl` set `user_name`=:user_name, `tximg`=:tximg, `time`=:time, `pinlun`=:pl, `dianzan`=:dz, `huifu`=:hf, `mov_id`=:mov_id"; $stmt=$pdo->prepare($sql); foreach ($arr_user as $v) { $name=$v['name']; $tximg=$v['tximg']; $time=$v['time']; $pl=$v['pl']; $dz=$v['dz']; $hf=$v['hf']; $mov_id=$v['mov_id']; $stmt->bindparam('user_name',$name,pdo::PARAM_STR); $stmt->bindparam('tximg',$tximg,pdo::PARAM_STR); $stmt->bindparam('time',$time,pdo::PARAM_STR); $stmt->bindparam('pl',$pl,pdo::PARAM_STR); $stmt->bindparam('dz',$dz,pdo::PARAM_INT); $stmt->bindparam('hf',$hf,pdo::PARAM_INT); $stmt->bindparam('mov_id',$mov_id,pdo::PARAM_INT); if ($stmt->execute()) { if ($stmt->rowCount() > 0) { echo '成功添加' . $stmt->rowCount(). '条记录, 该记录的主键id是: ' . $pdo->lastInsertId(); } } else { die('<pre>' . print_r($stmt->errorInfo(), true)); } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
第二步,在公共文件中存储从mysql中读取的数据,供其它页面引用
实例
$db = [ 'type'=> 'mysql', 'host' => 'localhost', 'name' => 'ckdatabase', 'user' => 'root', 'pwd' => '123456' ]; //配置dsn $dsn="{$db['type']}:host={$db['host']};dbname={$db['name']}"; // print_r($dsn); //连接数据库 try{ $pdo=new pdo($dsn,$db['user'],$db['pwd']); //捕获异常 }catch(exception $e){ //停止继续执行,并输出错误文件 die('connection filed:'.$e->getmessage()); } $sql="select * from cates"; $stmt=$pdo->prepare($sql); $stmt->execute(); $cates=$stmt->fetchAll(pdo::FETCH_ASSOC); $sql1="select * from `movies`"; $stmt1=$pdo->prepare($sql1); $stmt1->execute(); $movies=$stmt1->fetchAll(pdo::FETCH_ASSOC); $sql = "select * from `system`"; $stmt = $pdo->prepare($sql); $stmt->execute(); $system = $stmt->fetchAll(pdo::FETCH_ASSOC); $sql = "select * from `pl`"; $stmt = $pdo->prepare($sql); $stmt->execute(); $pl = $stmt->fetchAll(pdo::FETCH_ASSOC); ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例
第三步,在其它文件中,引用pdo文件
总结:从mysql中读取的数据都是二维数组,在使用时用循环的方式使用数据。