I'm having this error when I try to insert data in my database. I've searched the reasons of this error and I think my codes are right and I'm not supposed to get the error. My codes are these:
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...
As you can see, I declared the variable $pdo inside the registerUser functions, besides the variables that contain the name, username, password and email are parameters of the same function.
I know this is a several times duplicated question but I cannot solve this error with the solutions in the other ones.