我正在尝试从多个输入发送多个查询,但名称相同。
这是我需要运行的查询
$sql = "INSERT INTO cv_education VALUES (
'$id', '$school_name', '$school_desc', '$school_start_date', '$school_end_date'
)";
这些是输入
<input type="text" class="form-control" name="school_name[]" id="exampleInputName2"
placeholder="Institution name">
<textarea class="form-control" rows="3" name="school_desc[]"
placeholder="Tell us about what you did there"></textarea>
<input type="number" id="ed_start_date" name="school_start_date[]"
placeholder="Date" value="2015">
<input type="number" id="ed_end_date" name="school_end_date[]"
placeholder="Date" value="2016">
但是用户可以添加更多具有相同名称的输入,如何从多个具有相同名称的输入中运行多个查询?
我试过“foreach”但它只适用于一个var。
答案 0 :(得分:0)
使用用户数据创建SQL非常不安全。不要这样做,否则我会写入您的某个输入字段'); TRUNCATE cv_education; --
,您的所有数据都将消失。
使用PDO或DBAL。
以下是PDO的示例:
<?php
$conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass); // change it
$sql = 'INSERT INTO cv_education (' .
' school_name, school_desc, school_start_date, school_end_date' .
') VALUES (' .
' :school_name, :school_desc, :school_start_date, :school_end_date' .
')';
$count = count($_POST['school_name']);
for ($i = 0; $i < $count; $i++) {
$stmt = $conn->prepare($sql);
$stmt->bindParam('school_name', $_POST['school_name'][$i]);
$stmt->bindParam('school_desc', $_POST['school_desc'][$i]);
$stmt->bindParam('school_start_date', $_POST['school_start_date'][$i]);
$stmt->bindParam('school_end_date', $_POST['school_end_date'][$i]);
$stmt->execute();
}