Monday 3 September 2018

The simple mysqli query does not work

I'm trying to get simple info from a database and echo it to screen, but it's not working for me.

$con=mysqli_connect("SERVER.COM","USERNAME","PASSWORD", "DATABASE");

function GetTeamFixtures($team)
{
    $queryget = mysqli_query($con, "SELECT * FROM 'mlsfixtures' WHERE team='$team' LIMIT 1");
    $row = mysqli_fetch_assoc($queryget);
    $gw1 = $row['gw1'];
    $gw2 = $row['gw2'];

    echo $team.' '.$gw1.' '.$gw2.'<br>';
}

$team = "Chicago Fire"; GetTeamFixtures($team);
$team = "Chivas USA"; GetTeamFixtures($team);
$team = "Colorado Rapids"; GetTeamFixtures($team);
//continue for all teams - removed for simplicity

Here are the error messages I get (line 46 is the $queryget= one and line 49 is the $row = one).
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in server.com\teamfix.php on line 46
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in server.com\teamfix.php on line 49
Any idea why? I'm not sure if there's an easier way of doing the same thing but for 19 different teams.

You don't have access to $con from within your function. This should work:
$con = mysqli_connect("SERVER.COM","USERNAME","PASSWORD", "DATABASE");

function GetTeamFixtures($team)
{
    global $con;
    $queryget = mysqli_query($con, "SELECT * FROM `mlsfixtures` WHERE `team`='$team' LIMIT 1");
    $row = mysqli_fetch_assoc($queryget);
    $gw1 = $row['gw1'];
    $gw2 = $row['gw2'];

    echo $team.' '.$gw1.' '.$gw2.'<br>';
}

P.S. If the $team you're passing in to GetTeamFixtures comes from user input, you should prepare your statement, to prevent SQL injection.

0 comments:

Post a Comment