gpt4 book ai didi

php - CREATE TABLE 和 INSERT,相同的查询

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:03 25 4
gpt4 key购买 nike

<分区>

我在创建表并在同一个查询中向其中插入数据时遇到问题。我的PHP脚本如下

<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

try {
$db = new pdo('mysql:host=' . $request->hostname . ';dbname=' . $request->dbname, $request->username, $request->password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q = "CREATE TABLE admins (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
password varchar(32) NOT NULL,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

INSERT INTO admin (id, username, password, name, email) VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'Your Name', 'you@yourdomain.com');";

try {
$db->exec($q);
output("success");
}
catch(PDOException $e) {
output("Failed to create tables->" . $e->getMessage());
}
}
catch(PDOException $ex) {
output('Unable to connect. Make sure your connection info is correct.');
}
?>

表已创建,但是插入不起作用。它提示 admins 表还不存在。好的,这是有道理的。我怎样才能使这项工作?

我尝试修改 exec 行来做一个单独的查询来插入,但是 if 失败了

$create = $db->exec($q);
if ($create)
{
$q = "INSERT INTO admin (id, username, password, name, email) VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'Your Name', 'you@yourdomain.com');";
$db->exec($q);
output("success");
}

25 4 0