我有这个查询,这是完美的工作。
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) {
以上查询工作正常,并输入数据。但我有两个文本框,从那里我得到的数据与逗号分开,并插入到两个不同的表。我怎么能做到呢?我发现了其他的帖子,但不能使他们工作
从两个输入字段收集数据,分解成多个部分并组合成一个数组,然后迭代生成并执行sql:
$pieces=array_merge( explode(',', $qs_ansen), explode(',', $qs_ansE) );
foreach( $pieces as $piece ){
/* process piece */
}
SPL的MultipleIterator可以帮助您实现这一点。
例如
<?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)
Btw: mysql_*扩展已被弃用,这种处理适合使用预处理语句。
edit: sscce using PDO:
<?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)
)
');
}