douzhang7184 2016-12-28 11:51
浏览 31

在php函数中使用参数似乎已经破坏了我的mysql查询[重复]

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>
  • 写回答

1条回答 默认 最新

  • douhunkuang8955 2016-12-28 11:55
    关注

    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) {
        .
        .
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况