0

I'm trying to pass a variable from a dbh.inc.php to index.php using include_once, But it gives me an error in $con at index.php that it is not defined

dbh.inc.php:

<?php

$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "loginsystem";

$con = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

indux.php:

<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html lang="">
<head>
    <title></title>
</head>
<body>
<?php
$sql = 'SELECT * FROM users;';
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);

if($resultCheck > 0)
{
    while ($row = mysqli_fetch_assoc($result))
    {
        echo $row['user_uid'] . "<br>";
    }
}
?>
</body>
</html>
2
  • Maybe the path for the include is wrong because there is nothing wrong with your code Commented Nov 21, 2021 at 16:27
  • If you put them in the same file it works?! If so then you are probably calling the file with the wrong path... if it doesn't it means that $con wasn't created because you didn't succeed in loggin in to you db. Commented Nov 21, 2021 at 17:27

1 Answer 1

1

Usually you can access variables from one file to another by including file like:

vars.php

<?php

$color = 'green';
$fruit = 'apple';

?>

test.php

<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

First of all check it by turning on the error reporting for that particular file and you will get error if the included path was not correct.

you can add it as follow:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Thanks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.