我的代码出了什么问题?我的目的是创建一个表,该表将行输入到具有可变行数的html表中。我的代码返回警告:
为foreach()提供的参数无效
<?php
{
$user=$_SESSION['username'];
$pass=$_SESSION['password'];
}
$con = mysql_connect("localhost","****","*****");
var_dump($con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("****", $con);
$result = mysql_query("select * from `order` WHERE username='$user'");
while ($row = mysql_fetch_array($result))
{
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><th>Company Symbol </th><th>Amount </th><th>Actual Stockprice </th><th>Old Stockprice </th><th>Cost </th><th>Profit/loss </th><tr>';
foreach($result as $row) {
$html_table .= '<tr><td>' .$row['company']. '</td><td>' .$row['amount']. '</td><td>' .$row['stock']. '</td></tr>';
}
$html_table .= '</tr></table>';
$html_table = str_replace('<tr></tr>', '', $html_table);
echo $html_table;
}
?>
任何帮助都会很棒。
答案 0 :(得分:2)
我认为这也可能是一个解决方案:
echo '<table border="1" cellspacing="0" cellpadding="2">';
echo '<th>Company Symbol</th><th>Amount</th><th>Actual Stockprice</th><th>Old Stockprice</th><th>Cost</th><th>Profit loss</th><tr>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
foreach($row as $value) {
echo "<td>$value</td>";
}
echo '</tr>';
}
echo '</table'>;
另外,我会考虑使用PDO或mysqli_,因为mysql_已经折旧并且不安全。
答案 1 :(得分:0)
你的foreach循环被破坏了,它应该是
foreach($row as $a_variable_name_that_is_not_result) {
//stuff
}
另外,如果您计划输出不同数量的列,则需要将<tr>
标记移到foreach
循环之外。
答案 2 :(得分:-1)
试试这个
$html_table = '<table border="1" cellspacing="0" cellpadding="2"><th>Company Symbol </th><th>Amount </th><th>Actual Stockprice </th><th>Old Stockprice </th><th>Cost </th><th>Profit/loss </th><tr>';
while ($row = mysql_fetch_array($result))
{
$html_table .= '<tr><td>' .$row['company']. '</td><td>' .$row['amount']. '</td><td>' .$row['stock']. '</td></tr>';
}
$html_table .= '</tr></table>';
答案 3 :(得分:-1)
首先,$ reuslt是一个PHP资源,从
返回mysql_query("select * from `order` WHERE username='$user'");
http://php.net/manual/en/function.mysql-query.php
你已经在这里引用了$ row
while ($row = mysql_fetch_array($result))
所以只需摆脱foreach循环。我根本没有看到它的目的。
除此之外,肯定必须对最终标记的生成方式进行一些更改,因为它将“破坏”/无效