Issue
So i've been having an issue with NetBeans code completion. I'm currently trying to set up a database connection that i can use in my other files. Inside of my connection.php file, I have access to all of the usual database methods. My end goal is to use prepared statements for my queries.
However, when i am inside my register.php file, with connection.php required at the top, suddenly code completion doesn't work anymore. I get the generic popup. This is the file i would like to actually use those prepared statements in. I would also like to avoid having to open a new connection in every file.
So my question to you is, is it me or is it NetBeans?
connection.php
$host = "localhost";
$username = "root";
$pass = "password";
$database = "LoganWebsiteUserLogin";
try {
$conn = new PDO('mysql:host=localhost;dbname=' . $database . ';charset=utf8mb4', $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected Successfully!";
} catch (PDOException $e) {
echo "Connection failed! " . $e->getMessage();
}
register.php
<?php
require 'connection.php';
// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];
// trying to access $conn from connection.php here, however autocomplete for
// it is not working. NetBeans doesn't know that $conn is a PDO
$conn->
Solution
It works in PhpStorm but not in Netbeans. But anyway, global variables are not recommended and lead to unwanted side effects. Maybe try a different approach.
Example:
connection.php
<?php
function db(): PDO
{
static $pdo = null;
if (!$pdo) {
$host = "localhost";
$username = "root";
$password = "password";
$database = "LoganWebsiteUserLogin";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
];
$pdo = new PDO("mysql:host=$host;dbname=$database;charset=utf8mb4", $username, $password, $options);
}
return $pdo;
}
register.php
<?php
require_once __DIR__ . '/connection.php';
// Create session variables
$_SESSION['firstName'] = $_POST['firstName'];
$_SESSION['lastName'] = $_POST['lastName'];
$_SESSION['email'] = $_POST['email'];
// Works :-)
db()->
Answered By - odan