E
E
Evgeny Krysanov2014-11-15 07:16:35
PHP
Evgeny Krysanov, 2014-11-15 07:16:35

Mysqli database query description in class?

I want to describe the processing of a request to the database in a class method.

function verifyUser($name) {
    $query = "SELECT psw, user_group FROM users WHERE name = ?";
  $stmt = $mysqli->stmt_init();
  if ($stmt = $mysqli->prepare($query)) {
    /* связываем параметры с метками */
    $stmt->bind_param("s", $name);

    /* запускаем запрос */
    $stmt->execute();

    /* связываем переменные с результатами запроса */
    $stmt->bind_result($psw, $user_group);

    /* получаем значения */
    $stmt->fetch();

    printf("login - %s, password - %s, user_group - %s", $name, $psw, $user_group);

    /* закрываем запрос */
    $stmt->close();
    }
  }
}
$name = $_POST["name"];
$auth = new Auth($name);
$auth->verifyUser($name);

$mysqli is an object of the mysqli class. The connection to the database has been completed.
Result: Fatal error: Call to a member function stmt_init() on a non-object
Points to the string $stmt = $mysqli->stmt_init();.
If you use the code outside the class, then everything works. I figured out that $stmt must be an object. I don’t know how to declare it in a class and I’m already tired of looking for examples.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2014-11-15
@krysanoveo

$name = $_POST["name"];
$db = new mysqi();
$auth = new Auth($db); 
$auth->verifyUser($name);

In the constructor you write $this->db = $db;

R
Rsa97, 2014-11-15
@Rsa97

And where does $stmt? The error says that the stmt_init() method is not called on an object, that is, $mysqli is not an object.

R
Reey, 2014-11-15
@Reey

The error says $mysqli is not an object.

function verifyUser($name) {
    $query = "SELECT psw, user_group FROM users WHERE name = ?";

    require_once path_to_mysqli_class //на случай если файл не в автолоудинге и еще не заинклюжен
    $mysqli = new Mysqli();
    $stmt = $mysqli->stmt_init();
    ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question