【问题标题】:mysql error report from php class reporting 0来自php类报告0的mysql错误报告
【发布时间】:2017-02-14 14:24:11
【问题描述】:

我正在尝试通过类中的函数连接到 MySql。同样可以更轻松地完成,但这也是一种学习体验。代码都按预期工作,但是如果 MySql 查询失败,mysqli_error() 返回空白,mysqli_errno() 返回 0。我发现手动将数据输入 mysql 的错误,它是 db 中的一个太短的列,但是我不明白为什么 mysqli_error() 和 mysql_errno() 都没有报告错误。提前感谢您的帮助。

<?php

class FrmAddProduct {

    protected function getDbConnection(){
        return new mysqli("localhost", "root", "****", "test");
    }

    /**
    *all variables are declares and assigned here
    *
    **/
    function commitSignUp (){
        $commitSignUp = "INSERT INTO Login ( `logTitle`,`logFirstName`, `logLastName`,`logLandLine`,) VALUE (\"$this->title\", \"$this->firstName\",\"$this->lastName\", \"$this->landLine\",)";
        if ($this->getDbConnection()->query($commitSignUp)){
            echo "The new product is added.";
            return 1;
        } else {
            echo "Mysql reported this error description: ".mysqli_error($this->getDbConnection()."<br>";
                echo "Mysql reported this error number: ".mysqli_errno($this->getDbConnection());
                return 0;
        }

【问题讨论】:

标签: php mysql


【解决方案1】:

无论你在这里做什么都是完全错误的方法。您正在创建连接实例两次或三次。而且您希望将错误写在那里。

以这种方式更改您的代码。

protected function getDbConnection(){
    return mysqli_connect("localhost", "root", "****", "test");
}

也这样做

function commitSignUp (){
      $commitSignUp = "INSERT INTO
                           Login (
                                     `logTitle`,
                                     `logFirstName`,
                                     `logLastName`,
                                     `logLandLine`,
                                   )
                            VALUE (
                                      \"$this->title\",
                                      \"$this->firstName\",
                                      \"$this->lastName\",
                                      \"$this->landLine\",
                       )";

            $conn = $this->getDbConnection();

            if ($conn->query($commitSignUp)) {
                echo "The new product is added.";
                return 1;
            } else {
                echo "Mysql reported this error description: ".mysqli_error($conn."<br>";
                echo "Mysql reported this error number: ".mysqli_errno($conn);
                return 0;
            }

【讨论】:

  • 这不会改变主要问题的任何内容。它仍然会与 OP 的当前代码执行完全相同的事情
  • 多连接的唯一问题。
  • 最大的问题是混合new Mysqli(OOP 风格),同时尝试使用mysqli_error()(程序风格)来获取错误。它们不能混用。 但是是的,您对保持连接也有很好的看法。我意识到我的第一条评论听起来有点刺耳。 :)
  • 感谢 Vinay 和 Magnus Eriksson。维奈,我认为 getDbConnection 中的“新”应该被删除,因为它是程序风格。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
相关资源
最近更新 更多