Proper Use of MySQLi

Can someone instruct me on how to use the MySQLi extension in PHP? I have always used MySQL procedural functions before and want to make changes, but I find the examples on PHP.net and other sites too complicated. There seem to be several ways to do the same. I want to use it in the following method:

function checkCredentials($username, $password)
{
    $q = $db->prepare("SELECT id FROM `users` WHERE username=? AND password=? LIMIT 1");
    $q->bind_param('ss', $username, $password);
    $q->execute();
}

Regarding the PHP.net examples, but I get this error:

Fatal error: call a member function Prepare () for a non-object in C: \ XAMPP \ HTDOCS \ Classes \ user.class.php on line 14

(the variable $dbis a handle in my user class and works fine)

The documentation seems to be too complicated for those who have never used hold before and for someone who is moderately new to classes and OOP.

- , , / / , ?

.

+3
3

, $db ( null). error_reporting E_ALL, $db... - $db :

:

function checkCredentials($username, $password) {
    global $db;

- ( ):

function checkCredentials($username, $password) {
    $q = $this->db->prepare();

- , :

function checkCredentials($username, $password, $db) {
+2

$db . global $db :

function checkCredentials($username, $password)
{
    global $db;
    $q = $db->prepare("SELECT id FROM `users` WHERE username=? AND password=? LIMIT 1");
    $q->bind_param('ss', $username, $password);
    $q->execute();
}

.

+2

, , $db .

, $db , - global. PHP - PHP, :

function foo() {
    global $db;
    // do stuff with $db
}

, FALSE, mysqli_connect() - , - .

+2

Source: https://habr.com/ru/post/1762301/


All Articles