-2

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

我正在根据业务角色逻辑执行查询。所以在某些情况下,我会选择并更新,在其他情况下,我会选择、更新,然后在第四次插入。这是我如何处理代码的总体结构

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, "");
4

1 回答 1

0

可能是什么问题呢?我还能检查什么?为什么插入在脚本中不起作用,而在 phpmyadmin 中起作用?

欢迎来到程序员的话。
事实上,编程不仅仅是代码。
但是,不幸的是,程序员最多 50% 的时间都花在了回答您上面提出的问题上。这不是一件容易的工作。必须付出相当大的努力。坏消息是,这类问题在问答网站上几乎找不到答案。你自己怎么回答的?所以,你自己的手是你最后的手段。因此,卷起袖子开始调试:

  1. 确保您可以看到 PHP 引发的每个错误。
  2. 确保 PDO 确实在错误时引发异常。
  3. 确保您没有使用@,try..catches和零错误报告来扼杀这些错误。
  4. 设置看门狗来记录错误查询、它们的数据并从 mysql 获得诊断(至少 SHOW PROCESSLIST)。
于 2013-04-04T16:05:29.797 回答