我在创建表并在同一查询中向其插入数据时遇到问题。我的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");
}
答案 0 :(得分:3)
您创建名为admins
的表,但尝试在表admin
你也不需要插入id字段,因为它是AUTO_INCREMENT
而mysql会为你做。
修复插件,如下所示:
INSERT INTO admins (username, password, name, email) VALUES ('admin', '21232f297a57a5a743894a0e4a801fc3', 'Your Name', 'you@yourdomain.com');
答案 1 :(得分:1)
您正在为AUTO_INCREMENT COLUMN指定值。您应该将此值留空,以便MySQL自动填充
答案 2 :(得分:0)
尝试使用PDO::prepare()
代替PDO::exec()