我尝试在数据库中插入数据时遇到此错误。我已经搜索了这个错误的原因,我认为我的代码是正确的,我不应该得到错误。我的代码是这些:
的config.php
<?php
class DatabaseConnection{
public function __construct(){
try{
$pdo = new PDO('mysql:host=localhost;dbname=test','root',''); //'mysql:host=host;dbname=dbname','mysqluser','mysqlpassword'
}
catch (PDOException $e){
exit('Database error');
}
}
}
?>
的functions.php
<?php
require "config.php";
class LoginRegister{
function __construct(){
$database= new DatabaseConnection();
}
public function registerUser($username,$password,$name,$email){
global $pdo; //THIS IS THE LINE WITH ERROR
$query=$pdo->prepare("SELECT id FROM usuarios WHERE nombre_usuario=? AND correo_e=?");
$query->execute(array($username,$email));
$num=$query->rowCount();
if($num==0){
$query = $pdo->prepare("INSERT INTO usuarios(nombre_usuario,nombre_real,password,correo_e) VALUES (?,?,?,?)");
$query->execute(array($username,$password,$name,$email));
return true;
}else{
return print "Username or E_mail in use";
}
}
}
?>
register.php
<?php
require_once "functions.php";
$user = new LoginRegister();
?>
...HTML CODE...
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$username=$_POST['nombre_usuario'];
$password=$_POST['password'];
$name=$_POST['nombre_real'];
$email=$_POST['correo_e'];
if(empty($username) or empty($password) or empty($name) or empty($email)){
echo "Error... Field must not be empty";
}else{
$register = $user->registerUser($username,$password,$name,$email);
if($register){
echo "Register done <a href='login.php'>Click here</a> for login";
}else{
echo "Username or E_mail in use";
}
}
}
?>
...HTML CODE...
如您所见,我在registerUser函数中声明了变量$ pdo,除了包含名称,用户名,密码和电子邮件的变量是同一函数的参数。
我知道这是一个多次重复的问题,但我无法用其他解决方案解决这个错误。
答案 0 :(得分:1)
您的代码存在一些问题。
在另一个答案中解释了两个,这将使你的代码工作(最终它全部被破坏),但它仍然是错误的方法,它将连接到数据库你有多少个对象。
以这种方式更改DatabaseConnection类
class DatabaseConnection{
public $pdo;
public function __construct(){
$user = 'root';
$pass = '';
$dsn = 'mysql:charset=utf8;dbname=test;host=localhost;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
$this->pdo = new PDO($dsn, 'root', '', $opt);
}
}
以这种方式更改LoginRegister构造函数
function __construct($db){
$this->db= $db;
}
以这种方式制作register.php
require_once "functions.php";
$db = new DatabaseConnection();
$user = new LoginRegister($db->pdo);
然后在LoginRegister中一直使用$this->db
而不是$pdo
。
使$ db连接成为应用程序类的外部服务的主要思路。否则它将与被鄙视的全球相同,但只是另一种形式。
答案 1 :(得分:0)
对不起,我必须说出糟糕的代码。你正在犯下所有最严重的错误。首先永远不要使用全球,永远不要这样做。谷歌它的解释原因。 现在,您在构造函数中创建的变量只有那里的范围,因此它们在您的其他类或方法中永远不可用。这就是为什么$ pdo不是PDO对象,它只是一个具有null值的局部var。试试这个:
class DatabaseConnection{
private $pdo;
public function __construct(){
try{
$this->pdo = new PDO('mysql:host=localhost;dbname=test','root',''); //'mysql:host=host;dbname=dbname','mysqluser','mysqlpassword'
}
catch (PDOException $e){
exit('Database error');
}
}
public function getPdo()
{
return $this->pdo;
}
class LoginRegister{
private $database;
function __construct(){
$this->database= new DatabaseConnection();
}
public function registerUser($username,$password,$name,$email){
$pdo = $this->database->getPdo();
$query=$pdo->prepare("SELECT id FROM usuarios WHERE nombre_usuario=? AND correo_e=?");
现在这仍然很可怕,但至少它会起作用。你真的必须从一本好书中读到面向对象的编程,这本书还教你如何设计模式和SOLID,DRY和其他最佳实践。
答案 2 :(得分:0)
在这里,我已将php单例PDO连接与mysql一起使用。希望这会有所帮助
<?php
class DB {
protected static $instance;
protected function __construct() {
if(empty(self::$instance)) {
try {
self::$instance = new PDO("mysql:host=localhost;dbname=techprojects", 'root', '');
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
} catch(PDOException $error) {
echo $error->getMessage();
}
}
}
public static function getInstance() {
if(empty(self::$instance)) {
try {
new DB();
//var_dump(self::$instance);
} catch(PDOException $error) {
echo $error->getMessage();
}
}
//var_dump(self::$instance);
return self::$instance;
}
private function __clone() {
// Stopping Clonning of Object
}
private function __wakeup() {
// Stopping unserialize of object
}
}
?>
<?php
try {
$db = DB::getInstance();
$db1 = DB::getInstance();
$sqlExample = 'SELECT * FROM keywords';
$stm = $db->prepare($sqlExample);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
var_dump($db);
var_dump($db1);
echo "<pre>";
print_r($result);
echo "</pre>";
} catch (Exception $e) {
print $e->getMessage();
}
?>
答案 3 :(得分:-1)
您没有在数据库类上设置$pdo
到global
(这没关系)。您可以改为创建内部数据库连接。看看是否有效:
<强>的config.php 强>
<?php
class DatabaseConnection
{
// Create a singleton to store the connection for reuse
private static $singleton;
// save connection to singleton and return itself
public function __construct()
{
// If your singleton is not set
if(!isset(self::$singleton))
// assign it this class
self::$singleton = $this;
// return this class
return self::$singleton;
}
// This is a connection method because your __construct
// is not able to return the $pdo connection
public function connection()
{
try {
// as @Your Common Sense notes, there are some good
// PDO settings you can apply at connection time
$opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_EMULATE_PREPARES => false);
// Return your PDO Conneciton here.
return new PDO('mysql:host=localhost;dbname=test','root','',$opts);
}
catch (PDOException $e){
exit('Database error');
}
}
}
<强>的functions.php 强>
<?php
require("config.php");
class LoginRegister
{
// This variable will store the db connection in this class
private $con;
// Construct will instantiate the DB
function __construct()
{
// Instantiate connection class
$pdo = new DatabaseConnection();
// Assign internally the connection to $this->con
$this->con = $pdo->connection();
}
public function registerUser($username,$password,$name,$email)
{
// Once assigned to $this->con, you can use the connection
// throughout this class
$query = $this->con->prepare("SELECT id FROM usuarios WHERE nombre_usuario=? AND correo_e=?");
$query->execute(array($username,$email));
// This should not use rowCount(),
// instead use a COUNT(*). The manual states this is not
// reliable on SELECT statements
$num = $query->rowCount();
if($num==0){
$query = $this->con->prepare("INSERT INTO usuarios(nombre_usuario,nombre_real,password,correo_e) VALUES (?,?,?,?)");
$query->execute(array($username,$password,$name,$email));
return true;
}else{
return print "Username or E_mail in use";
}
}
}
?>