function getConnection() { $conn = mysqli_connect('localhost', 'root', 'root', 'example'); return $conn; } getConnection(); var_dump($conn); Prompt how correctly to return a flow of connection with a DB from function.
The function returns a value. Assign it to a variable.
$conn = getConnection(); This function does not make sense if it is applied correctly, and will bring a lot of harm, if applied as intended.
Connection to the database should occur in the script strictly once. After that, the resulting object should be used to perform all requests in the application.
That is, the only correct use of this function will be
function getConnection() { $conn = mysqli_connect('localhost', 'root', 'root', 'example'); return $conn; } $conn = getConnection(); which of course can be reduced to simple
$conn = mysqli_connect('localhost', 'root', 'root', 'example'); If you plan to call this function in any place where a connection to the database is required, this will lead to the opening of dozens of connections, which will quickly kill the server, even with a little traffic.
Your function returns a value. Where do you use it? The code should be such
$conn = getConnection(); var_dump($conn); Source: https://ru.stackoverflow.com/questions/579661/
All Articles