HTML表单输入字段以逗号分隔

时间:2012-08-08 08:50:42

标签: php mysql html

我试图找出如何在一个表单中的单个文本框中输入多个单词输入,每个单词用逗号(,)分隔,然后根据逗号分隔单词,并将每个单词作为单独的记录插入db

我想到的是接受输入

然后使用php的explode函数分离出单词,并存储在db中,但我不知道如何在db中存储。

4 个答案:

答案 0 :(得分:3)

我知道一堆mysql_ *函数的答案会进来,所以不好添加准备好的查询路径。

这不是完美的,但你会明白这个想法

// Get the array of words
$words = explode( ',', $formname );

// Create an array of :word1, :word2, :word3, etc for use in binding
foreach( range( 1, count( $words ) ) as $wordnumber ) {
    $bind[] = ':word'.$wordnumber;
}

// Create the sql query
$sql = sprintf( "insert into table ( word ) values ( %s )", implode( '),(', $bind ) );

// Prepare the query
$stmnt = $pdo->prepare( $sql );

// Bind each word
foreach( $words as $k => $word ) {
    $stmnt->bindValue( ":word" . ++$k, $word );
}

// Execute
$stmnt->execute();

答案 1 :(得分:2)

你也可以用PDO做到这一点:

<?php 
//Connect safely to your database
try {
    $db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}


if ($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['words'])) {

    $sql = "INSERT INTO words_table (word) VALUES (:word)";
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':word', $word);

    foreach (explode(',', $_POST['words']) as $word) {
        $word = trim($word);
        if (empty($word)) {
            continue;
        }
        $stmt->execute();
    }
}
//Your form
?>
<h1>Words</h1>
<form method="POST" action="">
    <input type="text" name="words"/>
    <input type="submit" name="submit" value="Submit"/>
</form>

答案 2 :(得分:0)

如果您需要将单词封装在引号中,这应该可以解决问题:

<?php

$myString='sometext,someothertext,and something else';
$query="insert into table1 (columnName) values (('".str_replace(',',"'),('",$myString)."'))";

echo $query;
?>

输出:

insert into table1 (columnName) values (('sometext'),('someothertext'),('and something else')) 

这将根据mysql insert multiple values syntax正确插入多条记录。

答案 3 :(得分:0)

$str = $_POST['words'];
$piece = explode(',',$str);
foreach($piece as $substr){
    mysql_query("INSERT INTO test (words) VALUES ('".$substr."');";
}