簡體   English   中英

PHP / MySQL將字符串插入數據庫

[英]PHP/MySQL insert string into database

我正在嘗試將多個不同的單詞插入數據庫中(如果它們尚未在數據庫中)。 我從用戶輸入多個類別的文本字段中獲取文本。 我想用逗號分割從此文本字段傳遞的文本,如果尚未插入數據庫,則將其分別插入數據庫。 當前,沒有任何內容輸入數據庫。 在此先感謝您的幫助!

這是我的代碼,用於拆分文本字段數據並插入數據庫中:

$category = trim($_POST['category']);

$cat2 = explode(',', $category);
foreach ($cat2 as $new_interest)
{
$insert_user_interests = sprintf("INSERT INTO interests IF NOT EXISTS name = '". $new_interest . "'" .
                                                 "(name) " .
                            "VALUES ('%s');",
                             mysql_real_escape_string($new_interest));
mysql_query($insert_user_interests);
}

這是您的insert語句:

INSERT INTO interests IF NOT EXISTS name = '". $new_interest . "'" .
                                             "(name) " .
                        "VALUES ('%s')

據我所知,這不是有效的insert語法。 (文檔在這里 。)我認為您將其與create table語法混淆了。 相反,請使用ignore和類似的內容:

INSERT IGNORE INTO interests(name) VALUES(". $new_interest . "')" 

編輯:

正確,如果您不想插入重復項,請在name上創建一個唯一索引:

create index unique interests_name on interests(name);

然后上面的查詢將做您想要的。

暫無
暫無

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

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