Count always returns 1…but does it exist?

点点圈 提交于 2020-01-11 14:08:09

问题


I'm trying to check if a file name already exists in the "reviews" column within a particular category, before it's created. If it already exists, I want to add today's date to the name to make it a unique filename. I can't seem to find if it exists using count. When I echo $checkfile, it always returns 1, whether the file exists or not.

$today = date("Y-m-d");
$list = service_category;
$php_file_name = $last."_".$first.".php";

$check = mysqli_query($sqli, "SELECT count(reviews) FROM table WHERE `category`='$list' AND `reviews`='$php_file_name'");

$checkfile = mysqli_num_rows($check);
    if($checkfile >= 1){
        $php_file_name = $last."_".$first.$today.".php";
        }

回答1:


When you use COUNT() in your query you will always get one row returned even if only to tell you the count is zero. You need to check the value of COUNT(reviews) to get that value:

$result = mysqli_query($sqli, "SELECT count(reviews) AS `count` FROM myTable WHERE `category`='$list' AND `reviews`='$php_file_name'");
$check = mysqli_fetch_assoc($result);

if($check['count'] >= 1){

You'll notice that I gave count(reviews) an alias as it makes accessing that value easier in the PHP code.



来源:https://stackoverflow.com/questions/23096472/count-always-returns-1-but-does-it-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!