PDO无效的数据源问题

时间:2015-01-02 17:52:12

标签: php pdo

我正在做一个项目并在一个类中使用PDO,所有函数都像魅力一样,但我有一个返回无效数据源错误,这是文本副本:

  

致命错误:未捕获的异常'PDOException',消息'无效   数据源名称'in   /home/decoded/public_html/studiobug/xxxx/class.php:194

     

堆栈追踪:

#0 /home/decoded/public_html/studiobug/xxxx/class.php(194):
PDO->__construct('DB_DSN', 'DB_USERNAME', 'DB_PASSWORD') 
#1 /home/decoded/public_html/studiobug/xxxx/deleteQuiz.php(5):
Admin->goodByeQuiz('2') 
#2 {main} thrown in
/home/decoded/public_html/studiobug/xxxx/class.php on line 194

这里有2个公共函数,第一个工作正常,第二个是返回错误的那个。 我无法找到正在发生的事情,因为代码几乎相同,只有查询发生变化。

public function saveEditQuestions($quizno,$todo) {
 $table = "quiz".$quizno."Questions";
 $sql = "";
  $sql .= "TRUNCATE $table;"; 
 foreach ($todo as $c => $v){        
  $sql .= "INSERT INTO $table SET ";
  $sql .= "option1 = '".$v['Answer1']."', ";
  $sql .= "option2 = '".$v['Answer2']."'; ";
 }

   $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
   $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

try {
$stmt = $con->prepare($sql);
$success = $stmt->execute();
return $success;
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}   
}
public function goodByeQuiz($del) {    
  $table1 = "quiz".$del."Questions";
  $table2 = "quiz".$del."Results";
  $sql = "UPDATE formStatus set active = 0 WHERE formNumber = $del;";
  $sql .= "TRUNCATE $table1;";  
  $sql .= "TRUNCATE $table2;";

   $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
   $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $con->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

try {
$stmt = $con->prepare($sql);
$success = $stmt->execute();
return $success;
}
catch (PDOException $e)
{
echo $e->getMessage();
die();
}   
}

1 个答案:

答案 0 :(得分:1)

问题似乎与您的关系有关。像这样使用....

connect.php

<?php 
$db_host = "localhost";
$db_name = "blogdata";
$db_user = "username";
$db_pass = "password";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

在你的职能中,

require 'connect.php';

并在任何地方使用此连接