在PHP中使用explode函数并使用for循环插入数据库

时间:2015-01-02 14:07:43

标签: php mysql mysqli explode

这是我想分三步完成的事情。

1-)从表单中获取名称。名称将使用逗号之间的逗号输入到表单中。

2-)从数据库中获取名称的ID。

3-)将这些名称插入表格中。

我希望我明确表达了我想做的事情。

这是我到目前为止所做的事情。 (我正在使用单页,在此处排除表格)

$writer_name = "Franz Kafka, Agatha Christie, George Bernard Shaw"; // I used a
//variable instead of using a form value here
$thing_id = 10;

$values_select = explode(",", $writer_name);
echo $values_select[0]; // returns Franz Kafka, our explode function worked

$who = "SELECT writer_id FROM writer_name WHERE writer_name = '$values_select[]'"; 

// I stuck here, I need to get all the writer's ID's and store it in an array 
// in order to insert below X times (depends on how many writers are entered), right? But how?

$who_result = $sqli->query($who);
$who_row = $who_result->fetch_array();
$who_finish = $who_row['writer_id']; 

$values = explode(",", $writer_name);
$control = count($values) - 1;
$new_values = $sqli->prepare("INSERT INTO book(thing_id, person_id) VALUES(?,?)");
for ($i = 0; $i < count($values); $i++) {
    if (!empty(trim($values[$i]))) {
        $new_values .= "('" . trim($values[$i]) . "')";
    }
    if ($control == $i) {
        $new_values .= ";";
    } else $new_values .= ",";
}
    $thing->bind_param("ii", $thing_id, $values[$i]); // using integer because I insert data into a junction table that accepts only ID values)
    $thing->execute();

2 个答案:

答案 0 :(得分:1)

您可以查询所有数组值:

$who_finish = array();
while(list($k, $v)=each($values_select)) {
    $v = $sqli->real_escape_string(trim($v));
    $who = "SELECT writer_id FROM writer_name WHERE writer_name = '$v'";
    $who_result = $sqli->query($who);
    $who_row = $who_result->fetch_array();
    $who_finish[] = $who_row['writer_id'];
}

或更好(顺便说一句,你检查拼写错误等吗?)是这样一次查询所有: SELECT writer_id, writer_name FROM writer_name WHERE writer_name IN ("Franz Kafka", "Agatha Christie", "George Bernard Shaw")

要在表中插入值(我不太了解你的代码所以假设在这里):

$new_values_q = $sqli->prepare("INSERT INTO book(thing_id, person_id) VALUES(?,?)");

while(list($k, $v)=each($who_finish)) {
    $new_values_q->bind_param("ii", $thing_id, $v); // $v should be author_id
    $new_values_q->execute();
}
$new_values_q->close();

答案 1 :(得分:1)

它可能会有所帮助,而不是经过测试。

 $writer_name = "Franz Kafka, Agatha Christie, George Bernard Shaw";

$values_select = explode(",", $writer_name);

foreach($values_select as $sel){
    $query = "INSERT INTO book (thing_id, person_id)
SELECT $thing_id, location
FROM   writer_name
WHERE  writer_name  = ".trim($sel);
$sqli->query($query);
}