PDO数据源无效问题


PDO invalid data source issue

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

致命错误:未捕获的异常"PDOException",消息"无效"数据源名称"中的/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();
}   
}

问题似乎出在您的连接上。像这样使用它....

连接.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';

并在您想要的任何地方使用此连接