Error when making connection with MySQL?

Hi,
I’m a newbie in PHP. I have created my connection in a seperate php file. The code for connection.php is:

<?php
//error_reporting(0);
$con = mysqli_connect('localhost','root', '', 'resume') or die('connection lost');
?>

<?php
function GetGeneralInfo($connection){
    $select = mysqli_query($connection, "SELECT * FROM 'generalInfo' limit 1");
    return mysqli_fetch_array($select);
}
?>

Then I tried to use this file in index.php file as below:

<?php
include "Controllers/Connection.php";
$generalInfo = GetGeneralInfo($con);
?>

but $con has a red underline and I cannot create a connection. I wrote it based on a tutorial but mine gives error. How can I fix it?

Chances are, the path that you are including is wrong – the included path is always relative to the currently executed PHP file. Make sure that “Controllers/Connection.php” path correct and the directory separator is correct.

I recommend using the __DIR__ constant, which always refers to the directory of the currently executed file, for example, debugging with file_exists(__DIR__ . 'Controllers/Connection.php') can easily give you information if the file you are including actually is there.

1 Like

I used echo file_exists("Controllers/Connection.php");

It gives 1. So the path is correct.

You should also have PHP error reporting turned on.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

It will help you spot the error(s) if there are errors.

Another thing you could do is get it to work by having the connection function and the mysqli code together that way it should be simple to get it the way you want it to.

1 Like

If this file is in the same folder that the index.php file is.

PS: Normally you do not use capitals in filenames and folder names. You can use them if you wish, but, make sure you use the correct capitals in the correct places.

1 Like

BTW - I’m just curious what IDE you are using as I know PHPStorm can cause those kind of fits?

1 Like

I use PHPStorm 2021. I tried VSCode too but VSCode doesn’t show errors in red underline.

Sponsor our Newsletter | Privacy Policy | Terms of Service