0

Trying to get total count of rows using variable in sql query but not able to get that can anyone here help me with this ?

<?php

    $business = $value['business_name'];

    //echo $business;

    $sql = "SELECT COUNT(*) FROM listings_reviews WHERE business_name = '$business'";

    $result = $conn-> query($sql);

    $row = $result -> fetch_assoc();

    //print_r ($row) ;

    $rating = implode($row);

    echo $rating;
    ?>
3
  • Format your code properly and explain what you want to do. Count the amount of Rows? Count the Amount of the Values of the Rows or what do you want to do? Commented Jul 2, 2017 at 10:51
  • @Vikas Temgire you question is half clear do you want to count rows WHERE business_name = '$business'" or you want to count the amount. Edit the question again Commented Jul 2, 2017 at 10:58
  • Yes bro, But I got that solution but thank you for your interest.... Commented Jul 2, 2017 at 11:42

3 Answers 3

2

Give an alias to your COUNT(*) in the SQL, for example, here I have aliased it to cnt.

Then in PHP you can identify clearly the variable of the $row array

$business = $value['business_name'];

//echo $business;

$sql = "SELECT COUNT(*) AS cnt FROM listings_reviews WHERE business_name = '$business'";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    $rating = $row["cnt"];
}

echo $rating;
Sign up to request clarification or add additional context in comments.

Comments

0

Like this:

$q = 'SELECT COUNT(*) AS `all_lines` FROM `table_name`';
$record = $db->query_first($q);

$all_lines = $record['all_lines'];

2 Comments

Where is query_first() in any standard php mysql extension
It is just example based on php mysql class from ricocheting.com. If you want to use plain php replace function query_first() to mysql_query().
0

Group by business name:

$business = $value['business_name'];

$sql = "SELECT COUNT(*) AS c FROM listings_reviews WHERE business_name = '$business' GROUP BY business_name";

$result = $conn->query($sql);

$row = $result ->fetch_assoc();

$listingsByBusiness = $row['c'];

For reference, see

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.