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

时间:2016-07-21 13:07:41

标签: php mysql

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

WebRequest

然后我尝试使用以下脚本

将数据插入此表
$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;

1 个答案:

答案 0 :(得分:1)

$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()

Additionaly:

如果你试图从另一个表填充表,没有其他步骤,你可以直接通过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"
  }
}