Reputation: 2594
i want to insert the array values into database with same contact id,
i want like this
contactid languageid
124 1
124 2
this is my array value of languageid:Array ( [0] => 1 [1] => 2 [2] => ) and my contactid = 124
can any one tell me how do this,
$queryinsert="INSERT INTO contactlanguage (contactid,languageid) VALUES ('$languageId','$contactId')";
mysql_query($queryinsert);
print $queryinsert;
Upvotes: 1
Views: 1593
Reputation: 2330
You can do that like this
<?php
$con=mysqli_connect("your_db_ip","your_username","your_password","your_db_name");
$array = array(1,2,3);
$contactId = 124;
foreach($array as $value){
$languageId = $value;
$queryinsert="INSERT INTO contactlanguage (contactid,languageid) VALUES ('$contactId','$languageId')";
mysqli_query($con,$queryinsert);
}
?>
Upvotes: 0
Reputation: 11984
First Remember that mysql_* functions are depreciated and you are obsolete to sql injection because you are directly passing user inputs to the query.Its time to switch into mysqli_* or pdo.
Iterate over your languageid array and insert each one like this and you need to change to column names order in your query.
$arrlanguageid = array ( 0 => 1 , 1 => 2);
$contactid = 124;
foreach($arrlanguageid as $key=>$val){
$queryinsert="INSERT INTO contactlanguage (contactid,languageid) VALUES ('$contactid','$val')";
mysql_query($queryinsert);
}
You can use for loop or foreach for looping over an array
Upvotes: 0
Reputation: 896
Try this:
$languageid = array(1, 2);
$contactid = 124;
foreach($languageid as $key=>$id) {
$statement = "INSERT INTO contactlanguage (contactid, languageid) VALUES ('$contactid', '$id')"
mysql_query($statement);
}
Upvotes: 0
Reputation: 926
$queryinsert="INSERT INTO contactlanguage (contactid,languageid) VALUES ('$languageId','$contactId')";
mysql_query($queryinsert);
print $queryinsert;
your iteration values are wrong. You passed on values to the query is in wrong formate,
Check your first field is contactid and second one is languageid, and your first value is languageid and second is contactid,
So in this case, your languageid goes in contactid field and contactid goes into languageid field. So make it proper as follows,
$languageid = array(xx, xx); // Which is your array values
$contactid = xxx; // which is your conatec value.
foreach($languageid as $key=>$val) {
$statement = "INSERT INTO contactlanguage (contactid, languageid) VALUES ('".$contactid."', '".$val."')"
mysql_query($statement);
}
Upvotes: 0
Reputation: 7948
You just have a column mismatch (your columns have switched). Consider this example:
// provided, you have already connected to mysql
$languageid = array(1, 2);
$contactid = 124;
foreach($languageid as $id) {
$statement = "INSERT INTO contactlanguage (contactid, languageid) VALUES ('$contactid', '$id')"
mysql_query($statement);
}
Upvotes: 2