Counting database entries that are the same/mysqli

2019-09-20 01:26发布

问题:

There doesn't seem to be a similar question anywhere. I need this to just loop through each unique value, and then kick out how many are the same but, somehow I'm using mysqli_num_rows wrong. Thank you in advance.

//This portion fetches unique entries that aren't empty
$query = "SELECT DISTINCT burger ";
$query .= "FROM newbob ";
$query .= "WHERE burger != '' ";
$query .= "ORDER BY burger ASC ";


$result = mysqli_query($dbc, $query);
if (!$result){
    die ("Database query failed.");
}

//and I want this portion to count how many there are that are the same, and
//just add it next to it.
while($entries = mysqli_fetch_assoc($result)) {
echo $entries["burger"];
$query2 = "SELECT burger ";
$query2 .= "FROM newbob ";
$query2 .= "WHERE burger = '$entries[burger]'";
$result2 = mysqli_query($dbc, $query2);
$rowcount = mysqli_num_rows($result2);

echo "( " . $rowcount . " )<br>";
}

Edit: my query is failing somehow, I fixed the spaces in the query but, I'm wondering if I'm doing something wrong with the $entries[burger] part of the query.

Edit2: Might sit here and type myself through it! I just needed some single quotes around it. Now I'm failing when it hit's an apostrophe though. Any ideas?

回答1:

Yup, just worked my way right through it. It's not necessarily beautiful but, I'm not sure how to do it better. The new bottom portion is

//and I want this portion to count how many there are that are the same, and
//just add it next to it.
while($entries = mysqli_fetch_assoc($result)) {
echo stripslashes($entries["burger"]);
 foreach ($entries as $entries) {
            $entries2 = mysqli_real_escape_string($dbc,$entries); }
            $query2 = "SELECT burger ";
            $query2 .= "FROM newbob ";
            $query2 .= "WHERE burger = '$entries2'";
            $result2 = mysqli_query($dbc, $query2);
                            if (!$result2){
    die ("<br>Database query failed.");
}
            $rowcount = mysqli_num_rows($result2);

           echo "( " . $rowcount . " )<br>";
 }