我的sql应该打印两行。
id符号共享 3 CSCO 40 3 FB 200
但此代码仅打印第一行两次。像这样: jharvard拥有40股CSCOjharvard股份,拥有40股CSCO
为什么?
先谢谢你。
$users = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
$rows = query("SELECT * FROM stocks WHERE id = ?", $_SESSION["id"]);
$stock = $rows[0];
$username = $users[0];
foreach ($rows as $row)
{
if( $stock["id"] === $_SESSION["id"])
{
print("<td>" . $username["username"] . " has " . $stock["Shares"] . " shares of " . $stock["Symbol"] . "</td>");
}
}
答案 0 :(得分:1)
原因是你的变量在循环中
foreach ($rows as $row) {
if( $stock["id"] === $_SESSION["id"]) {
print("<td>" . $username["username"] . " has " . $stock["Shares"] . " shares of " . $stock["Symbol"] . "</td>");
}
}
您正在打印您之前定义的$stock
的值:
$stock = $row[0];
因此始终输出第一行的数据。
我怀疑你想改变你的循环如下:
foreach ($rows as $row) {
// Changed from $stock['id'] to $row['id']
if( $row["id"] === $_SESSION["id"]) {
// Changed from $stock['Shares'] and ['Symbol'] to $row['Shares'] and ['Symbol']
print("<td>" . $username["username"] . " has " . $row["Shares"] . " shares of " . $row["Symbol"] . "</td>");
}
}