开发者

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.


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.


There are few things wrong here.

First one is that you are not executing this query.

Secondly, query will fail if any of the subqueries returns more than one row.

Lastly, executing queries in a loop is not a good idea, especially when one of subqueries will return same result every time. You can easily achieve what you want with 3 queries (the size of $B_list wont't matter).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜