表单提交
前台正常表单提交
<?phpheader('Conten-Type: text/html; charset=utf-8');$dbms='mysql'; // 数据库类型$host='localhost'; // 主机名或ip地址$dbname= 'PHPlesson'; //数据库名称$user= 'root'; // 用户名$pass= ''; // 密码$dsn="$dbms:host=$host;dbname=$dbname"; // 拼接成串try {$dbh = new PDO($dsn,$user,$pass);$newstitle = $_REQUEST["newstitle"];$newsimg = $_REQUEST["newsimg"];$newscontent = $_REQUEST["newscontent"];$addtime = $_REQUEST["addtime"];$sql = "INSERT INTO `news`(`newstitle`, `newsimg`, `newscontent`, `addtime`) VALUES ('".$newstitle."','".$newsimg."','".$newscontent."','".$addtime."')";$res = $dbh->exec($sql);$arr = array('message'=>'添加成功','data'=>[],'code'=>1);echo json_encode($arr, JSON_UNESCAPED_UNICODE);$dbh = null;} catch(PDOException $e){die("Error:" . $e.getMessage(). "<br>");}?>
这里一定要注意SQL语句里面变量要用拼接字符串的方式连接起来 不然会是空的。
表格查询
前台正常查询表格
<?phpheader('Conten-Type: text/html; charset=utf-8');$dbms='mysql'; // 数据库类型$host='localhost'; // 主机名或ip地址$dbname= 'PHPlesson'; //数据库名称$user= 'root'; // 用户名$pass= ''; // 密码$dsn="$dbms:host=$host;dbname=$dbname"; // 拼接成串try {$dbh = new PDO($dsn, $user, $pass);$dbh->query('set names utf8');$sql = 'SELECT * FROM `news`';$result = $dbh->query($sql);$arr = array();foreach ($result as $row) {array_push($arr,array('newsid'=>$row['newsid'],'newstitle'=>$row['newstitle'],'newsimg'=>$row['newsimg'],'newscontent'=>$row['newscontent'],'addtime'=>$row['addtime']));}$datas = array('code'=>1,'data'=>$arr,'message'=>'查询成功');echo json_encode($datas);} catch (PDOException $e) {die("Error:" . $e.getMessage(). "<br>");}
这里有两点需要注意,一个是输出的是utf-8的编码,需要$dbh->query('set names utf8');来控制让前台拿到的中文不是乱码,还有一个点就是拿到了数据封装进一个数组内。
