0

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.

Divakarcool
  • 473
  • 6
  • 20

2 Answers2

2

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);
}
Ravish
  • 2,383
  • 4
  • 37
  • 55
  • If i want to update 5 with id 1 and 6 with id 2, and 7 with id 3 . then ? – Divakarcool Jan 02 '16 at 12:01
  • so, do you already have those id's in the table? if so, then I think you should probably be executing an update query, instead insert. If these are new values, then you should keep the id column empty, and let id be auto incremented. – Ravish Jan 02 '16 at 15:14
1
$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')
Alfiza malek
  • 994
  • 1
  • 14
  • 36