嗯,基本上我正在制作 YouTube 上的注册和登录教程。它使用旧版本的 PHP,并且我尝试更新代码,但是当 PHP 查询数据库时,它不会返回我期望它返回的内容。
基本上,我通过将 $username 设置为数据库中存在的“euan”来测试查询是否有效,但由于某种原因,它不会返回“euan”存在。
初始化.php
<?php
session_start();
error_reporting(0);
require 'database/connect.php'; echo '[connect loaded]'; echo ' ';
require 'functions/users.php'; echo '[users loaded]'; echo ' ';
require 'functions/general.php'; echo '[general loaded]'; echo ' ';
$errors = array();
?>
连接.php
<?php
$connection_error = 'We\'re experiencing connection issues. Come back later.';
$con = mysqli_connect('localhost','root','') or die($connection_error);
mysqli_select_db($con,'forum') or die($connection_error);
?>
登录.php
<?php
include 'core/init.php';
$username = "euan";
echo $username; echo ' '; echo ' '; echo ' ';
if (user_exists($username) === true) {
echo '[Yeah that exists]';
} else {
echo '[Nah thats not there]'; echo ' ';
echo $username; echo ' ';
}
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
}
}
?>
用户.php
<?php
function user_exists($username) {
echo $username;
//$username = sanitize($username);
$query = mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = $username");
return(mysqli_query($query, 0) == 1) ? true : false;
}
?>
数据库图像:(由于代表原因无法嵌入。)
最佳答案
在您的 users.php 中,$username
应位于 '
引号内,如下所示,这样您的查询将类似于 where username='euan'
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
并更改函数的返回值,使用mysqli_affected_rows($con)==1
这应该可以解决您的问题,并且 $query
也不是必需的
<?php
function user_exists($username) {
echo $username;
//$username = sanitize($username);
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return(mysqli_affected_rows($con) == 1) ? true : false;
}
?>
关于PHP 没有从 MySQL 查询返回正确的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29238991/