【问题标题】:I'm trying to add a record to the database with php and mysql OOP我正在尝试使用 php 和 mysql OOP 向数据库添加记录
【发布时间】:2019-04-14 12:04:22
【问题描述】:

大家,我很难理解发生了什么。我是 OOPS 的新手,想在我的数据库中添加一条记录。我有一个班级客户,在那个班级中,我有一个函数 create() 可以创建一条新记录并插入到 DB 中。我的连接正常,我实例化(希望这是正确的术语)该函数,然后调用 create()。

$costumer = new Customer($args);
$date = date("Y-m-d");
$result = $costumer->create("Nome", "Cognome", 2, "email3@email.com", "12", "address", 00133, "payment", $date, "male");  

   public function create($first_name, $last_name, $phone_number, $email, $codice_fiscale, $adress, $cap, $payment, $data_of_join, $genre) {

        $sql = "INSERT INTO costumers (first_name, last_name, phone_number, email, codice_fiscale, adress, cap, payment, data_of_join, genre) 
        VALUES ('$this->first_name','$this->last_name','$this->phone_number','$this->email','$this->codice_fiscale','$this->adress','$this->cap','$this->payment','$this->data_of_join','$this->genre')";

        $result = self::$database->query($sql);

        if(!$result) {
            echo self::$database->error;
            echo self::$database->errno;
        }

        return $result;
    }

去我的页面看看我是否得到任何结果。我在第 11366 行的“phone_number”列有不正确的整数值:''。

我的数据库字段是:-

ID
first_name
last_name
phone_number
email
codice_fiscale
adress
cap
payment
data_of_join
genre

真的不知道是什么问题。我做了同样的事情,但在程序相同的 SQL 中,一切正常。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您的代码对SQL injection 相关的攻击是开放的。请学会使用Prepared Statements

    现在,在这种情况下,您不需要使用 $this-> 来使用变量。当变量是可访问的类成员时使用$this。但是,在您的情况下,这些是函数参数。

    在当前代码中,你可以改变SQL字符串如下:

    $sql = "INSERT INTO costumers (first_name, last_name, phone_number, email, codice_fiscale, adress, cap, payment, data_of_join, genre) 
            VALUES ('$first_name','$last_name','$phone_number','$email','$codice_fiscale','$adress','$cap','$payment','$data_of_join','$genre')";
    

    【讨论】:

    • 非常感谢......你救了我的命。但为什么没有抛出错误,因为我使用它的方式不好?
    • @AdrianLupu 你需要打开错误报告。您可能也有一些异常处理。见:stackoverflow.com/questions/1053424/…
    【解决方案2】:

    这是一个疯狂的猜测,因为您没有告诉我们您的列的数据类型。

    看起来您的 phone_number 列在您的数据库中由一个整数表示。你不能那样做™。用户提供的许多电话号码带有空格或标点符号。

    阅读:phone number should be a string or some numeric type that have capacity to save phone number?

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      相关资源
      最近更新 更多