I want to insert the values of a form into the database table called company. But this program again and again tells me that my query did not get executed. May I know why this is so??
I have stored all the values of the form into an array called insert and than I implode the array and name it as newarray so that it is in a form which can be inserted into the database.
But this does not seem to work for me. Please tell me what's the problem in here??
<?php
$host = "localhost";
$name = "root";
$password = "";
$db = "shopinz";
$con = mysqli_connect($host,$name,$password,$db);
$insert = array();
$newarray = array();
if(mysqli_connect_errno()){
echo("Cannot connect to the databse".mysqli_connect_errno());
exit();
}
else{
if($_SERVER['REQUEST_METHOD'] == 'POST'){
foreach($_POST as $value){
if($value == $_POST['submit']){
break;
}
else{
array_push($GLOBALS['insert'],$value);
}
}
$newarray = implode(',',$insert);
$result = mysqli_query($con,"INSERT INTO company (company_name,company_number,company_address) VALUES($newarray)");
if($result){
echo("1 row added");
}
else{
echo("Query not executed");
}
}
}
?>
This line has no significance:
array_push($GLOBALS['insert'],$value);
Push your values to the one that you need which is $insert
unset($_POST['submit']);
foreach($_POST as $value){
$insert[] = "'".$con->real_escape_string($value)."'";
}
$newarray = implode(',',$insert);
Note: I suggest use prepared statements instead.
$insert = $con->prepare('INSERT INTO company (company_name,company_number,company_address) VALUES(?, ?, ?)');
$insert->bind_param('sss', $_POST['company_name'], $_POST['company_number'], $_POST['company_address']);
$insert->execute();
Looking at your code the problem I can see is here:
foreach($_POST as $value){
In your foreach you have $_POST but you dont define what posit it si it should be $_POST['something']