Reputation: 11
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
Upvotes: 0
Views: 69
Reputation: 411
$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.?
and you should use i where an integer. You then declare your variables as shown.I hope this helps. This is how I do my SQL queries.
Upvotes: 0
Reputation: 2009
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
}
Upvotes: 1