我需要在PDO mysql中使用一个查询在mysql数据库中插入数据。
我需要使用mysqli多查询完成同样的事情。
这很好用
$insert ="
insert into comments (user_id,comment) values('$user_id','$comment');
insert into comments2 (user_id,comment) values('$user_id','$comment');
$run = mysqli_multi_query($con,$insert);
但我怎么能在PDO中做到这一点
connection.php:
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'hotwall'; //name of your database
$this->port = '3306';
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
我该怎么做才能插入另一张表
$query = $bdd->execute('insert into comments (user_id,comment)
values('$user_id','$comment')');
答案 0 :(得分:1)
在一个语句中执行这些插入没有一个理由。无论你试图以这种方式解决什么问题,要么不存在,要么以其他方式解决。
但通常只需单独插入即可。
来自connection.php的db类也是一场灾难。创建一个原始PDO连接,然后逐个运行插入:
$stmt = $pdo->prepare("insert into comments (user_id,comment) values(?,?)");
$stmt->execute([$user_id,$comment]);
$stmt = $pdo->prepare("insert into comments2 (user_id,comment) values(?,?)");
$stmt->execute([$user_id,$comment]);
是您需要的所有代码。