问题
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