2

I have been following this tutorial on CRUD in php but I have come across an error that I have failed to intercept

Fatal error. Call to member function prepare() on null in C:\xampp\htdocs\CRUD\read.php on line 29** and this error ion line 29 of my code is **$stmt = $conn->prepare($query);

read.php file is this

<!DOCTYPE html>  
<html>  
<head>
    <title>PDO - Read Records - -PHP CRUD Tutorial</title>

    <!--Bootstrap-->
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">

    <script src="bootstrap/js/bootstrap.min.js"></script>
     </head> <body>
    <div class="container">
        <div class="page-header">
            <h1>Read Products</h1>
        </div>
        <!--Dynamic content will go here-->

        <?php

        // include database connection
        include_once 'config/database.php';

        // select all data
        $query = "SELECT id, name, description, price FROM products ORDER BY id DESC";

        // prepare query for execution
        $stmt = $conn->prepare($query);

        // execute the query
        $stmt->execute();

        // this how to get number of rows returned
        $num = $stmt->rowCount();

        // link to create record form
        echo "<a href='create.php' class='btn btn-primary m-b-1em'>Create New Product</a>";

        // check if more than 0 records found
        if($num > 0) {
            echo "<table class='table table-hover table-responsive table-bordered'>"; // start table

            // creating our table heading
            echo "<tr>";
            echo "<th>ID</th>";
            echo "<th>Name</th>";
            echo "<th>Description</th>";
            echo "<th>Price</th>";
            echo "<th>Action</th>";
            echo "</tr>";

            // retrieve our table contents
            //fetch() is faster than fetchAll()

            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                // extract row
                // this will make $row['firstname'] to 
                // just $firstname only
                extract($row);

                // creating new tablerow per record
                echo "<tr>";
                    echo "<td>{$id}</td>";
                    echo "<td>{$name}</td>";
                    echo "<td>{$description}</td>";
                    echo "<td>&#36;{$price}</td>";
                    echo "<td>";

                // read one record
                echo "<a href='read_one.php?id={$id}'class=''btn btn-info m-r-1em'>Read</a>";

                // we will use this link  to the next part of the post
                echo "<a href='update.php?id={$id}' class='btn btn-primary m-r-1em'>Edit</a>";

                // we will use this link  to the next part of the post
                echo "<a href='#' onClick='delete_user({$id});' class='btn btn-danger'>Delete</a>";

                echo "</td>";
            echo "</tr>";
            }
            //end table
        echo "</table>"; 

        }

        // if no records found
        else{
            echo "<div class='alert alert-danger'>No records found.</div>";
        }
        ?>

    </div><!--end of container-->

    <!--Jquery (necessary for bootstrap's javascript plugin)-->
    <script src="jquery-ui-bootstrap-jquery-ui-bootstrap-71f2e47/js/jquery-1.8.3.min.js">
 </script> 
 </body>  
</html>

database.php file:

<?php
    //variables used to connect to the database
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "1phpbeginnercrudlevel1";

    //create a connection using the PDO extension
    try{
        $conn = new PDO("mysql:host=$servername;dbname=1phpbeginnercrudlevel1",$username,$password);

        //set the PDO error mode to exception
        echo "Connected successfully";
    }
    catch(PDOException $e)
    {
        echo "Connection failed: " .$e->getMessage();
    }


    ?>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    http://php.net/manual/en/pdo.error-handling.php --- http://php.net/manual/en/function.error-reporting.php – Funk Forty Niner Feb 16 '17 at 15:43
  • 2
    Dear Fred! By the way, maybe your connection fails. Check out Fred link and declare a $conn before the try/catch with a value, just to let it exists. – Theraloss Feb 16 '17 at 15:45
  • i have really tried about it but still gives me the same error....what could be wrong with this line of code $stmt = $conn->prepare($query); – Ssendikadiwa Stephen Feb 16 '17 at 16:21
  • The problem is likely with include. ALWAYS have the proper **ERROR REPORTING** configured and never guess what could be possibly a probable issue is. – Your Common Sense Nov 12 '20 at 05:56

2 Answers2

-1

Seems like your connection failed or including database.php was failed

Alex Slipknot
  • 2,439
  • 1
  • 18
  • 26
  • hey thanks, i have figured it out, the it was not accessing the database file and so i have decided to include it directly into my read.php file instead of using the include command...but is there any problem with that? how can i fix that problem so that i can use the include command – Ssendikadiwa Stephen Feb 16 '17 at 16:48
  • You should check connection. So if ($conn) then continue operation. Else show some error message – Alex Slipknot Feb 17 '17 at 07:31
-1

An missing found in your database.php file:

you should must add "return $conn;" on try block

correction is given in below :-

 <?php
        //variables used to connect to the database
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "1phpbeginnercrudlevel1";
    
        //create a connection using the PDO extension
        try{
            $conn = new PDO("mysql:host=$servername;dbname=1phpbeginnercrudlevel1",$username,$password);
    
            //set the PDO error mode to exception

           return $conn;
            echo "Connected successfully";
        }
        catch(PDOException $e)
        {
            echo "Connection failed: " .$e->getMessage();
        }
    
    
        ?>