[英]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.