我在变量中有一些值(以逗号分隔)。 我想逐个在数据库中插入这些值

我在变量中有一些值(以逗号分隔)。 我想逐个在数据库中插入这些值

问题描述:

My Code is given below :

$trend=5,6,7;
$variableAry=explode(",",$trend); 
            foreach($variableAry as $var)
            {
    $sql="insert into trending_lawyer(id,lawyers_id)values('','$var')";
    $query=mysql_query($sql);
}

Please suggest me to what to do/modify in this code to insert values in database.

我的代码如下: p>

  $ trend = 5  ,6,7-; 
 $的variableAry =爆炸( “”,$趋势);  
 \ foreach($ variableAry as $ var)
 {
 $ sql =“insert into trending_lawyer(id,lawyers_id)values('','$ var')”; 
 $ query = mysql_query($ sql);  
} 
  code>  pre> 
 
 

请建议我在此代码中做什么/修改以在数据库中插入值。 p> div>

What about doing it something like:

$trend='5,6,7';
$variableAry=explode(",",$trend); 
foreach($variableAry as $var)
{
    $sql="insert into trending_lawyer(id,lawyers_id)values('','$var')";
    $query=mysql_query($sql);
}

There are other ways to optimize you code, but, for starters, this should work for you.

Just realized that you are trying to insert id as part of insert statement, if id is a PR and AI column, you can skip it in you insert statement, so, you code will look like:

$trend='5,6,7';
$variableAry=explode(",",$trend); 
foreach($variableAry as $var)
{
    $sql="insert into trending_lawyer(lawyers_id)values('$var')";
    $query=mysql_query($sql);
}

$variableAry = explode(",", $trend);
$sql = "insert into trending_lawyer(id,lawyers_id)values";
for ($i = 0; $i < count($variableAry); $i++) {
    $sql.="('','$variableAry[$i]'),";
}
$sql=trim($sql,',');
$query = mysql_query($sql);

Query looks like :

insert into trending_lawyer(id,lawyers_id)values('','5'),('','6'),('','7')