-1

Here is my code:

<?php
$db_host        = 'localhost';
$db_user        = 'root';
$db_pass        = 'root';
$db_database    = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp() {
    $patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
    echo $patient['name'];
}
temp();
?>

When I run this, the query doesn't seem to execute and nothing shows up on the page. However, if I remove the function and just change the code to this:

<?php
$db_host        = 'localhost';
$db_user        = 'root';
$db_pass        = 'root';
$db_database    = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
// function temp() {
    $patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
    echo $patient['name'];
// }
// temp();
?>

It works, and the patient's name is displayed.

What is going on here?

apoorvumang
  • 169
  • 1
  • 2
  • 8
  • 5
    its a scope issue. `$link` is out of scope, you'll need to pass the connection in the argument. `temp($link)` – Kevin May 08 '15 at 09:57
  • Because of Scope. http://php.net/manual/en/language.variables.scope.php . If you still wanna use outside variable in function, you can declare `global $link;` inside function and you'll be good. – Bhavesh G May 08 '15 at 10:17
  • thanks! can't believe I'm so stupid – apoorvumang May 08 '15 at 11:23

2 Answers2

0

Pass $link to the function. It is not working because of the scope of that variable. Try with -

function temp($link) {
    $patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
    echo $patient['name'];
}
temp($link);
Kevin
  • 41,694
  • 12
  • 53
  • 70
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

Pass the $link to function as a parameter. Try this:

<?php
$db_host        = 'localhost';
$db_user        = 'root';
$db_pass        = 'root';
$db_database    = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp($link) {
    $patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
    echo $patient['name'];
}
temp($link);
?>
Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38