0

我收到了这个错误,这让我摸不着头脑:

致命错误:在 /Users/aaronwilson/Desktop/testing_server/ATOM_CMS/functions/sandbox.php:10 中未捕获异常“PDOException”和消息“无效数据源名称”堆栈跟踪:#0 /Users/aaronwilson/Desktop/testing_server/ATOM_CMS /functions/sandbox.php(10): PDO->__construct('SELECT title FR...') #1 /Users/aaronwilson/Desktop/testing_server/ATOM_CMS/config/setup.php(30): get_title(NULL, 'blog') #2 /Users/aaronwilson/Desktop/testing_server/ATOM_CMS/index.php(2): include('/Users/aaronwil...') #3 {main} 在 /Users/aaronwilson/Desktop/ 中抛出testing_server/ATOM_CMS/functions/sandbox.php 第 10 行

这是 sandbox.php 代码:

<?php ## Sandbox PHP/PDO Functions 
function get_page($dbc, $pg) {
$sql = new PDO("SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");
$stmt = $dbc->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content">'.$page['body'].'</div>';}
function get_title($dbc, $pg)  
$sql = new PDO("SELECT title FROM pages WHERE page = '$pg' AND status = 1   LIMIT 1");
$stmt = $dbc->prepare($sql);
$stmt->execute();
$row = $stmt->fetch();
return $page['title'];}
?>

在 Setup.php 上有一个 S_GET 函数来拉取 url 以调用 sandbox.php 上的函数:

if ($_GET ['page'] == '') {
$pg = 'home';} 
else {
$pg = $_GET ['page']; }
4

2 回答 2

0
new PDO("SELECT * FROM pages WHERE page = '$pg' AND status = 1 LIMIT 1");

这不是您创建 PDO 对象的方式,它的参数不同,它不接受查询。以下是构造函数原型。

公共 PDO::__construct() ( 字符串 $dsn [, 字符串 $username [, 字符串 $password [, 数组 $driver_options ]]] )

相应地向它发送参数。发送dsn, username, password.

来自 php.net 的示例

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

资源

于 2013-11-12T04:45:11.013 回答
-1

您没有正确使用 PDO Library ,这就是导致错误的原因。这是许多正确方法中的一个示例:(根据您的情况调整它,我相信它会对您有所帮助)

$variable1 = "somthing";
$variable2 = "somewhat";
try
  {
    require_once("db-info.php");
    $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
    $db = new PDO('mysql:host='.$host.';dbname=' . $dbname, $dbuser, $dbpassword,     $pdo_options);
    $response = $db->prepare('SELECT column1, column2 FROM table WHERE column1 = :value1 and column2 = :value2');

    $response->execute(array('value1' => $variable1,
                             'value2' => $variable2
                            ));
    $data = $response->fetch(); // works for one set of data 
    // if your are trying to fetch multiple line use a (while $data = $response->fetch())
    //and insert your code inside the while loop.

    //insert your code here....
    //.........................
    //.............
    //using a return true or false may help you with your function case
    $response->closeCursor();
}
catch (Exception $error)

   {

 die('error while selecting data' . $error->getMessage());

   }  
于 2013-11-12T06:33:16.880 回答