我正在处理一个具有动态生成字段的表单。我的问题是我无法从这些生成的字段中插入数据。我尝试了这个线程How to insert json array into mysql database但它不适合我。
我尝试在传输到 PHP 时填充数据,但没有成功。
数据库连接
<?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 数据
$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 文件
<?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]')");
}
?>
我需要将生成字段中的数据放入第二个查询中。
最佳答案
首先,SQL Injection .
现在,
foreach($data as $item) {
为什么要循环 $data
,难道不应该循环 $ownedPress
吗?
而且,我不确定 Crud.php
是如何实现的,但我认为它是:
$last_id = $result->user_id;
关于php - 在 Angularjs 中将 JSON 数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667470/