PHP & MySQL - How to count the number of records
Okay so I have this 开发者_JAVA技巧web site search script and I'm trying to count how many records will be displayed when the user enters there search term or terms. I was wondering how would I be able to do this when i don't know what keywords will be entered?
Below is my search query.
Here is the part of my PHP & MySQL search code.
$search_explode = explode(" ", $search);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$construct .= "article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$construct .= "OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$construct = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE $construct";
Here is the first error.
MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT users.*, users_articles.* FROM users_articles INNER JOIN users O' at line
Here is the second error.
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
Store the part of your SQL query after FROM
in a variable then you can use COUNT(*)
to get the amount of rows:
$search_explode = explode(" ", $search);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$construct .= "article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$construct .= "OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$from = "FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE $construct";
$count_query = "SELECT COUNT(*) " . $from;
$result = mysql_query($count_query);
$count_result = mysql_fetch_row($result);
$count = $count_result[0];
You might also want to take a look at mysql_num_rows()
精彩评论