php pdo插入数据
Inserting data is very simple as we already know how to establish connection with mysql (MariaDB) using PDO? We can use the same code as a skeleton and then edit the $sql query to insert data instead of selecting.
插入数据非常简单,因为我们已经知道如何使用PDO与mysql(MariaDB)建立连接 ? 我们可以使用与框架相同的代码,然后编辑$ sql查询以插入数据而不是选择数据。
PHP code to insert data into table using PDO
PHP代码使用PDO将数据插入表
<?php
//Connection Variables
$host = "localhost";
$uname = "username";
$pw = "password";
$db = "DBtest";
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $uname, $pw);
// set error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SQL insert query
$sql = "INSERT INTO users (firstname, lastname, email)
VALUES ('John', 'Abraham', '[email protected]')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e) {
echo $sql . $e->getMessage();
}
//Set Connection state to null
$conn = null;
?>
Output
输出量
New record created successfully
This way, we can interact with MySQL using PDO to easily add new records to database table.
这样,我们可以使用PDO与MySQL进行交互,以轻松地向数据库表中添加新记录 。
翻译自: https://www.includehelp.com/php/pdo-inserting-data-into-tables.aspx
php pdo插入数据