can't find multiple values in SQL

64 Views Asked by At

I have a DB full of players and I am trying to create a page to register them into a specific tournament. The tournament director will search for players by username (which is only "firstname.lastname").

The problem I'm experiencing is that when I run loop to echo each $players[$x] it only gives the ID for the first matching DB record, and repeats the number once for each match. Rather than returning ID 7, 11, 26 it will return 7, 7, 7. Please can someone explain why?

I have written the following code in a .php file:

session_start();
if (isset($_POST['newsearch']) === true && empty($_POST['newsearch'] === false)){
require 'dbconnect.php';
$term = $_POST['newsearch'];
$terms = "%" . $term . "%";

$query = ("SELECT PlayerID FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
$search = mysqli_fetch_assoc($run_query);
$players = array ();

    do{
    //Get data from players table
    $PlayerID = $search['PlayerID'];
array_push ($players, $PlayerID);        
    }
        while ($dbsearch = mysqli_fetch_assoc($run_query));}
2

There are 2 best solutions below

2
On BEST ANSWER

You have more that one fetch for the same query, replace the code after $run_query = mysqli_query($dbcon, $query); with this code:

 $players = array ();
 while ($dbsearch = mysqli_fetch_assoc($run_query))
     {
         array_push($players, $dbsearch['PlayerID']);;
     }
0
On

Your while loop is wrong

$query = ("SELECT PlayerID FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);
$search = mysqli_fetch_assoc($run_query);
$players = array ();

do{
    //Get data from players table
    $PlayerID = $search['PlayerID'];
    array_push ($players, $PlayerID);        
    }
    while ($search = mysqli_fetch_assoc($run_query));
}

Put $search instead of $dbsearch

$search = mysqli_fetch_assoc($run_query))

Note : your query is vulnerable to SQLI