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