Error using PDO prepare() function

Asked

Viewed 346 times

1

I’m on a new project, and I need to use the prepare() of the PDO, I do not know why, but only with him who is giving this error, every time it has some function, or some line with prepare(), PHP returns an error.

I’ve looked all over the O.R., I found answers, but I tried them all and no question was the same as mine/or was similar, but the answer didn’t solve.

Page code conexao.php:

$pdo = new PDO("mysql:host=localhost;dbname=central", "root", "");

Page code index.php:

require_once('conexao.php');
$sql = $pdo->prepare("INSERT INTO logs VALUES (:id, :type, :info)");
$sql->execute(array(":id" => NULL, ":type" => $type, ":info" => $info));

Informed error:

Notice: Undefined variable: pdo in C:\xampp\htdocs\index.php on line 2

Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\index.php on line 2
  • Gustavo has to give us more information, is this the only mistake that gives? Check if in conexao.php is set to $pdo with var_dump($pdo); after creating the PDO.

  • I had a similar problem this week, the system worked normally on a server, after uninstalling the xampp and reinstalling on another machine the system presented the error. I passed to make the connection in the same index file and fixed. I did not look for where the error was because I did not have time yet.

  • $pdo does not appear to exist in the.php connection file or is missing include/require in index.php

1 answer

4


It would be nice if you posted all the code for further clarification. Anyway, try to improve the code for the connection.

<?php
if(!defined("HOST")){ define('HOST','localhost'); }
if(!defined("DATABASE")){ define('DATABASE','central');}
if(!defined("USER")){ define('USER','root'); }
if(!defined("PASS")){ define('PASS',''); }

$conexao = 'mysql:host='.HOST.';dbname='.DATABASE;

try{
    $pdo = new PDO($conexao, USER, PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOexception $e){
    echo "Erro ao conectar" . $e->getMessage();
}
?>

I hope it helped. A hug

Browser other questions tagged

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