简体   繁体   中英

PHP, MySQL, PDO - Insert Into Not Working

I have this code:

<?php
require_once 'dbconfig.php';

if(isset($_GET['id'])) {
    try {
    $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $getSavedHolidays = $db->prepare("INSERT INTO tvinfo(id, imdbid, name, rating, genre1, genre2, year, plot, uploader, views, downloads, uploaddate, size, resolution, fps, audio) VALUES (:id, :id, :id, :id, :id, :id, :id, :id, :id, :id, :id, :id, :id, :id, :id, :id)");
    $getSavedHolidays->setFetchMode(PDO::FETCH_ASSOC);
    $getSavedHolidays->execute(array(':id' => $_GET['id']));
    $Result = $getSavedHolidays->fetchAll();

    if(!$Result){
        die('Error: ID Not Found');
    }

}
catch (PDOException $e) {
    print_r($e->errorInfo);
    die();
}

foreach ($Result as $r) {
    echo 'Name: '.$r['name'].'<br>';
    echo 'Rating: '.$r['rating'].'<br>';
    echo 'IMDB ID: '.$r['imdbid'].'<br>';
    echo 'Genre 1: '.$r['genre1'].'<br>';
    echo 'Genre 2: '.$r['genre2'].'<br>';
    echo 'Year: '.$r['year'].'<br>';
    echo 'Plot: '.$r['plot'].'<br>';
    echo 'Uploader: '.$r['uploader'].'<br>';
    echo 'Views: '.$r['views'].'<br>';
    echo 'Downloads: '.$r['downloads'].'<br>';
    echo 'Uploaded at: '.$r['uploaddate'].'<br>';
    echo 'Size: '.$r['size'].'<br>';
    echo 'Resoution: '.$r['rsolution'].'<br>';
    echo 'FPS: '.$r['fps'].'<br>';
    echo 'Audio: '.$r['audio'].'<br>';
}

}

?>

When i go to example.com/file.php?id=Lel it outputs: Array ( [0] => HY093 ) and no error_logs. the tables etc are definitely there.

This code works fine when I use it with a select query to grab some info and output it but when I try inserting it wont work. Any ideas?

You can set ATTR_EMULATE_PREPARES to true:

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

then you will be allowed to bind a single time or you will have to do it for each time you have it in the query

Also get rid of $Result = $getSavedHolidays->fetchAll(); since you are inserting there is nothing to fetch

To check if the value exist before inserting, you can do:

$sql = 'SELECT COUNT(*) from tvinfo WHERE imdbid = :id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':id' => $_GET['id']));

if($stmt->fetchColumn()){ die('Already exist');}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM