PDO不允许执行插入查询

时间:2013-04-04 15:34:59

标签: php mysql sql pdo

我正面临一个令我疯狂的奇怪问题。我从来没有碰到这样的事情。即使我可以预测这将是非常容易的事情,但我在看它。

我正在基于业务角色逻辑执行查询。所以在某些情况下我会选择并更新,在其他情况下我会做一个选择,更新,然后插入所以第四个。以下是我处理代码的整体结构

Open PDO connection

1 getDataSet 1 (select)
2 ProcessQuery (update)
3 getDataSet 1 (select)
4 ProcessQuery (Insert)

Close PDO connection by setting the PDO object to null.

由于奇怪的原因,插入根本不起作用!选择工作,更新工作没有问题但是当涉及到插入部分它不起作用。它根本不会给我任何错误。实际上,我复制了相同的查询并在phpMyAdmin中执行它并且查询有效!

我应该注意到我要插入的表非常大,并且有超过400万条带有许多索引的记录。

可能是什么问题?我还能检查什么?为什么插入不是从脚本工作,它是从phpmyadmin ??

这是我的代码

这是我用来连接服务器的当前PDO类 http://pastebin.com/XQ2RrhA1

<?php

class connection {

        private $connString;
        private $userName;
        private $passCode;
        private $server;
        private $pdo;
        private $errorMessage;
        protected $lastQueryTime;
        protected $lastQuery;

        private $pdo_opt = array (
                                                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                                                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                                                        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
                                                        );


        function __construct($dbName, $serverName = 'localhost'){

                //sets credentials
                $this->setConnectionCredentials($dbName, $serverName);

                //start the connect
                $this->startConnection();

        }

        function startConnection(){


                        $this->pdo = new PDO($this->connString, $this->userName, $this->passCode, $this->pdo_opt);

                        if( ! $this->pdo){

                                $this->errorMessage  = 'Failed to connect to database. Please try to refresh this page in 1 minute. ';
                                $this->errorMessage .= 'However, if you continue to see this message please contact your system administrator.';
                                echo $this->getError();
                        }
        }


        //this will close the PDO connection
        public function endConnection(){

                $this->pdo = null;
        }

        //return a dataset with the results
        public function getDataSet($query, $data = NULL)
        {
                $start = microtime(true);
                $cmd = $this->pdo->prepare( $query );

                $cmd->execute($data);
                $ret = $cmd->fetchAll();
                //$cmd->closeCursor();
                $this->lastQueryTime = microtime(true) - $start;
                $this->lastQuery = $query;

                return $ret;
        }



        public function processQuery($query, $data = NULL)
        {
                $start = microtime(true);
                           //$this->pdo->beginTransaction();
                $cmd = $this->pdo->prepare( $query );
                $ret = $cmd->execute($data);
                           //$this->pdo->commit();
                           //$cmd->closeCursor();
                $this->lastQueryTime = microtime(true) - $start;
                $this->lastQuery = $query;

                return $ret;
        }


        //return last insert id
        public function lastInsertId($name = NULL) {
                if(!$this->pdo) {
                        return false;
                }

                return $this->pdo->lastInsertId($name);
        }


        public function getOneResult($query, $data = NULL){
                $cmd = $this->pdo->prepare( $query );
                $cmd->execute($data);

                return $cmd->fetchColumn();
        }

        public function getError(){
                if($this->errorMessage != '')
                        return $this->errorMessage;
                else
                        return true;  //no errors found

        }

        //this where you need to set new server credentials with a new case statment
        function setConnectionCredentials($dbName, $serv){

                switch($serv){

                        case default:
                                $this->connString       = 'mysql:host='.$serv.';dbname='.$dbName.';charset=utf8';
                                $this->userName         = 'USER';
                                $this->passCode         = 'PASSWORD';
                        break;



                        }

        }


public function lastQueryTime() {
    if(!$this->lastQueryTime) {
        throw new Exception('no query has been executed yet');
    }
    return $this->lastQueryTime;
}

public function lastQuery() {
    if(!$this->lastQuery) {
        throw new Exception('no query has been executed yet');
    }
    return $this->lastQuery;
}



}



?>

这是我的实际代码

<?php
require('../classes/connection.php');

$db = new connection(DATABASE_NAME, DATABASE_HOST);

$sendUpdate = 0;
$id = 0;
$resultCode = 0;
$callCode = 0;
$total_attempts = 0;
$account_id = 0;
$timer = 0;

$notes = '';
$triggerOn = '';
$subject = '';

if(isset($_POST['sendUpdate'])){
        $sendUpdate = 1;
}

if(isset($_POST['current_call_id'])){
        $id = bigint($_POST['current_call_id']);
}

if(isset($_POST['result_code_menu'])){
        $resultCode = bigint($_POST['result_code_menu']);
}

if(isset($_POST['selected_call_code'])){
        $callCode = bigint($_POST['selected_call_code']);
}

if(isset($_POST['total_attempts'])){
        $total_attempts = bigint($_POST['total_attempts']);
}

if(isset($_POST['account_id'])){
        $account_id = bigint($_POST['account_id']);
}

if(isset($_POST['notes'])){
        $notes = trim($_POST['notes']);
}

if(isset($_POST['triggerOn'])){
        $triggerOn = convertTimeToUTCzone( $_POST['triggerOn'], USER_TIME_ZONE );
}

        $subject = $resultCode;


if(isset($_POST['timer'])){
        $timer = convertTimeToSeconds($_POST['timer']);
}

//CONVERT $time to seconds

        $error_list = '';
        $pass_message = '';

        if($id  < 1){
                $error_list .= '<li>You have selected an invalid link</li>';
        }

        if($callCode == 0){
                $error_list .= '<li>You must select a call code.</li>';
        }

        if($resultCode == 0){
                $error_list .= '<li>You must select a result code.</li>';
        }

        if($timer == 0){
                $error_list .= '<li>You can not reset timer before submitting the form.</li>';
        }      




        //if pass all check
        if($error_list == ''){

                $pass_all = 0;


                //Find out what is the next action
                        $action = $db->getDataSet('SELECT result FROM result_codes WHERE result_code_id = '.$resultCode.' LIMIT 1;' );

                                if( count($action) == 1){
                                        $next_action = $action[0]['result'];
                                } else {
                                        $error_list .= '<li>Error #95: Unknown Error: result code was not found.</li>';
                                        $pass_all = 0;
                                }




                //Close existing open phone call
                if( $next_action == 'FINISH' || $next_action == 'CREATE NEW CALL'  || $next_action == 'TRY AGAIN' ){

                        $statment = $db->processQuery('UPDATE phone_calls SET result_code_id= ?, call_notes= ?, call_duration = ?,
                                                                                  first_attempt_on = if(first_attempt_on IS NULL,  NOW(), first_attempt_on),
                                                                                  first_attempt_by = if(first_attempt_by = "", '.USER_ID.',first_attempt_by),
                                                                                  last_attempt_on = NOW(), total_attempts = total_attempts+1, status=2 WHERE phone_call_id = '.$id.' LIMIT 1;'
                                                                                  , array($resultCode, $notes, $timer) );

                                if($statment){
                                        $pass_all = 1;
                                } else {
                                        $error_list .= '<li>Error #96: System could not update Phone Call</li>';
                                        $pass_all = 0;
                                }
                        $statment = null;
                }




                //Update the existing phone call & Keep it open to be called again
                if( $next_action == 'TRY AGAIN'){


                        $new_call = $db->getDataSet('SELECT call_code_title AS subject FROM call_codes WHERE call_code_id= '.$callCode.' LIMIT 1;' );

                                if( count($new_call) == 1 ){
                                        $subject = $new_call[0]['subject'];
                                } else {
                                        $error_list .= '<li>Error #79: Unknown Error: call code was not found.</li>';
                                }
                        $new_call = null;
                        $this_attempt = $total_attempts+1;

                        if($this_attempt >= 1){
                                $subject = $subject . ' attempt: ' . $this_attempt;
                        }



                                        $statment = $db->processQuery('INSERT INTO phone_calls (account_id, call_code_id, trigger_on, created_on, call_subject, status, last_call_id
                                                                                , call_direction, owner_id, workflow_generated, call_notes)
                                                                                                                 VALUES('.$account_id.', '.$callCode.', "'.$triggerOn.'", NOW(), "'.$subject.'", 1, '.$id.', "OUTBOUND", '.USER_ID.', 1, "");');                                                                                                                                         



                                if($statment ){
                                        $pass_all = 1;
                                } else {
                                        $error_list .= '<li>Error #80: System could not generate a new attempt</li>';
                                        $pass_all = 0;
                                }
                $statment = null;

                }



                //Update the existing phone call THEN assign the activity to the master user define in APP_configuration.php
                if( $next_action == 'MGR REVIEW'){


                        $statment = $db->processQuery('UPDATE phone_calls SET result_code_id= ?, call_notes= ?, call_duration = ?,
                                                                                  first_attempt_on = if(first_attempt_on IS NULL,  NOW(), first_attempt_on),
                                                                                  first_attempt_by = if(first_attempt_by = "", '.USER_ID.',first_attempt_by),
                                                                                  last_attempt_on = NOW(), total_attempts = total_attempts+1,
                                                                                  trigger_on = ?, owner_id = '.CMS_ADMIN_ID.' WHERE phone_call_id = '.$id.' LIMIT 1;'
                                                                                  , array($resultCode, $notes, $timer, $triggerOn) );

                                if($statment){
                                        $pass_all = 1;
                                } else {
                                        $error_list .= '<li>Error #98: System could not update Phone Call</li>';
                                        $pass_all = 0;
                                }
                $statment = null;
                }


                if($sendUpdate == 1 && $error_list == '' && $pass_all == 1 ){

                $statment = $db->processQuery('DELETE FROM phone_calls WHERE last_call_id = '.$id.' LIMIT 1;');

                                if($statment){
                                        $pass_all = 1;
                                } else {
                                        $error_list .= '<li>Error #81: System could not run reverse system flow.</li>';
                                        $pass_all = 0;
                                }                      
                $statment = null;
                }






                //Generate new phone call
                if( $next_action == 'CREATE NEW CALL'){

                        //Find the nect call code to generate

                                $new_call = $db->getDataSet('SELECT ie.action_id, CONCAT(cc.call_code_name, " - ", cc.call_code_title) AS subject FROM inventory_engine AS ie
                                                                                         INNER JOIN call_codes AS cc ON ie.action_id = cc.call_code_id
                                                                                         WHERE ie.call_code_id= ?  AND ie.result_code_id = ? LIMIT 1;', array($callCode,$resultCode ) );

                                if( count($new_call) == 1 ){
                                        $new_callcode_id = $new_call[0]['action_id'];
                                        $subject = $new_call[0]['subject'];
                                } else {
                                        $error_list .= '<li>Error #94: Unknown Error: call code was not found.</li>';
                                }

                                $new_call = null;

                $statment = $db->processQuery('INSERT INTO phone_calls (account_id, call_code_id, trigger_on, created_on, call_subject, status, last_call_id
                                                                                , call_direction, owner_id, workflow_generated, call_notes)
                                                                                                                 VALUES(?, ?, ?, NOW(), ?, 1, ?, "OUTBOUND", ?, 1, "");',
                                                                                                                 array($account_id, $new_callcode_id, $triggerOn, $subject, $id, USER_ID ) );

                                if($statment){
                                        $pass_all = 1;
                                } else {
                                        $error_list .= '<li>Error #99: System could not update Phone Call</li>';
                                        $pass_all = 0;
                                }
                $statment = null;
                }


                if($pass_all == 1 && $error_list == ''){
                        $pass_message = '<li>You have successfully complete the phone call.</li>';
                } else {
                        $error_list .= '<li>Error #100: Unknown Error: Please contact your system admin</li>';
                }

        }


//close database connection
$db->endConnection();


        $return = array();
        if($pass_message != ''){

                $return['msg']   = '<ul>'.$pass_message.'</ul>';
                $return['error'] = false;

        } else {
                $return['msg'] = '<ul>'. $error_list.'</ul>';
                $return['error'] = true;
        }


echo json_encode($return);






?>

这是我的实际代码,不插入记录

http://pastebin.com/QSt03qqx

感谢您的帮助:)

PS 这是我的代码中不会运行的查询,但是当我在PHPmyadmin

中运行它时它会运行
INSERT INTO phone_calls (account_id, call_code_id, trigger_on, created_on, call_subject, status, last_call_id , call_direction, owner_id, workflow_generated, call_notes) VALUES(11601, 1, "2013-04-11 16:36:00", NOW(), "Initial Development attempt: 1", 1, 17132, "OUTBOUND", 1, 1, "");

1 个答案:

答案 0 :(得分:0)

  

可能是什么问题?我还能检查什么?为什么插入不能从脚本工作,它是从phpmyadmin工作?

欢迎来到程序员的话 事实上,编程不只是编写代码 但是,不幸的是,程序员花了50%的时间来回答上面提到的问题。这不是一件容易的事。必须付出相当大的努力。坏消息,这样的问题几乎无法在Q&amp; A网站上找到答案。你自己回答了什么?所以,你自己的手是你的最后手段。这样卷起袖子开始调试:

  1. 确保您可以看到PHP引发的每个错误。
  2. 确保PDO在出错时抛出异常。
  3. 请确保您没有使用@try..catches和零错误报告来解决这些错误。
  4. 设置监视程序以记录错误的查询及其数据并从mysql(至少SHOW PROCESSLIST)获取诊断。