在放入MYSQL数据库之前插入文本和分隔

时间:2012-01-11 16:56:45

标签: php mysql

我想创建一个函数,客户端可以通过textarea上传凭证代码(即复制和粘贴),一旦表单提交,编码将提取每个代码并将其放在具有自己id的数据库中。 / p>

代码示例将是

GBVVVVVVV

HGBBBBBBB

JKKKKKKKK

2 个答案:

答案 0 :(得分:1)

你可以这样做:

$vouchers = explode("\n", $textfield);

将变量$ textfield的每一行放入一个名为$ vouchers的数组中。

然后你可以循环遍历数组中的所有项目:

foreach ($vouchers as &$value) {
    // put your mysql insert here
}

答案 1 :(得分:0)

你会像这样制作一个SQL语句:

// Replace "<table name>" with the name of your table.
// This sets up the first part of the SQL statement. This should look very
// familiar if you have used any flavor of SQL.
$query = 'INSERT INTO <table name> VALUES ';
$is_first = true;

// Loop through each line.
// We assume '\n' is the line separator.
// You will need to replace "<textarea name>" with the proper value.
foreach (explode('\n', $_POST['<textarea name>']) as &$voucher) {
    // This determines whether or not we need a comma to separate multiple
    // records. See note below.
    if ($is_first) $is_first = false; else $query .= ', ';
    // This can be unfamiliar to some who are somewhat familiar with SQL. You can
    // insert more than one record with just one query.
    // Note that we escape the $voucher variable to prevent SQL injections.
    $query .= '(' . mysql_real_escape($voucher) . ')';
}

然后,通过PHP将其发送为普通的SQL语句。请注意,这假设您使用的是post方法。此外,这可能有错误。我根本没有测试它,但它肯定会引导你朝着正确的方向前进。