pdo 预处理
/* 通过调用驱动程序创建一个PDO实例 */ // 获取请求体,@的作用为屏蔽警告,可去除。 $post = @file_get_contents('php://input'); // 解析成数组 $post = json_decode( $post, true ); $name=$post[0]['name']; $age=$post[0]['age']; $phone=$post[0]['phone']; $dsn = 'mysql:dbname=mic12345;host=127.0.0.1'; $user = 'admin_read'; $password = 'matrix11'; try { $db = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } $sql="INSERT INTO test(test_name,test_age,test_phone) VALUE(:test_name,:test_age,:test_phone)"; $stmt=$db->prepare($sql); //进行参数的绑定 $stmt->bindValue(":test_name",$name); $stmt->bindValue(":test_age",$age); $stmt->bindValue(":test_phone",$phone);
//$stmt->bindParam(":test_name",$name);
//$stmt->bindParam(":test_age",$age);
//$stmt->bindParam(":test_phone",$phone);
// 执行这个sql 语句 $result=$stmt->execute();
批量新增数据:
<?php /* 通过调用驱动程序创建一个PDO实例 */ // 获取请求体,@的作用为屏蔽警告,可去除。 $post = @file_get_contents('php://input'); // 解析成数组 $post = json_decode($post, true); $dsn = 'mysql:dbname=mic12345;host=127.0.0.1'; $user = 'admin_read'; $password = 'matrix11'; try { $db = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } $sql = "INSERT INTO test(test_name,test_age,test_phone) VALUE(:test_name,:test_age,:test_phone)"; $stmt = $db->prepare($sql); foreach ($post as $item) { $stmt->bindvalue( ':test_name', isset($item['name']) ? $item['name'] : '' ); $stmt->bindvalue( ':test_age', isset($item['age']) ? $item['age'] : '' ); $stmt->bindvalue( ':test_phone', isset($item['phone']) ? $item['phone'] : '' ); $result = $stmt->execute(); } if ($result) { echo 123; } else { echo 456; }
结果: