Reputation: 195
I'm having issues with the current code, actually I'm not sure if I'm going about the right way either way.
My current script (the total) uploads a photo and returns the id from the MySQL database. When the photo is selected, it's also been given tags. To associate these tags, I have chosen to have a table 'tagrefs' which simple combine tag_id with photo_id for later querying. The table 'tags' consists of tag_id and tag_name. The table 'photos' has tons of fields, the only relevant one being photo_id.
Currently, I pass the tags via POST.
$tags = trim($_POST['tags']);
$tags = preg_replace('/\s+/', '', $tags);
$tags = htmlspecialchars($tags);
$tags = mysql_real_escape_string($tags);
$tags = strip_tags($tags);
$tags = explode(",", $tags);
$insert = $dbh->prepare('INSERT INTO tags (tag_name) VALUES (:tag)');
$insert->bindParam(':tag', $tag, PDO::PARAM_STR);
foreach ($tags as $tag) $insert->execute();
$select = $dbh->prepare('SELECT tag_id FROM tags WHERE tag_name = (:tag)');
$select->execute();
$result = $select->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");
Up until $select it works perfectly. Tags are inserted, photo is uploaded. Peachy. Now I need to write something that will give me the tag_id of the tag_name s I just added, then I need to combine that with the photo_id and insert that into 'tagrefs'. The bottom $select is my failing attempt to retrieve said tag_id's that I just created by comparing them to the string the user POSTs. The manner I was thinking of is retrieving them, then creating a new array with the photo_id and the tag_id s and inserting the values into 'tagrefs'.
It all sounds overly complicated and there is probably a much better/safer way to do it but an hour of Googling has not helped.
Upvotes: 1
Views: 93
Reputation: 360572
foreach ($tags as $tag) $insert->execute();
is incorrect. There's no {}
, so all the foreach is doing is that one execute call, over and over. The rest of the code afterwards is NOT executed as part of the foreach. As such, you insert all of the tags, then when the loop is completed, you try to fetch the id of the LAST tag you inserted. Assuming this tag_id is an auto_increment primary key field, you should be using something like this:
foreach($tags as $tag) {
$insert->execute();
$tag_id = $insert->lastInsertId();
....
}
and not doing a dedicated select anyways.
Upvotes: 1