Neeraj Neeraj - 23 days ago 5
SQL Question

php mysql nested query

I have two tables

table TA(id, name_A) and
Table TB(id, name_B).


they are many to many relation. so I create a third table

TA_TB(id, A_id, B_id)


with appropriate foreign keys. Now I execute these queries to insert the data into mysql which fails.

$cat = $_POST["cat"];
$B_list=$_POST["B_list"];
if ($B_list){
foreach ($B_list as $i)
{
$query = "insert into TA_TB(A_id, B_id) values((select id from Table_A where name_A like '$cat'), (select id from Table_B where name_B like '$i'))";
if (!$query) {
die('Could not add Item:' . mysql_error());
break;
}
}

}


what is going wrong here? I know the values are coming in fine, because I can get them echoed or printed on the page alright. Insert does not insert. something is going wrong.

Answer

You need to use the mysql_query() function:

$query = mysql_query("insert into TA_TB(A_id, B_id) values((select id from Table_A where name_A like '$cat'), (select id from Table_B where name_B like '$i')))";

Otherwise you just have a string.