This question already has an answer here:
Edit: This was closed as a duplicate for being about scope, but the issue was actually about my use (or lack) of apostrophes in the SQL query. The scope was incorrect, but wasn't what was causing my issue. I'm happy for this to be deleted, or re-opened for the posting of a solution.
The following code works fine and displays a nice HTML table:
$link = mysqli_connect($host, $username, $password, $db_name);
$round = 1;
$result = mysqli_query($link,"SELECT car.carID, car.team, result.cost FROM result INNER JOIN car ON car.carID=result.carID WHERE result.roundID=$round AND car.class='LMP1'");
echo "<h1>" . 'LMP1' . "</h1>
<table border='1'>
<tr>
<th>Car</th>
<th>Team</th>
<th>Cost</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['carID'] . "</td>";
echo "<td>" . $row['team'] . "</td>";
echo "<td>" . $row['cost'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($link);
But when I wrap it in a function I get the table headers and no data:
function displayClassCosts($class) {
$link = mysqli_connect($host, $username, $password, $db_name);
$round = 1;
$result = mysqli_query($link,"SELECT car.carID, car.team, result.cost FROM result INNER JOIN car ON car.carID=result.carID WHERE result.roundID=$round AND car.class=$class");
echo "<h1>" . $class . "</h1>
<table border='1'>
<tr>
<th>Car</th>
<th>Team</th>
<th>Cost</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['carID'] . "</td>";
echo "<td>" . $row['team'] . "</td>";
echo "<td>" . $row['cost'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($link);
}
displayClassCosts('LMP1');
displayClassCosts('LMP2');
displayClassCosts('GTE_Pro');
displayClassCosts('GTE_Am');
The only differences are the hard-coded string in the query condition and the H1 tag in the first version vs using the passed variable.
Ideas welcome!
</div>
When wrapped in a function, from where will you get the variables for DB connection $host, $username, $password, $db_name
You can use these variables by using global
keyword in your function.
function displayClassCosts($class) {
global $host, $username, $password, $db_name;
.
.
}
Another approach is to pass them as parameters.
function displayClassCosts($class, $host, $username, $password, $db_name) {
.
.
}