简体   繁体   中英

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM