简体   繁体   English

为什么我从这段代码中得到“Query is empty”错误?

[英]Why am I getting a “Query was empty” error from this block of code?

I'm trying to make a login/register system and when you press login it should say exists... 我正在尝试建立登录/注册系统,当你按下登录时,它应该说存在...

<?php
include 'core/init.php';


function user_exists($username){
$username = sanitize($uusername);
$query = mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `username` = '$username'");

$result = mysql_query($query) or die(mysql_error());  // Check if query was successful
$row = mysql_fetch_array($result); // fetch the first row
return ($row[0] > 1);  // If there is one or more users with this name, return true.




}

Here is the code that should make the page say "Exists": 以下是应该使页面显示“存在”的代码:

<?php
include 'core/init.php';

if(user_exists('Zuzima') === true) {
echo 'exists';
}
die();

if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];

if(empty($username) === true || empty($password) === true){
    $errors[] = 'You need to a username and password.';
} else if (user_exists($username) === false) {
    $errors[] = 'We can\'t find that username. Have you registered?';
}
}
?>

Please help me I've been working on this for 6 months at the least. 请帮助我,至少6个月我一直在研究这个问题。

If there is one or more users with this name, return true. 如果有一个或多个具有此名称的用户,则返回true。

So shouldn't return ($row[0] > 1); 所以不应该return ($row[0] > 1); just be return ($row[0] >= 1); 只是return ($row[0] >= 1);

You must alias any aggregates to use in an array. 您必须为要在数组中使用的任何聚合设置别名。

SELECT COUNT (`user_id`)  AS userIdCount ...

It would just be easier to return a single column and use the row count to determine if there is a record for your user. 返回单个列并使用行计数确定是否有用户记录会更容易。

Further, mysql_ functions have been deprecated. 此外,不推荐使用mysql_函数。 You need to use PDO or mysqli_ with prepared statements. 您需要在准备好的语句中使用PDOmysqli_

The $query is getting assigned a resource handle from mysql_query , then you are passing that resource handle in as a string to mysql_query mysql_query获取$query的资源句柄,然后将该资源句柄作为字符串传递给mysql_query

$query = mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `username` = '$username'");

$result = mysql_query($query) or die(mysql_error());

should be 应该

$result = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'") or die(mysql_error())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM