Question

PHP MySQL connection script in different file

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.

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

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

if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //lines above get moved to db_connect.php
$sql = “SELECT name FROM my_table WHERE age = 22”; $result = $conn->query($sql);

if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "the name is: " . $row[“name”]. “<br>”; } } else { echo “0 results”; } $conn->close(); ?>

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:

require_once ‘\var\www\my_website\private_database\db_connect.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.

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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.

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