Reputation: 823
Im working on a form which has a dynamic generated fields. My problem is I cant insert data from those generated fields. I tried this thread How to insert json array into mysql database but Its not working for me.
I tried to populate the data when transferred to PHP but got no luck.
DB Connection
<?php
class DbConfig
{
private $_host = 'localhost';
private $_username = 'root';
private $_password = '';
private $_database = 'machines';
protected $connection;
public function __construct()
{
if (!isset($this->connection)) {
$this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
if (!$this->connection) {
echo 'Cannot connect to database server';
exit;
}
}
return $this->connection;
}
}
?>
JSON data
$scope.columns = [
{"id":1,"brand":"robotworx","tonnage":"200","tableSize":"20x50","pressType":"Kiss Cutting"},
{"id":2,"brand":"fanuc","tonnage":"100","tableSize":"30x60","pressType":"Swing Arm"}
];
Controller
$scope.register=function(){
$http.post("http://localhost/clickermag/controller/register.php", {
'company':$scope.company,
'email':$scope.email,
'phone':$scope.phone,
'position':$scope.position,
'firstName':$scope.firstName,
'lastName':$scope.lastName,
'presses':$scope.columns
})
.then(function(response){
console.log("Data Inserted Successfully");
},function(error){
alert("Sorry! Data Couldn't be inserted!");
console.error(error);
});
}
PHP file
<?php
$data = json_decode(file_get_contents("php://input"));
//including the database connection file
include_once("../classes/Crud.php");
$crud = new Crud();
$company = $data->company;
$email = $data->email;
$phone = $data->phone;
$position = $data->position;
$firstName = $data->firstName;
$lastName = $data->lastName;
$ownedPress = $data->presses;
//insert data to database
$result = $crud->execute("INSERT INTO users(company, email, phone, position, first_name, last_name) VALUES('$company','$email','$phone','$password','$position','$firstName','$lastName')");
$last_id = $crud->user_id;
foreach($data as $item) {
$pressesQuery = $crud->execute("INSERT INTO owned_presses(user_id, brand, tonnage, table_size, press_type) VALUES ('$last_id','$item[brand]','$item[tonnage]','$item[tableSize]','$item[pressType]')");
}
?>
I need to put the data from the generated fields to the second query.
Upvotes: 0
Views: 684
Reputation: 2351
First things first, SQL Injection.
Now,
foreach($data as $item) {
Why are you looping through $data
, shouldn't you be looping through $ownedPress
?
And, I'm not sure how Crud.php
is implemented, but I'd assume it'd be:
$last_id = $result->user_id;
Upvotes: 1