我的查询工作正常。
foreach (explode(', ', '$qs_ansen') as $piece) {
$piece = mysql_real_escape_string(trim ($piece));
$answers_query = "INSERT INTO answers (answer, qs_id, test_id, ans)
VALUES('$piece', '$last_id', '$test_id', '$qs_ansE')";
mysql_query($answers_query);
}
我如何以一次爆炸或任何其他方式分隔两个文本框的字符串并将它们插入单独的列中?
foreach (explode(', ', '$qs_ansen, $qs_ansE') as $piece) {
以上查询工作正常并输入数据。 但我有两个文本框,我可以通过用逗号分隔并插入两个不同的表来获取数据。我怎么能做到这一点?? 我找到了其他帖子,但无法让它们发挥作用
答案 0 :(得分:0)
从两个输入字段中收集数据,爆炸成碎片并组合成一个数组,然后迭代生成并执行sql:
$pieces=array_merge( explode(',', $qs_ansen), explode(',', $qs_ansE) );
foreach( $pieces as $piece ){
/* process piece */
}
答案 1 :(得分:0)
SPL MultipleIterator可以为您提供帮助 E.g。
<?php
$_POST = array( // Only for demostration purposes.....
'ansE' => '10,11,12,13,14',
'answer_en' => 'A1,B2,C3,D4'
);
$it = new MultipleIterator;
$it->attachIterator( new ArrayIterator( explode(',', $_POST['ansE']) ) );
$it->attachIterator( new ArrayIterator( explode(',', $_POST['answer_en']) ) );
foreach( $it as $e ) {
echo $e[0], ' : ', $e[1], "\r\n";
}
打印
10 : A1
11 : B2
12 : C3
13 : D4
并且您只需在查询中使用$ e [0]和$ e [1]
(请注意,ansE中的14
项尚未处理,请参阅MultipleIterator::MIT_NEED_ANY)
顺便说一下:mysql_* extension is deprecated这种处理适合使用prepared statements。
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo); // boilerplate, seting up temp.tables and sample data for this example
$it = new MultipleIterator;
$it->attachIterator( new ArrayIterator( explode(',', $_POST['ansE']) ) );
$it->attachIterator( new ArrayIterator( explode(',', $_POST['answer_en']) ) );
$stmt = $pdo->prepare('
INSERT INTO
soAnswers
(ansE,answer_en)
VALUES
(?,?)
');
// Warning: the prepared statement uses positional placeholders
// This only works as long as the position and the order of the iterators in the multipleiterator are in sync
// (call the two attachIterator the other way round and the result will be wrong)
// named parameters like VALUES (:anse, :answer_en) are a bit more robust in this sense.
foreach( $it as $e ) {
$stmt->execute( $e );
}
// and now check the contents of the table
foreach( $pdo->query('SELECT * FROM soAnswers', PDO::FETCH_ASSOC) as $row ) {
echo join(', ', $row), "\r\n";
}
// boilerplate, seting up temp.tables and sample data for this example
function setup($pdo) {
$_POST = array( // 0nly for demostration purposes.....
'ansE' => '10,11,12,13,14',
'answer_en' => 'A1,B2,C3,D4'
);
$pdo->exec('
CREATE TEMPORARY TABLE soAnswers (
id int auto_increment,
ansE varchar(32),
answer_en varchar(32),
primary key(id)
)
');
}