Search code examples
phphtmlmysqlsimple-html-dom

Simple html dom and mysql insert


Hello Guys i am using the code bellow to scrap some content. I need to insert this into mysql. Also i have to check the title if is the same and if it is to do not insert the post.

My code bellow inserts the first record even if it exists.

    foreach($html->find('div.article_item') as $div) {

        $title = $div->find('h2.title a ', 0)->innertext;              
        $thumb = $div->find('p.image_left img ', 0)->src;
        $details = $div->children(3)->plaintext;
        $url = $div->find('p.more a', 0)->href;

        //I need only 3 posts to grab
        for( $i= 0 ; $i <= 3 ; $i++ )
        {    

        $qry="SELECT * FROM posts WHERE posttitle ='$title'";
        $result=mysqli_query($connectiondb, $qry);

        //Check whether the query was successful or not
        if($result) {
        if(mysqli_num_rows($result) == 1) {
        //Post Exists
        }else {

        $posttitle = $title;
        $postthumb = $thumb;
        $postdetails = $details;
        $posturl = $url;

        mysqli_query ($connectiondb, "INSERT INTO posts (posttitle, postthumb, postdetails, posturl) VALUES ('$posttitle', '$postthumb','$postdetails','$posturl')");

    }


    }else {
    (mysqli_error());
    }
    mysqli_close($connectiondb);

    } 


// Clear dom object
$html->clear(); 
unset($html); 
}

Solution

  • Try to change == 1 to > 0 in this case:

    if(mysqli_num_rows($result) > 0) {
        // Post Exists
    } else {
    

    And since you're using mysqli, why not use prepared statements.

    Sidenote: I see that comment, I only need three posts,