好吧,基本上我正在使用youtube上的注册和登录教程。哪个使用旧版本的PHP,我试图更新代码,但是当PHP查询数据库时,它不会返回我期望它返回的内容。
基本上我通过将$ username设置为' euan'来测试查询的工作原理。它存在于数据库中,但出于某种原因,它不会返回“euan”#e;存在。
的init.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();
?>
Connect.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);
?>
Login.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?';
}
}
?>
users.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;
}
?>
数据库图片:(由于代表无法嵌入)
答案 0 :(得分:0)
中,$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;
}
?>