gpt4 book ai didi

PHP 未在 MySQL 临时表中插入自动增量字段

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

我使用以下 PHP 脚本创建了一个临时表

$query = "CREATE TEMPORARY TABLE people(id int(11) not null auto_increment, first_name varchar(25), second_name varchar(25), primary key(id))";
$q=$pdo->prepare($query);
$q->execute();

然后我尝试使用以下脚本将数据插入到该表中

$query2 = "INSERT INTO people(first_name, second_name) VALUES(:firstname,:secondname)";
$q2=$pdo->prepare($query2);
$q2->bindValue(':firstname', $firstname,PDO::PARAM_STR);
$q2->bindValue(':secondname', $secondname,PDO::PARAM_STR);
$q2->execute;

我尝试插入的数据来自另一个表。起初,这似乎是由基本错误引起的问题,但我无法弄清楚问题出在哪里,因为当我运行此脚本时(见下文),我看到所有字段都已创建

$query3 = "DESCRIBE people";
$q3 = $con->prepare($query3);
$q3->execute();
$row = $q3->fetchAll(PDO::FETCH_COLUMN);
print_r($row);

最佳答案

$query2 = "INSERT INTO people(first_name, second_name) VALUES(:firstname,:secondname)";
$q2=$pdo->prepare($query2);
$q2->bindValue(':firstname', $firstname,PDO::PARAM_STR);
$q2->bindValue(':secondname', $secondname,PDO::PARAM_STR);
$q2->execute;

缺少 execute() 方法的 ()

另外:

如果您尝试从另一个表填充该表,中间没有其他步骤,您可以直接通过 mysql 执行此操作:

$query2 = "INSERT INTO people(first_name, second_name)
select firstname, secondname from otherTABLE where something = 'xy'";
$pdo->exec($query2);

直接在数据库中执行此操作会减少 php 尝试执行相同操作时出错的机会。

你的脚本的其余部分是正确的,我在本地测试过:

$pdo = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', '', array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));

$query = "CREATE TEMPORARY TABLE people(id int(11) not null auto_increment, first_name varchar(25), second_name varchar(25), primary key(id))";
$q = $pdo->prepare($query);
$q->execute();

$firstname = 'test';
$secondname = 'what';

$query2 = "INSERT INTO people(first_name, second_name) VALUES(:firstname,:secondname)";
$q2 = $pdo->prepare($query2);
$q2->bindValue(':firstname', $firstname, PDO::PARAM_STR);
$q2->bindValue(':secondname', $secondname, PDO::PARAM_STR);
$q2->execute();

$pdo->exec("INSERT INTO people(first_name, second_name) SELECT 'prename', 'surname'");

$result = $pdo->query('SELECT * FROM people');
echo '<pre>';
var_dump($result->fetchAll());
exit;

显示:

array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["first_name"]=>
string(4) "test"
["second_name"]=>
string(4) "what"
}
[1]=>
array(3) {
["id"]=>
string(1) "2"
["first_name"]=>
string(7) "prename"
["second_name"]=>
string(7) "surname"
}
}

关于PHP 未在 MySQL 临时表中插入自动增量字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505141/

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