gpt4 book ai didi

php - 如何用一个查询PDO mysql在多个表中插入数据?

转载 作者:行者123 更新时间:2023-11-29 02:45:23 24 4
gpt4 key购买 nike

我需要通过 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 中做到这一点

连接.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')');

最佳答案

使用 2 个查询,而不是一个。当然必须是参数化查询。

$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]);

是您需要的所有代码。

关于php - 如何用一个查询PDO mysql在多个表中插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43203874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com