0

Please how can I make my server connection global so that it can be accessed in in defined functions? I'm trying to design an automated electronic health records for a friend's MSc dissertation but the connection seems to fail.

It gives me an error. Notice: Undefined variable connection in (file_directory) on line 17 and then the subsequent call to the mysqli_query function fails because of the connection variable being undefined. I've gone ahead to define connection in each function as a quick fix, but is there another way I can go about it? Thanks for your time. The code is given as follows:

<?php
define("DATABASE_HOST","localhost");
define("DATABASE_USER","root");
define("DATABASE_PASS","");
define("DATA_TABLE","ehr");

//define a global connection
global $connection;
$connection = new mysqli(DATABASE_HOST,DATABASE_USER,DATABASE_PASS,DATA_TABLE);
function surname(){
    $sql = "SELECT * FROM lastname ORDER BY RAND()";
    $query = mysqli_query($connection,$sql);
    $result = mysqli_fetch_assoc($query);
    $family_name = $result['lastname'];
    global $family_name;
}
function names_and_gender(){
    $sql = "SELECT * FROM names ORDER BY RAND()";
    $query = mysqli_query($connection,$sql);
    $result = mysqli_fetch_assoc($query);
    global $first_name, $middle_name, $gender;
    $first_name = $result['name'];
    $gender = $result['gender'];
    $sql = "SELECT * FROM names WHERE gender = '$gender' ORDER BY RAND()";
    $query = mysqli_query($connection,$sql);
    $result = mysqli_fetch_assoc($query);
    $middle_name = $result['name'];
}
surname();
echo "First Name: ".$family_name."<br/";
names_and_gender();
echo "First Name".$first_name."Middle Name: ".$middle_name."Gender: ".$gender."<br/";
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
eiodelami
  • 3
  • 2

0 Answers0