简体   繁体   中英

How to use the result of one query in another query (PHP/MySQL)

I have 2 tables (artist, cd) and I'm trying to use the result of the first query which returns an artID and make it equal to the artID in the 2nd table(cd) where artID is a foreign key but I'm not sure how to do it. Any help would be appreciated.

$strqueryID="SELECT artID FROM artist WHERE artName= '" . $_POST["category"] . "' ";
$resultsID=mysql_query ($strqueryID) or die(mysql_error());

$strqueryCD="INSERT INTO cd SET cdTitle='" . $_POST['title'] . "', artID='" . ??? . "' cdPrice='" . $_POST['price'] . "', cdGenre='" . $_POST['genre'] . "', cdNumTracks='" . $_POST['tracks'] . "'";
$resultsCD=mysql_query ($strqueryCD) or die(mysql_error());

You can use one single query, like this:

$strqueryCD="
INSERT INTO cd (cdTitle, artID, cdPrice, cdGenre, cdNumTracks) 
VALUES(
   '" . $_POST['title'] . "', 
   (SELECT artID FROM artist WHERE artName= '" . $_POST["category"] . "'), 
   '" . $_POST['price'] . "', 
   '" . $_POST['genre'] . "', 
   '" . $_POST['tracks'] . "')
";

also, google 'sqlinjection' before you continue

So, first thing's first - you shouldn't be using mysql_* functions now in 2017. I mean, really - they're actually even removed in later versions of PHP (7.0+). Refer to this StackOverflow post for more information.

Now, for your question at hand. Given the fact that you've searched for (and found) a given artID , you'll first have to get the actual "rows" from the $resultsID variable. In this example, we'll do it in a typical while loop:

while ($row = mysql_fetch_assoc($resultsID)) {
    $strqueryCD="INSERT INTO cd SET cdTitle='" . $_POST['title'] . "', artID='" . $row['artID'] . "' cdPrice='" . $_POST['price'] . "', cdGenre='" . $_POST['genre'] . "', cdNumTracks='" . $_POST['tracks'] . "'";
    $resultsCD=mysql_query ($strqueryCD) or die(mysql_error());
}

That should now loop over the artID s that you've found in your first query and use them in the subsequent insert(s).

--

Disclaimer: I've disregarded the fact that user input is being passed straight into the query itself, as it's just too much "out of scope" for this post.

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