php预处理方式向mysql中插入多条数据

php预处理方式向mysql中插入多条数据


DATE: 2017-09-19 10:37:09

原始代码来自:http://www.runoob.com/php/php-mysql-prepared-statements.html

调试代码如下:

<?php

//mysql
$servername = "localhost";
$username = "root";
$password = "******";
$dbname = "yixzm";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
        die("Connect Failed: " . $conn->connect_error);
}

//预处理,个人理解:封装数据库操作,简化多条数据场景下的提交过程
$stmt = $conn->prepare("insert into guests (name, email) values(?, ?)");
//i(int), s(string), d(double)
$stmt->bind_param("ss", $name, $email);

// add data to table
$name = "Sanji";
$email = "sanji@onepiece.com";
$stmt->execute();

$name = "Usopp";
$email = "usopp@onepiece.com";
$stmt->execute();

echo "Insert Successfully!";

$stmt->close();
$conn->close();

?>

这里写图片描述

与之前插入数据的方式

$sql = "insert into guests (name, email)
        values ('Luffy', 'luffy@onepiece.com')";

相比,现在的方式在预处理后,用赋值的方式(如$name = "Sanji";)定义数据后,统一使用$stmt->execute();提交数年的方式显然更适合以后大量数据采用各种骚包算法变着花样以各种姿势插入。

版权声明

弈心博客


本文首发site_name,转载请附上博文链接!