【问题标题】:Data successfully inserted, yet execute() returns false数据插入成功,但execute()返回false
【发布时间】:2016-09-26 14:01:05
【问题描述】:

我在这里搜索了我的问题的答案。有些人可能已经在这里回答了其他版本或驱动程序。这个答案对我的发展有很大帮助。

我的PDOStatement::prepare() 正在返回 true。但我的 PDOStatement::execute(); 返回 false。

然而,这些行已成功插入数据库中。我在 php.net 以及 PDO 文档中搜索了该问题。我的搜索进行得很顺利。

我的简单插入代码如下:

// get current rank into a variable //

$sql = 'SELECT count(email)+1 AS RANK FROM users_main';

$pre = $dbc->prepare($sql);

if($pre){

    $pre->execute(array($email)); // <-- working good ... 

    $res = $pre->fetchObject();

    if($res)$rank=(string)$res->RANK;else $rank='';
}   

// now inserting new user into the table as per his new rank.   

$usercode = substr(md5(gzencode($email)),0,10);
$activationcode = md5(gzencode(substr(md5($email),0,10)));


// inserting the actual row into db ... 

$sql = "INSERT INTO users_main(email,usercode,activation_code,current_rank) VALUES (?,?,?,?)";
$pre = $dbc->prepare($sql);


// debugging ... 
echo '<pre>';

try {   
    $pre->execute(array($email,$usercode,$activationcode,$rank));    // <-- PROBLEM IS HERE . RETURNING FALSE.  
}catch(Exception $e){   
    echo $e->getMessage();  // <--  NO ERROR MESSAGE    
}


echo '<br><br>';

print_r($dbc->errorInfo());    //   <-- here sqlstate is 0000

echo '</pre>';

    /*$emailSubject = 'Welcome Mail!';
    $emailLink = '?b='.$activationCode;
    if(insertEmailQueue('W',$email,$emailSubject,$emailLink))return true;else return false;
    }*/    

除了上述信息之外,我还检查了我尝试插入的每一列的数据类型。一切看起来都很好。 回答这个问题对我真的很有帮助。

更新

我正在调试上面的代码,并试图更改以了解错误所在。我已将代码更改如下:

try {

    $res = $pre->execute(array($email,$usercode,$activationcode,$rank));    // <-- PROBLEM IS HERE . RETURNING FALSE.

}catch(PDOException $e){    
    echo $e->getMessage();  // <--  NO ERROR MESSAGE    
}


echo '<br><br>';

print_r($dbc->errorInfo());    //   <-- here sqlstate is 0000

echo '<br><br>';

print_r($dbc->errorCode());

echo '<br><br>';

print_r($pre->errorCode());

echo '</pre>';

结果如下:

Array
(
    [0] => 00000
    [1] => 
    [2] => 
)


00000

23000    // <-- this is a fatal error as per the documentation.

【问题讨论】:

  • 我看不到你怎么知道execute返回false。
  • 您的 pdo 错误模式是否设置为异常?
  • 我正在转储结果,它显示为bool(false),我也无法捕获任何错误消息。我在重复我的话,行已成功插入。
  • @YourCommonSense 是的。设置好了..
  • 你试试,把“Exception”改成“PDOException”

标签: php mysql pdo pdostatement


【解决方案1】:

经过两天的努力才知道错误是什么,最后我通过尝试获取错误和其他互联网参考找到了。我改变的是

    .... 

    // now inserting new user into the table as per his new rank.   

    $usercode = addslashes(substr(md5(gzencode($email)),0,10));
    $activationcode = addslashes(md5(gzencode(substr(md5($email),0,10))));


    ....

addslashes() 是转义不可接受字符的原始方法之一。

我还是想知道,为什么MySQL接受语句,插入行,插入后返回false。如果我发现为什么会出现这个奇怪的问题,我会更新答案。

感谢大家帮助我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    相关资源
    最近更新 更多