2016-09-06 58 views
-1

數據庫我希望將多個值添加到MySQL數據庫

table: "country" 
coloums:"id_country,country_name" 

我只有一個文本費爾德:

Country: <input type=text name="country_name" > 
$conn->query("insert into country"); 

我想填補這一費爾德與

「印度,澳大利亞,加拿大等「。

從上面的行(,)必須像對待新的價值。 因此它在數據庫存儲與id_country增量..

+3

爲什麼要這麼做?它會使你的數據很難在以後使用,而且遠沒有好的數據庫設計。 –

+1

你可以建議任何最好的方式來添加多個值.. @ JayBlanchard –

+2

爲什麼它不好@JayBlanchard。他說:「從上面的一句話來看,(,)必須像新的價值一樣對待。」所以它會變成像1,印度2,澳大利亞等 –

回答

3

你可以像下面: -

<?php 

$data = "india,australia,canada"; 
$exploded_data = explode(',',$data); 
$data_to_insert = "('".implode("','",$exploded_data)."')"; 

echo $data_to_insert; 

輸出: -

https://eval.in/636118

https://eval.in/636131

注意: - 您的id_country列必須爲Auto-incremented primary key

如果這樣的話只是一個查詢: -

"INSERT INTO country (country_name) VALUES ".$data_to_insert;

或者

"INSERT INTO country (country_name) VALUES $data_to_insert";

會做的每 - 件事

更好地做到這一點。

2

我不知道如果我理解你,但我可以解釋你,爆炸。它會返回一個字符串數組。

$values = "value1, value2"; 
$explode = explode(",", $values); 

之後您可以繼續以下操作;

$explode[0]; 
$explode[1]; 
+0

爆炸確定如何存儲數據..? –

+0

當您想要將數據存儲在1值中時,您如何讓用戶分離這些值?用空格或','?那麼你可以Implode它 –

2
$countries = ['india','australia','canada'] 

foreach ($countries as $country) { 
    // Run/build you sql query 
} 

SQL示例查詢

INSERT INTO `country` (`country_name`) 
VALUES ('india'); 
2

要處理張貼串首先確保該變量被實際設定並通過初步測試和使用爆炸以產生包含國家名稱的數組。使用mysqliprepared 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();