0
I am trying to create a registration system using classes, my code does not appear any error, however still information is not saved in the database.
I could not find the problem, in case someone can help me I thank
class Usuario {
private $pdo;
public function conectar($dataBase, $host, $user, $password) {
global $pdo;
try {
$pdo = new PDO("mysql:dbname=".$dataBase.";host=".$host, $user, $password);
} catch(PDOException $e) {
throw new PDOException($e);
}
}
public function cadastrar($nome, $sobreNome, $email, $telefone, $senha, $codigo, $level = 5) {
global $pdo;
$sql = $pdo->prepare("SELECT id FROM usuarios WHERE Email = ?");
$sql->execute(array($email));
if($sql->rowCount() > 0) {
return false; //email já cadastrado
} else {
//email não cadastrado, então cria uma função para cadastrar
$sql = $pdo->prepare("INSERT INTO usuarios (Nome, SobreNome, Email, Telefone, Senha, codigo, Level) VALUES (?, ?, ?, ?, ?, ?, ?)");
$sql->execute(array($nome, $sobreNome, $email, $telefone, $senha, $codigo, $level));
return true;
}
}
}
$conn = new Usuario();
$conn->conectar("codigo_util", "localhost", "root", "");
$cadastro = new Usuario();
$cadastro->cadastrar($_POST['nome'], $_POST['Sobrenome'], $_POST['email'], $_POST['telefone'], $_POST['senha'], $_POST['codigo']);
Edit
I redid all the code using the tips you gave, and the problem was solved, thank you very much for the help, I’ll leave the code below in case anyone needs.
class Usuarios {
private $pdo;
public function __construct($dataBase, $host, $user, $pass) {
try {
$this->pdo = new PDO("mysql:dbname=".$dataBase.";host=".$host, $user, $pass);
} catch(PDOException $e) {
echo "Erro: ".$e->getMessage();
}
}
public function cadastrar($nome, $sobreNome, $email, $telefone, $senha, $codigo, $level = 5) {
$sql = $this->pdo->prepare("SELECT id FROM usuarios WHERE email = ?");
$sql->execute(array($email));
if($sql->rowCount() < 1) {
$sql = $this->pdo->prepare("INSERT INTO usuarios (Nome, SobreNome, Email, Telefone, Senha, CodigoRegistro, Level) VALUES (?, ?, ?, ?, ?, ?, ?)");
$sql->execute(array($nome, $sobreNome, $email, $telefone, $senha, $codigo, $level));
} else {
echo "Email já existente";
}
}
}
$cadastro = new Usuarios("codigo_util", "localhost", "root", "");
$cadastro->cadastrar($_POST['nome'], $_POST['Sobrenome'], $_POST['email'], $_POST['telefone'], $_POST['senha'], $_POST['codigo']);