我正在尝试用php和mysql oop向数据库添加一条记录

4sup72z8  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(167)

各位,我很难理解到底发生了什么。我是oops新手,想在数据库中添加一条记录。我有一个类customer,在这个类中,我有一个函数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\u number”列的整数值不正确:“”。
我的数据库字段是:-

ID
first_name
last_name
phone_number
email
codice_fiscale
adress
cap
payment
data_of_join
genre

真的不知道是什么问题。我做了同样的事情,但是用的是同样的sql,一切都很好。

mtb9vblg

mtb9vblg1#

这是一个疯狂的猜测,因为您还没有告诉我们您列的数据类型。
看起来数据库中的phone\u number列用整数表示。你不能那样做™. 许多由用户提供的带有空格或标点符号的电话号码。
读这个:电话号码应该是一个字符串或一些数字类型,有能力保存电话号码?

ajsxfq5m

ajsxfq5m2#

您的代码容易受到sql注入相关的攻击。请学会使用事先准备好的语句
现在,在这种情况下,您不需要使用 $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')";

相关问题