2014-07-14 46 views
0

這裏是我下面的代碼:爲什麼我的PDO :: FETCH語句返回0?

$barcode = $_POST['barcode']; 
$year = $_POST['year']; 
$movietitle = $_POST['movietitle']; 
$stmt = $pdo->prepare("SELECT COUNT(movietitle) FROM movies WHERE movietitle LIKE '%:movie%'"); 
$stmt->bindParam(':movie', $movietitle); 
$stmt->execute(); 
$fetch = $stmt->fetch(); 
if($fetch[0] == 0) {  
    $displaytitle = $_POST['displaytitle']; 
    $media = $_POST['media']; 
    $youtube = $_POST['youtube']; 
    $genre = $_POST['genre']; 
    $youtube = "www.youtube.com/embed/" . $youtube; 
    $stmtins = $pdo->prepare("INSERT INTO `movies` VALUES (null, :genre, :movietitle, :displaytitle, :year, :youtube, :media, :barcode)"); 
    $stmtins->bindParam(':genre', $genre); 
    $stmtins->bindParam(':movietitle', $movietitle); 
    $stmtins->bindParam(':displaytitle', $displaytitle); 
    $stmtins->bindParam(':year', $year); 
    $stmtins->bindParam(':youtube', $youtube); 
    $stmtins->bindParam(':media', $media); 
    $stmtins->bindParam(':barcode', $barcode); 
    $stmtins->execute(); 
    $message = "The movie was added to your database. - $fetch[0]"; 
} else { 
    $message = "Already owned."; 
} 

每次它的運行時間,$取[0]總是返回0,儘管$語句查詢返回大於0以上這是怎麼回事?

回答

1

我建議你在異常模式下運行PDO ...

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

,那麼你會看到查詢錯誤。

問題是,你不能像你在LIKE比較中那樣使用插值參數。試試這個...

"SELECT COUNT(movietitle) FROM movies WHERE movietitle LIKE CONCAT('%', :movie, '%')" 

還有一個更簡單的方法來檢查它是否存在...

$stmt = $pdo->prepare("SELECT 1 FROM movies WHERE movietitle LIKE CONCAT('%', :movie, '%')"); 
$stmt->bindParam(':movie', $movietitle); 
$stmt->execute(); 
if(!$stmt->fetch()) { 
    // fetch will return false if there are no rows 
+0

乾杯!我可以發誓我以前就這樣做過。無論哪種方式,謝謝! – user2416047