簡體   English   中英

在文本框中用逗號分隔的文本在MYSQL中添加新行

[英]Add new row in MYSQL from Comma Separated text in textbox

我有一個PHP / MYsql問題。

我正在嘗試在每個逗號后插入新行。

基本上,我想要這個功能:

假設我們有一個包含以下文本的文本框:

籃球,網球,足球,排球->提交按鈕

單擊提交按鈕后,我想在每個單詞后的一個表中插入新行。

基本上,我希望這樣的結果在數據庫中

id      category
1       Basketball
2       Tennis
3       Futbol
4       Volleyball

有人可以幫助我嗎?

謝謝 :)

您可以循環瀏覽每個,然后分別添加。

$input = "Basketball, Tennis, Futbol, Volleyball";
foreach (explode(',',$input) as $piece)
{
    $piece = mysql_real_escape_string(trim ($piece));
    $sql = "INSERT INTO table VALUES($piece)";
    //Run sql
}

您可以像這樣在一個查詢中執行此操作:

$Input = explode(',', 'a, b, c, d, e, f, g');
$Query = 'INSERT INTO Table(TableColumn) VALUES';

foreach ($Input as $Entry)
{
    $Query .= '("' . $Entry . '"), ';
}

$Query = substr_replace($Query, '', -2);

mysql_query($Query);

輸出的查詢將如下所示:

INSERT INTO Table(TableColumn) VALUES("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g")

只需從超級全局GET / POST / REQUEST數組中獲取值即可:

$categories = $_REQUEST['categories'];

使它們成為單獨的值:

$categories = explode(",", $categories);

為數組中的每個值創建一個SQL語句並執行它。

foreach($categories as $category) {
    $category = trim($category); // Remove possible whitespace
    $sql = "INSERT INTO table (category) VALUES ('%s')";
    $sql = sprintf($sql, mysql_real_escape_string($category));
    mysql_query($sql);
}

最短的代碼:

$Input = explode(',', 'a, b, c, d, e, f, g');
if($Input){
    echo('INSERT INTO Table(TableColumn) VALUES ("'.
      implode('"),("',$Input).'")');
} 

但是,您需要使$ Input轉義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM