'Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_assoc() [duplicate]
i'm trying to learn mysqli.
i get this error:
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetch_assoc() in C:\xampp\htdocs\bk2\login.php:14 Stack trace: #0 {main} thrown in C:\xampp\htdocs\bk2\login.php on line 14
and here is my db-conn.php:
<?php
require('bk-config.php');
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
here is my login.php:
<?php
include 'db-conn.php';
$post_username = $_POST['post_username'];
$post_password = $_POST['post_password'];
$sql = "SELECT username, password FROM users WHERE username = ? AND password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $post_username, $post_password);
$stmt->execute();
$rows = $stmt->num_rows;
if($rows = 1){
while ($row = $stmt->fetch_assoc()) {
echo $row['username'];
}
}
here is the form i have in the index.php:
<form class="px-4 py-3" action="login.php" method="post">
<div class="form-group">
<label>Username:</label>
<input type="text" name="post_username" class="form-control" placeholder="Enter username">
<label class="mt-2">Password:</label>
<input type="password" name="post_password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-danger float-right">Login</button>
</form>
Where is the problem whit the fetch_assoc() in login.php?
Solution 1:[1]
You have 2 options.
You can process the resultset from the Statement object like this by binding the columns in the resultset to variables and then use those variables to output the data
<?php
include 'db-conn.php';
$post_username = $_POST['post_username'];
$post_password = $_POST['post_password'];
$sql = "SELECT username, password FROM users WHERE username = ? AND password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $post_username, $post_password);
$stmt->execute();
// bind variables to the resulted values
$stmt->bind_result($u, $p);
while ($row = $stmt->fetch()) {
echo "Username = $u and Password = $p <br>";
}
Or you can convert the statements resultset to a mysqli_result object and do pretty much what you were doing.
<?php
include 'db-conn.php';
$post_username = $_POST['post_username'];
$post_password = $_POST['post_password'];
$sql = "SELECT username, password FROM users WHERE username = ? AND password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $post_username, $post_password);
$stmt->execute();
// convert to a result
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "Username = $row[username] and Password = $row[password] <br>";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |