好吧,基本上我正在youtube上编写注册和登录教程。它使用的是旧版本的PHP,我已经尝试更新代码,但是当PHP查询是数据库时,它不会返回我期望的结果。
基本上,我通过将$username设置为数据库中存在的"euan"来测试查询是否有效,但由于某种原因,它不会返回"euan"存在。
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;
}
?>
数据库的图像:(由于rep.无法嵌入)
https://i.stack.imgur.com/MAkqS.png
http://i.imgur.com/g1niTB3.png
在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;
}
?>