Dymond
Dymond

Reputation: 2277

if exist else insert PHP

I have some problem with my if else statement, but I cant figure out what, since it should work :)

What im trying to do is that IF the video_title already exist in my row then do nothing, but if the video_title does not exist, insert values to the table.

I have the value marvel.mp4 in my video_title column, But it still keeps on inserting marvel.mp4 as value on new rows...

Any ideas why its not working?

     $query  =  $dbh->query("SELECT video_title FROM video");
     $q         =   $query->fetch(PDO::FETCH_OBJ);

     $video_title = "marvel.mp4";

        if($video_title ==$q){

            // Do Nothing

        }else{
        $sql = "INSERT INTO video (video_title, video_cat, video_date) VALUES (:video_title,    :video_cat, NOW())";
            $query = $dbh->prepare($sql);
            $query->execute(array(
            ':video_title' => $video_title,
            ':video_cat' => $video_cat
            ));     
            }

Upvotes: 0

Views: 1201

Answers (2)

Barmar
Barmar

Reputation: 782693

It should be:

if ($video_title == $q->video_title)

When you use PDO::FETCH_OBJ, each column is a property of the object.

You also need to be more specific in the query, otherwise you're just testing whether the video is the first one returned by the query.

$video_title = "marvel.mp4";
$stmt - $dbh->prepare("SELECT video_title FROM video WHERE video_title = :title");
$stmt->execute(array(':title' => $video_title));
$q = $stmt->fetch(PDO::FETCH_OBJ);

Upvotes: 2

Sectona
Sectona

Reputation: 98

This code will solve your problem. I have just tested and run it and is working. Please rate me if you find this help awesome ....Sectona

<?php

$db = new PDO (

    'mysql:host=localhost;dbname=sectona_db;charset=utf8', 

    'root', // username
    'tt56u' // password

);

?>


<?php

require("pdo.php");


$video_t=strip_tags($_POST["video_t"]);


//check if the video title already exist in the database


$result = $db->prepare('SELECT * FROM video where video_title = :video_title');

        $result->execute(array(
            ':video_title' => $video_t
    ));



$nosofrows = $result->rowCount();
if ($nosofrows == 1)
//if ($nosofrows ==0)
{
echo '<br><b><font color=red><b></b>Video Title Already exist. Do not insert</font></b><br>';
exit();
}else{

// insert data

$statement = $db->prepare('INSERT INTO video(video_title,video_name)
                          values
                                                   (video_title,video_name)')
$statement->execute(array( 

':video_title' => $video_t,
':video_name' => 'Commando'


));

}

?>

Upvotes: 0

Related Questions