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.

<?php

header("Access-Control-Allow-Origin: *");

$username = "root"; 
$password = "root";   
$host = "localhost";
$database="test";

$connection = mysqli_connect($host, $username, $password, $database);

$myNodesQuery = "
SELECT * FROM nodes";

$query = mysqli_query($connection, $myNodesQuery);

if ( ! $query ) {
    echo mysqli_error();
    die;
}

$data = array();

for ($x = 0; $x < mysqli_num_rows($query); $x++) {
    $data[] = mysqli_fetch_assoc($query);
}

//echo json_encode($data, JSON_FORCE_OBJECT);     
echo json_encode($data);

mysqli_close($connection);

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:

<?php
$username = "root"; 
$password = "root";   
$host = "localhost";
$database="test";
$connection = mysqli_connect($host, $username, $password, $database);

The main file

<?php
header("Access-Control-Allow-Origin: *");
require 'connection.php';

$myNodesQuery = "
SELECT * FROM nodes";
// whatever follows
... 

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