PDO检索表数据

时间:2014-11-27 22:08:49

标签: php pdo

我是PDO的新手,过去曾使用过mySQL。我创建了一个单独的文件来连接数据库。

<?php
 $dbHost='localhost';
 $databaseName='dm_projectdb';
 $username='blah';
 $password='blah';

 $db= new PDO("mysql:host=$dbHost; dbName=$databaseName;
    charset=utf8", "$username","$password");
 $db->setAttribute(PDO::ATTR_ERRMODE,
                PDO::ERRMODE_EXCEPTION);
 $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  
            ?>

在我试图检索并打印表格的另一个文件中。

<?php   
require_once('connect.php');
$sql= "SELECT CourseID, Course_Name  FROM coursename WHERE CourseID = 1";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':CourseID', $CourseID, PDO::PARAM_INT);
$stmt->execute();

?>  

该表名为coursename,带有Course_Name和CourseID行。 当我运行这个时,我得到Notice: Undefined variable: pdo in N:\ftp\project\comparison.php on line 44

Fatal error: Call to a member function prepare() on a non-object in N:\ftp\project\comparison.php on line 44

我做错了什么?我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:0)

您应该使用您设置的内容,即$db,而不是$pdo

$db= new PDO

Abd也是,你没有在查询语句中添加你的命名占位符:

CourseID = :CourseID

最后:

require 'connect.php';
$sql = "SELECT CourseID, Course_Name  FROM coursename WHERE CourseID = :CourseID";
$stmt = $db->prepare($sql);
$stmt->bindParam(':CourseID', $CourseID, PDO::PARAM_INT);
$stmt->execute();

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($results);

connect.php

$dbHost ='localhost';
$databaseName ='dm_projectdb';
$username ='blah';
$password ='blah';

$db= new PDO("mysql:host=$dbHost;dbname=$databaseName;charset=utf8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);