1

我试图弄清楚如何在单个文本框中输入多个单词,每个单词用逗号(,)分隔,然后基于逗号分割单词并将每个单词作为单独的记录插入到数据库中。

我想到的是接受输入

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

4

4 回答 4

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();
于 2012-08-08T08:59:39.543 回答
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>
于 2012-08-08T09:10:54.643 回答
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 插入多个值语法正确插入多条记录。

于 2012-08-08T08:55:53.753 回答
0
$str = $_POST['words'];
$piece = explode(',',$str);
foreach($piece as $substr){
    mysql_query("INSERT INTO test (words) VALUES ('".$substr."');";
}
于 2012-08-08T08:57:16.437 回答