我正在尝试学习mysqli。
我收到此错误:
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
这是我的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;
}
这是我的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'];
}
}
这是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>
login.php中的fetch_assoc()存在什么问题?
答案 0 :(得分:1)
您有2个选择。
您可以通过将结果集中的列绑定到变量,然后使用这些变量输出数据,来处理Statement对象的结果集
<?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>";
}
或者您可以将语句结果集转换为mysqli :: result对象,然后执行几乎所有的操作。
<?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>";
}