1

我试过了,但对我没有用......我的意思是我正在拿到我的桌子,并且行数是正确的。但是,当我使用 $row['ColumnName']... 时,我一直在获取列的实际名称,而不是数据本身。如果我向表中添加更多行数据,我会增加行数,但数据仍然相同。只有列名。

有人遇到过这个问题吗?以及如何解决?php 版本:5.3 和 mysql 版本:5.5

$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('employeedb');

$query = "SELECT * FROM employee"
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";          
//$row['index']     the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection
4

3 回答 3

1

mysql_已弃用,这是 PDO 中的一些代码。

//Open PDO connection
try {
    $db = new PDO("mysql:dbname={'employeedb'}; host={'localhost'}", 'root', '');
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $Exception) {
    echo "There was an error.";
}
//Query prep
$query = $db->prepare("
    SELECT *
        FROM employee
");
//Query execution; try to use prepared statements always
$query->execute();    
//create string $output
$output = "<table>";
//for rows of indeterminable quantity, use foreach()
foreach($query as $table) {
    //append to $output
    $output .= "<tr><td>";
    $output .= htmlspecialchars($table["name"]);
    $output .= "</td><td>";
    $output .= htmlspecialchars($table["age"]);
    $output .= "</td></tr>";          
}    
$output .= "</table>";
//print $output
echo $output;
//close PDO connection
$db = null;

顺便说一句,请确保使用htmlspecialchars(). 我还会考虑使用某种try/catch复杂的方法来确保正确处理错误并且不会向用户透露相关信息。

哦,看来你解决了。如果您在未定义数量的行中工作,而不是使用while()循环,请考虑使用foreach()循环。

于 2013-10-08T02:12:17.340 回答
0

您可以尝试使用数字索引而不是列名。如下图

  while($row = mysql_fetch_array($result)){  

echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";          

  }
于 2013-10-08T02:13:06.413 回答
0

尝试这个:

$db = new PDO ('localhost', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT * FROM employee"
$statement = $db->prepare($query);
$statement->execute();
echo '<table>';
    foreach($statement as $row){
        echo '<tr>';
          echo '<td>', $row['name'],'</td>';
          echo '<td>',$row['age'],'</td>';
        echo '</tr>';
    }
echo '</table>';
于 2013-10-08T02:15:32.307 回答