Fatal error: Uncaught Error: Call to a member function prepare () on null

0

Good morning, I'm making a page and I'm making the connection to the database but it sends me the following error

<?php 
    require 'init.php';

    class Funciones{

        public function getPublicaciones(){
            global $pdo;

            $query = $pdo->prepare("
                SELECT *
                FROM blog
            ");
            $query->execute();

            return $query->fetchALL();
        }
    }
?>

And I'm calling it like this:

<?php 
    require 'php/Funciones.php';
    $obj = new Funciones();

    $publicaciones = $obj->getPublicaciones();

    echo '<pre>', print_r($publicaciones), '</pre>';
    exit();
?>
    
asked by Crisvallejo26 18.12.2018 в 05:03
source

1 answer

0

You need a file to make the MySQL connection with your database:

<?php
$servername = "localhost";
$username = "tusuario";
$password = "tupassword";
$dbname = "tuBD";


$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("La conexion ha fallado: " . mysqli_connect_error());
}
?>

Then in the file where you make the query, you call the connection file

require_once('archivo_conexion.php'); 
$sql= "SELECT * FROM blog";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

You show it

while ($row = $stmt->fetchObject()) {
    echo "<li>{$row->campo}</li>";
}
    
answered by 18.12.2018 в 09:07