Skip to content
Advertisement

separate db connection.php from db queries

I want to improve my non-existing PHP knowledge. To do so I created a MySQL DB and a connection.php file with an SQL query (please ignore SQL injection comments for now, I am aware of it). I trying to figure out, how I can split the connection from the actual query.

JavaScript

My thoughts were to create another PHP file and add $connection = mysqli_connect (require('connection.php')) to receive the connection string. Unfortunately, I receive a path error.

Advertisement

Answer

Keeping your code as is then:

File connection.php:

JavaScript

The main file

JavaScript

Please note that – unless you use a framework – it would be much better if you build your reusable connection class or connection-returning function. And BTW consider using the far superior PDO.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement