PHP,MySQL,PDO - 插入不工作

时间:2015-07-01 16:19:40

标签: php mysql pdo

我有这段代码:

<?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>';
}

}

?>

当我转到example.com/file.php?id=Lel它输出:Array([0] =&gt; HY093)并且没有error_logs。桌子等肯定在那里。

当我使用选择查询来获取一些信息并输出它时,此代码工作正常,但是当我尝试插入它不会工作。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以将ATTR_EMULATE_PREPARES设置为true:

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

然后您将被允许绑定一次,或者您必须在查询中每次执行此操作

同样摆脱$Result = $getSavedHolidays->fetchAll();,因为你插入没有什么可以提取

要在插入之前检查值是否存在,您可以执行以下操作:

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

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