PHP MySQL connection script in different file

Posted November 19, 2020 286 views

I have set up a MySQL table that has two columns, name and age, and inserted the data “steve” and 22.
If I have the following program called home.php and run it in my browser, everything works fine.

$servername = “localhost”;
$username = “myusername”;
$password = “mypassword”;
$dbname = “mydbname”;

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connecterror) {
die(“Connection failed: ” . $conn->connect
//lines above get moved to dbconnect.php

$sql = “SELECT name FROM my
table WHERE age = 22”;
$result = $conn->query($sql);

if ($result->numrows > 0) {
while($row = $result->fetch
assoc()) {
echo “the name is: ” . $row[“name”]. “<br>”;
} else {
echo “0 results”;

However, if I move the database connection part to a file, db_connect.php inside a folder and place this code at the top of home.php:

requireonce ’\var\www\mywebsite\privatedatabase\dbconnect.php’;

The browser no longer outputs “the name is steve”

Can someone please help me to understand why it works when I put the database connection variables inside the program, but not when I try to use require_once. I’m using LEMP.
Thank you.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer

Why wont Digital Ocean allow the original poster of a question to edit it?