Home > database >  How to put data into mysql database [error]
How to put data into mysql database [error]

Time:10-26

This is my php code:

 //INSERT COMPANY TO DATABASE
    if($result = $connect->query("INSERT INTO `$company_table` (`company_name`, `company_nip`, `company_regon`, `owner_name`, `owner_surname`, `company_post`, `company_city`, `company_street`) VALUES ('$company_name_user', '$company_nip_user', '$company_regon_user', '$owner_name_user', '$owner_surname_user', '$company_post_user', '$company_city_user', '$company_street_user'"))
        {

//pass

 }else
    {
        echo "error 3<br> $user_nick";
        echo $connect->connect_error;
    }

This code always showing me "error 3"

This is my mysql table structure mysql structure

CodePudding user response:

I prefer PDO myself, but using mysqli to safely insert data to prevent injection attacks. The table name is checked separately using a whitelist because you cannot parameterize it as you do the other variables. Also, separating your statement onto different lines (such as query variable), makes it easier to catch the syntax error you have.

$table_options = array("tbl_companies", "tbl_stuff", "tbl_things");

if (in_array($user_selected_table, $table_options) ){
    
    
    $query = "INSERT INTO `$user_selected_table` (`company_name`, `company_nip`, `company_regon`, `owner_name`, `owner_surname`, `company_post`, `company_city`, `company_street`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($query);
    
    $stmt->bind_param("ssssssss", $company_name_user, $company_nip_user, $company_regon_user, $owner_name_user, $owner_surname_user, $company_post_user, $company_city_user, $company_street_user);
    
    
    $stmt->execute();
}else{
    // invalid table name
}

CodePudding user response:

$stmt = $connect->prepare("INSERT INTO company_table(field1, field2, field3) VALUES(?,?,?)");
$stmt->bind_param("sss", $company_name_user, $company_nip_user, $company_region_user);
if($stmt->execute()){
   //Carry out something to show the insert was successful
}
$stmt->close();

Please take a look at my example above.

  • $connect is your database connection.
  • field 1, 2, 3 - these are your table columns. Define these here.
  • ? these comma separated question marks are your values which will be defined in bind_param.
  • bind_param, the "s" is for string and these represent the values in your query ? and you should use i where an integer. You then declare your variables as shown.
  • Then you run an execute, and close the query.

I hope this helps. This is how I do my SQL queries.

  • Related