Spratters53
Spratters53

Reputation: 415

Insert Into table using foreach

I'm trying to insert various different values into different tables. A user writes a main article with most of the details, and then certain values are lookups to prevent unnecessary duplication. What i'm trying to do is have a user select a developer already in the database (i've already got an option for if it's not there), but users can select more than one user.

What i want to do is, if a user selects more than one developer, insert them all into the connecting table in the following format

ArticleID DeveloperID

----1---- -------1-------

----1---- -------4-------

The article ID will always be 1, the developer id can effectively be any number. The code i'm using to attempt to do this is

if (isset($DEVid)){
     foreach($DEVid as $DeveloperArray){
     mysqli_query($dbc, "INSERT INTO temp_article_developer (ArticleID, DeveloperID)
                   VALUES ('$ArticleID', '$DEVid')");
     }
 }

DEVid is set by a multi-select input field

$DEVid = $_POST['SelectDevelopers'];

ArticleID is set by a query upon the main part of the article being inserted into the database (providing me with an ID to use, as the ID is not set by the user)

$qGetNewArticleID = "SELECT ArticleID FROM temp_article WHERE ArticleTitle='$TTL'";
$rGetNewArticleID = @mysqli_query($dbc, $qGetNewArticleID);
$GetArticleIDRow = mysqli_fetch_array($rGetNewArticleID, MYSQLI_ASSOC);
$ArticleID = $GetArticleIDRow['ArticleID'];

Currently the code i have used does not insert anything into the database. The Article ID field is definitely populated as i have tested it with another (simpler) insert which only allows one selected field. $_POST['SelectDevelopers'] is also definitely populated as it re-selects all selected values upon returning to the form in the case of an error. I just can't get it to insert the values.

Upvotes: 0

Views: 1286

Answers (1)

fortune
fortune

Reputation: 3382

In the procedural style the mysqli_query need connection string as the first argument

From Php.net

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

You are missing connection string in your insert query.

Update:

    foreach($DEVid as $DeveloperArray ){

    mysqli_query($dbc, "INSERT INTO temp_article_developer (ArticleID, DeveloperID)
                   VALUES ('$ArticleID', '$DeveloperArray')");
   }

Please check it.

Upvotes: 1

Related Questions