我正在尝试使用php和mysql OOP向数据库添加记录

问题描述:

everyone, I have a hard time to understand what is going on. I'm new on OOPS and wanted to add a record to my database. I have a class customer and in that class, I have a function create() that makes a new record and insert into DB. My connection is working, I instantiate(hope that is the right term) that function and then I call 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;
    }

going to my page to see if I get any result. I have Incorrect integer value: '' for column 'phone_number' at row 11366.

My database fields are: -

ID
first_name
last_name
phone_number
email
codice_fiscale
adress
cap
payment
data_of_join
genre

Really don't know what is the problem. I made the same thing but in procedural same SQL and everything works just fine.

Your code is open to SQL injection related attacks. Please learn to use Prepared Statements

Now, in this case, you do not need to use $this-> to use the variables. $this is used when the variables are accessible class members. However, in your cases, these are function parameters.

In the current code, you can change the SQL string as follows:

$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')";

This is a wild guess because you haven't told us the data types of your columns.

It looks like your phone_number column is represented in your database by an integer. You Can't Do That™. Many telephone numbers furnished by users with spaces or punctuation.

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