table: "country"
coloums:"id_country,country_name"
我只有一個文本費爾德:
Country: <input type=text name="country_name" >
$conn->query("insert into country");
我想填補這一費爾德與
「印度,澳大利亞,加拿大等「。
從上面的行(,)必須像對待新的價值。 因此它在數據庫存儲與id_country增量..
table: "country"
coloums:"id_country,country_name"
我只有一個文本費爾德:
Country: <input type=text name="country_name" >
$conn->query("insert into country");
我想填補這一費爾德與
「印度,澳大利亞,加拿大等「。
從上面的行(,)必須像對待新的價值。 因此它在數據庫存儲與id_country增量..
你可以像下面: -
<?php
$data = "india,australia,canada";
$exploded_data = explode(',',$data);
$data_to_insert = "('".implode("','",$exploded_data)."')";
echo $data_to_insert;
輸出: -
和
注意: - 您的id_country
列必須爲Auto-incremented primary key
。
如果這樣的話只是一個查詢: -
"INSERT INTO country (country_name) VALUES ".$data_to_insert;
或者
"INSERT INTO country (country_name) VALUES $data_to_insert";
會做的每 - 件事
更好地做到這一點。
最好是使用在輸入文本PHP的explode()
功能,採用", "
作爲分隔符,然後將結果數組到數據庫中添加每個國家通過foreach循環。
我不知道如果我理解你,但我可以解釋你,爆炸。它會返回一個字符串數組。
$values = "value1, value2";
$explode = explode(",", $values);
之後您可以繼續以下操作;
$explode[0];
$explode[1];
爆炸確定如何存儲數據..? –
當您想要將數據存儲在1值中時,您如何讓用戶分離這些值?用空格或','?那麼你可以Implode它 –
$countries = ['india','australia','canada']
foreach ($countries as $country) {
// Run/build you sql query
}
SQL示例查詢
INSERT INTO `country` (`country_name`)
VALUES ('india');
要處理張貼串首先確保該變量被實際設定並通過初步測試和使用爆炸以產生包含國家名稱的數組。使用mysqli
和prepared statements
可以讓您構建一次sql語句,綁定必要的參數和變量一次,但很快執行多次。
$dbhost = 'localhost';
$dbuser = 'xxx';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli($dbhost, $dbuser, $dbpwd, $dbname);
/* make sure the posted variable isn't empty */
$countries=!empty($_POST['country_name']) && stristr($_POST['country_name'], ',') ? $_POST['country_name'] : false;
if($countries){
/* explode the string to create the array */
$countries=explode(',',$countries);
/* construct sql statement for use as a prepared statement */
$sql='insert into `country` set `country_name`=?';
/* prepare the statement object */
$stmt=$db->prepare($sql);
/* bind the param to the variable */
$stmt->bind_param('s', $country);
/* iterate through all countries from POSTed string and execute the statement */
foreach($countries as $country){
$stmt->execute();
}
}
$stmt->close();
$db->close();
爲什麼要這麼做?它會使你的數據很難在以後使用,而且遠沒有好的數據庫設計。 –
你可以建議任何最好的方式來添加多個值.. @ JayBlanchard –
爲什麼它不好@JayBlanchard。他說:「從上面的一句話來看,(,)必須像新的價值一樣對待。」所以它會變成像1,印度2,澳大利亞等 –