0

I am using this code

$host = "localhost";
$db_name = "db_name";
$username = "username ";
$password = "password ";

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

try {
  $conn = new PDO("mysql:host=$host;port=3306;dbname=$db_name", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

$layers = getLayers();


function getLayers() {
    $query = "SELECT * FROM layers ORDER BY id ASC";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $list = $stmt->fetchall(PDO::FETCH_ASSOC);
    if(count($list) > 0){
        foreach ($list as $key => $value) {
            $data[] = array('id' => $value['id'], 'name' => $value['name'], 'price' => $value['price'], 'is_model_layer' =>  $value['is_model_layer']);
        }
    } else {
        $data[] = array('id' => '0', 'name' => 'Not Found');
    }
    return $data;
}

Getting Error

Connected successfully Notice: Undefined variable: conn in /var/www/html/path/ajax.php on line 24

Fatal error: Uncaught Error: Call to a member function prepare() on null in /var/www/html/speaker-config/ajax.php:24 Stack trace: #0 /var/www/html/path/ajax.php(19): getLayers() #1 {main} thrown in /var/www/html/path/ajax.php on line 24

Can any one tell me why DB connection variable is getting error. Thank you

krr2020
  • 23
  • 1
  • 7
  • `$conn` variable is in global scope, but not accessible in your function, unless you pass it as a parameter or include this line `global $conn;` before trying to use it. – Triby Jun 20 '20 at 06:24
  • `$layers = getLayers($conn); function getLayers($conn) { }` Worked for me, thank you – krr2020 Jun 20 '20 at 06:29

0 Answers0