0

Im working on a display of names using PHP, PDO and SQL.\ I currently have 3 files, an index.php (homepage), an account.class.php (class file) and a config.inc.php (database connection).

Showing the data on screen worked, but I want it to work using object oriented php. Thats why I have a separate class file.

The following code is my index page:

<?php
include ("includes/config.inc.php");

?>

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

</head>
<body>
    <a href="admindash/login.php"><button type="button" class="btn btn-primary">LOGIN</button></a>

    <?php
        $accounts = new Account();
        $accounts->allAccountName();


    ?>
</body>

</html>

The following code I use to connect to the database:

<?php

//config
$con = new PDO("mysql: host=localhost; dbname=hotelstardust", "root", "h0nd3ns3ct13!");

//includes
include ('classes/account.class.php');
?>

And finally the code for my class:

<?php

class Account {
    public function allAccountName() {
        $query = "SELECT * FROM account ORDER BY voornaam";

            $stm = $con->prepare($query);
            $stm->execute();
            $result = $stm->fetchAll(PDO::FETCH_OBJ);
            echo "<table>"; 
            echo "<tr>";
            echo "<th>".'Voornaam'."</th>";
            echo "<th>".'Achternaam'."</th>";
            echo "</tr>";
            foreach ($result as $pers) {
                echo "<tr>";
                echo "<td>".$pers->voornaam."</td>
                <td>".$pers->achternaam."</td>";
                echo "</tr>";
            }
            echo "</table>";

    }
}


?>

As you can see, the index page has an include for the config page, and the config page has and include for the class.

The error I keep on getting is

Notice: Undefined variable: con in C:\xampp\htdocs\sites\hotelstardust\classes\account.class.php on line 7

Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\sites\hotelstardust\classes\account.class.php on line 7

I need the class to be able to see the config. How can I do this?

0 Answers0