简体   繁体   中英

Compare equality and count how many times the same string appears in a returned sql query

I am coding a similar game to cards against humanity and I am a bit stuck on collating the results using PHP, I'm new to PHP so have hit a stumbling block.

So I have all my game data in an SQL table on my localhost and it looks like this roughly: These are the column headers and input as it is in the table:

+------------+-----------------+------------+-----------------+
| FirebaseID |     Votes       | GameNumber |    Submission   |
+------------+-----------------+------------+-----------------+
|     id1    | Option number 6 |   Game 9   | Option number 6 |
|     id2    | Option number 6 |   Game 9   | Option number 1 |
|     id3    | Option number 6 |   Game 9   | Option number 6 |
|     id4    | Option number 1 |   Game 9   | Option number 1 |
|     id5    | Option number 6 |   Game 9   | Option number 4 |
+------------+-----------------+------------+-----------------+

Where Votes is the answer they vote to be the best and Submission is their own submission to the card game. I know that the values don't mean much at the moment but once I get the thing working I'll enter different values for each card.

My code is this:

$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

$q = $_GET['q'];

$sql="SELECT Votes, FirebaseID FROM cauusers WHERE GameNumber = '".$q."'";

$result = mysqli_query($conn,$sql);

$length = $result->num_rows;

if ($result->num_rows > 0) {
// output data of each row
    $myResArray = [];
    $count = 0;

    while($row = $result->fetch_assoc()) {
        $myResArray[$count] = $row["Votes"];
        $count++;
    }

    //var_dump($myResArray);
    $max = 0;
    $winner = "";
    $index = 1;
    //$length = count($myResArray) (This prints 5);

    for($i = 0; $i < $length;$i++){
        for($j = 0; $j < $length; $j++){
            if($myResArray[$i]===$myResArray[$j]){
                $max += 1;
                $winner = $myResArray[$i];

            }
        }
    }
    echo $winner  . "<br>";

    $sqlSel="SELECT FirebaseID FROM cauusers 
             WHERE GameNumber = '".$q."' AND Submission = '".$winner."'";

    $Submission = mysqli_query($conn,$sql);
    echo var_dump($Submission);

    if ($Submission->num_rows > 0) {
        while($row = $Submission->fetch_assoc()) {
            echo $row["FirebaseID"] . "<br>";
        }
    }
 } else {
     echo "0 results";
 }
 mysqli_close($conn);
 ?>

When I print $q I get:

Game 9

When I var_dump $myResArray I get;

 array(5) { 
    [0] => string(15) "Option number 6"
    [1] => string(15) "Option number 6" 
    [2] => string(15) "Option number 6" 
    [3] => string(15) "Option number 1" 
    [4] => string(15) "Option number 6"
 }

So I am trying to gather which card was voted for most and then based on that find out what the person (or people) who submitted that cards ID's are so I can then award the winners with coins for later use in the game. I can see that I am retrieving the data I need but can't seem to access each individual string to compare against each other. At the moment if there are two answers voted for the same amount of times then only one answer is returned.

It prints the correct winning answer but it prints all 5 Firebase ID's instead of the

Any help would be massively appreciated.

Cheers

Instead of coding this logic in PHP, you could do most in SQL. The following query will determine what is most voted for, and return the records that match that vote:

SELECT *
FROM   cauusers
WHERE  Votes = (
    SELECT   Votes
    FROM     cauusers 
    WHERE    GameNumber = 'Game 9'
    GROUP BY Votes
    ORDER BY COUNT(*) DESC
    LIMIT    1);

See SQL Fiddle .

Integrate that in your PHP, and you'll get something like this (not tested):

$sql = "SELECT *
        FROM   cauusers
        WHERE  Votes = (
            SELECT   Votes
            FROM     cauusers 
            WHERE    GameNumber = GameNumber = '$q'
            GROUP BY Votes
            ORDER BY COUNT(*) DESC
            LIMIT    1)";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
    // output winners
    $winner = "";
    while($row = $result->fetch_assoc()) {
        if ($winner=="") {
            $winner = $row['Votes'];
            echo "winner: $winner<br>";
        }
        echo $row["FirebaseID"] . "<br>";
    }
} else {
    echo "0 results";
}

One thing you should still improve: it is better not to inject $q in the SQL string, certainly not when it is a value that is provided by the user. Then you are vulnerable to SQL injection . Better is to use prepared statements and parameters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM