doudou201701 2014-06-18 09:43
浏览 44
已采纳

选择插入不工作

I am trying to insert a number of ids into a new table. The list of ids is taken from another table.

My Code:

     $stmt = $con->prepare('DROP TABLE tblname;
                            CREATE TABLE tblname (
                                id BIGINT
                                );

                            INSERT INTO tblname (id)
                            SELECT tablename2.colname
                            FROM tablename2
                            WHERE (col1 = "value" AND col2 = "value")');

      $stmt->execute();

I create and dump the table because its part of an update script.

(Is there a better way to do that than dump/create?)

The script needs the current list of ids and I am trying to get create a table with those ids. What happens is, whenever I run the code (using putty) it returns "0" and the table remains empty.

What did I do wrong?

Any general help/advice concerning php/mysql welcome too!

  • 写回答

2条回答 默认 最新

  • duan1930 2014-06-18 10:04
    关注

    First, make sure PDO is set to throw exceptions if a query fails:

    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    Then, perhaps catch the exception (or let the exception halt the application) and see what is wrong.
    I do believe your insert query is, erm, off:

    INSERT INTO tblname (id)
    SELECT tblname2.colname
    FROM tablename2
    WHERE col1 = "val"
    

    Just seems ambiguous, and messy, even more: it seems unsafe. However, try this -equally messy- query:

    INSERT INTO tblname (id) VALUES (
        SELECT colname
        FROM tblname2
        WHERE col1 = "val"
    );
    

    Last but not least, make sure you're running PHP version 5.3+, because prior to that version, PDO did not support multiple queries.

    My suggestion, though, is not to use multiple queries for the INSERT query. Instead, I'd use a transaction and separate the select and insert query. I'd also add a safety-net to the DROP TABLE and CREATE TABLE queries, too:

    try
    {
        $con->beginTransaction();//DROP & CREATE:
        if ($con->exec('DROP TABLE IF EXISTS tblname') === false)
        {//query wasn't executed
            $con->rollback();
            exit($con->errInfo());//error
        }
        if ($con->exec('CREATE TABLE IF NOT EXISTS tblname(...);') === false)
        {
            $con->rollback();
            exit($con->errInfo());
        }
        $con->commit();//alter tables.
        $con->beginTransaction();//INSERT TRANSACTION
        $stmt = $con->prepare('INSERT INTO tblname (id) VALUES (:id)');
        $bind = array(
            ':id' => null
        );
        $select = $con->prepare(
            'SELECT colname FROM tblname2 WHERE col1 = :val1 AND col2 = :val2'
        );
        $select->execute(
            array(
                ':val1' => 'value1',
                ':val2' => 'value2'
            )
        );
        while ($row = $select->fetch(PDO::FETCH_ASSOC))
        {
            $bind[':id'] = $row['colname'];
            $stmt->execute($bind);//inserts row
            $stmt->closeCursor();//optional
        }
        $con->commit();//save changes to db
    }
    catch (PDOException $e)
    {
        //rollback transaction
        $con->rollback();
        exit($e->getMessage());//show what went wrong, and exit.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?