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.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Why wont Digital Ocean allow the original poster of a question to edit it?
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.