Php 我想向mysql数据库添加多个值
数据库Php 我想向mysql数据库添加多个值,php,mysql,sql,Php,Mysql,Sql,数据库 table: "country" coloums:"id_country,country_name" 我只有一个文本字段: Country: <input type=text name="country_name" > $conn->query("insert into country"); 国家: $conn->查询(“插入国家/地区”); 我想把这片土地填满 印度、澳大利亚、加拿大等 从上一行来看,(,)必须像对待新值一样对待。! 因此,它必须以id\u c
table: "country"
coloums:"id_country,country_name"
我只有一个文本字段:
Country: <input type=text name="country_name" >
$conn->query("insert into country");
国家:
$conn->查询(“插入国家/地区”);
我想把这片土地填满
印度、澳大利亚、加拿大等
从上一行来看,(,)必须像对待新值一样对待。!
因此,它必须以id\u country增量存储在db中。最好对输入文本使用PHP的
explode()
函数,使用,“
作为分隔符,然后通过foreach循环将结果数组中的每个国家添加到数据库中
更多信息:我不确定我是否理解你,但我可以解释你,爆发。它将返回一个字符串数组
$values = "value1, value2";
$explode = explode(",", $values);
之后,您可以继续执行以下操作:
$explode[0];
$explode[1];
您可以按如下方式进行操作:-
<?php
$data = "india,australia,canada";
$exploded_data = explode(',',$data);
$data_to_insert = "('".implode("','",$exploded_data)."')";
echo $data_to_insert;
SQL示例查询
INSERT INTO `country` (`country_name`)
VALUES ('india');
要处理发布的字符串,首先要确保变量已实际设置并通过基本测试,然后使用explode生成包含国家名称的数组。使用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,澳大利亚等等,我在找的是Anant;这就是为什么会出现混乱@Anantupto explode ok如何存储数据..?当您想将数据存储在一个值中时,如何让用户将这些值分开?用空格或,
?你可以让它内爆
$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();