tags:

views:

84

answers:

2

Okay so I have this 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
+2  A: 

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];
Jacob Relkin
How would I do that? sorry for my ignorance.
lone
`mysql_fetch_row($result)[0]` is not legal PHP syntax. You'd have to store the row array in a variable first before accessing its index.
BoltClock
@BoltClock, thanks! Coming from a `C/C++` background, i sometimes forget this pitfall of `PHP`.
Jacob Relkin
+1  A: 

You might also want to take a look at mysql_num_rows()

NullUserException
+1. If the query is simple, running two might be fine. But if the query is complicated, and you're not doing pagination, this is the best way to go.
Matchu
@Matchu I'm doing pagination I just can't count the number of rows.
lone
@Ione, then my solution is appropriate.
Jacob Relkin
@Jacob Relkin for some reason I get an error trying to use your code any suggestions?
lone
@Ione, what does the error say?
Jacob Relkin
@Ione, try my revised answer.
Jacob Relkin