I’m getting this error while trying to connect mysql: Fatal error: Uncaught Error: Call to a Member Function prepare() on null

Asked

Viewed 100 times

-1

php connection.

try{
    $conn = new PDO("mysql:host=$servidor;dbname=$banco;charset=utf8", $usuario, $senha);
    return $conn;
}catch(PDOException $e){
    throw new PDOException($e);
}

base php.

        require 'conexao.php';
        session_start();

        if(isset($_SESSION['login']) and !empty($_SESSION['login'])){
          $sql = $conn->prepare("select * from usuarios where id=:user;");
          $sql->execute(':user', $_SESSION['login']);
          $user = $sql->fetch(PDO::FETCH_OBJ);

login.php

<?php
include 'conexao.php';
//inicia a sessão
session_start();

//recebe o nome do usuário
$nome = $_POST['nome'];
//recebe a senha do usuário
$senha = $_POST['senha'];

//verifica se existe um usuário com esse nome e senha
$stmt = $conn->prepare('select * from usuarios where nome=:nome and senha=:pass;');
$stmt->bindParam(':nome',$nome);
$stmt->bindParam(':pass',$senha);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);

//se o resultado retornou o id do usuário
if($user->id > 0){
    //cria-se a sessão 'login' que recebe esse id
    $_SESSION['login'] = $user->id;
    //carrega página index
    header('location: ./index.php');
}

Also giving error here on line 18 where $sql gets $Conn

index php.

<?php require 'conexao.php'; ?>
<?php require 'base.php'; ?>
<?php

//se o usuário escreveu algo no campo de busca
if(isset($_POST['pesquisa']) and !empty($_POST['pesquisa'])){
    //recebe o texto do post de busca
    $pesquisa = $_POST['pesquisa'];

    //verifica se existem formulário com o valor de $pesquisa no nome
    $sql = $conn->prepare("select * from formulario where nome like '%$pesquisa%';");
    $sql->execute();
    $rows = $sql->fetchAll(PDO::FETCH_OBJ);

//senão
}else{
    //busca todos os formulários organizando-os de acordo com a data da ultima alteração em ordem decrescente
    $sql = $conn->prepare("select * from formulario order by data_modificacao desc;");
    $sql->execute();
    $rows = $sql->fetchAll(PDO::FETCH_OBJ);
}

  • The error clearly says it is calling the method prepare in a null object, $conn. See why $conn is null; either because the connection spoke or because it did not assign value to the variable. Also check your server’s error log file to see possible error messages that occurred in the process.

  • now showing this error: Notice: Undefined variable: Conn in C: Users User Documents Jobs Formgenerator asdfg index.php on line 18. It seems that require.php is not working..

  • Well, it shows that your variable really isn’t set...

  • but like, if it is in Try{ $Conn = new PDO("mysql:host=$server;dbname=$bank;charset=utf8",$user, $password);

  • But apparently they are not in the same file, are they? Make a [mcve] that reproduces the problem to better analyze.

  • Where can I send this example? Do it as another question or send it by right here? Sorry to bother you but it’s my first php project..

  • Can [Dit] the question

  • Putting $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) after it assigns the $conn (in the archive conexao.php), something different happens?

  • no, the error remains the same

Show 4 more comments

1 answer

0

Try it that way

$sql = $conn->prepare("select * from usuarios where id = :user");
$sql->execute([':user' => $_SESSION['login']); 
$user = $sql->fetcObject();

On the port you cannot use, it must be being used by another program, so you cannot open the PHP server on it,

Prefer also to use an object instead of using bindParam, make an object with everything you need, for example

$obj = [
   ':login' => $login,
   ':senha' => $senha,
   ':email' => $email
];

And then pass inside the execute

$sql->execute($obj);
  • Why changing the SQL will affect the value of the object $conn, which is null according to the error message?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.