I’m having some problems with the code below. What I’m trying to do is to tell if a tag already exists in the table tags, if it does, get the id and put that id in the table blog_post_tags, or if it does not exist, create it, get the id and put it in blog_post_tags table. The problem is that, whenever I try to check if the id already exists, I get errors all over the place telling me trying to get property of non object but fields are still being insert in the other table with an id of 0 (which is not a valid id for the tags).
Here is the code:
foreach ($tags as $tag)
{
//search for the tag to see if it exists
//the problem is located in this line of code
if($select_stmt = $mysqli->prepare("SELECT id FROM tags WHERE name = ?"))
{
$select_stmt->bind_param("s",$tag);
$select_stmt->execute();
$result = $select_stmt->get_result();
//if the tag exists
if($select_stmt->num_rows != 0)
{
if($insert_stmt = $mysqli->prepare("INSERT INTO blog_post_tags (blog_post_id, tag_id) VALUES (?,?)"))
{
$insert_stmt->bind_param('ii', $blogid, $result);
$insert_stmt->execute();
}
}
else
{
if ($insert_stmt2 = $mysqli->prepare("INSERT INTO tags (name) VALUES (?)"))
{
$insert_stmt2->bind_param('s', $tag);
$insert_stmt2->execute();
$tagid = $mysqli->insert_id;
if ($insert_stmt3 = $mysqli->prepare("INSERT INTO blog_post_tags (blog_post_id, tag_id) VALUES (?, ?)"))
{
$insert_stmt3->bind_param('ii', $blogid, $tagid);
$insert_stmt3->execute();
}
}
}
}
}
Thanks in advance for the help.
EDIT
Some how, the “trying to get property of a non object” disappeared, i suspect it may have been a connection erro with the server but i really cant tell, still the table blog_post_tags is being filled with fields that does not make any sense, “tag_id =0”. i suspect it may have something to do with the problem expressed here: php prepared stmt problem- update data at each result loop
¿ how could i correct me code if the problem is related to that of the link above ?
Well, i really dont know what it did, but it seem to have worked, here is the code without any errors:
hopefully this can help anyone that encounters a similar problem, also, i would like to know if this solution is optimal or if there is any way to improve it.