试图让php foreach工作的问题


Problems trying to get php foreach working

我想做以下事情…选择表hqfjt_chronoforms_data_addemailtemplate中的所有列,然后从列emailformname和emailformmessage中回显每条记录中的数据。我正在使用以下代码,但我得到一堆错误,我只是学习php,所以它可能有点错误:-S .

<?php
    $query = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addemailtemplate") or die(mysql_error());
    foreach($query as $detail) {
        echo $emailarray->emailformname;
        echo $emailarray->emailformmessage;
    }
?>

如前所述,对于那些正在学习的人来说,学习PDO可能更好。它更安全,更多信息和教程可以在这里找到:http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

如果你想在mysql查询中使用对象,像这样的东西将允许你这样做:

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
mysql_free_result($result);
?>
http://php.net/manual/en/function.mysql-fetch-object.php

如果你想做Frits提到的事情,那么像这样做将达到你的结果:

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}
http://php.net/manual/en/function.mysql-fetch-assoc.php

也有数组作为替代:

http://php.net/manual/en/function.mysql-fetch-array.php

哦,这只是让我微笑:)

查看下面的代码示例:http://php.net/mysql_query

使用whilemysql_fetch_assoc或类似的环

试试这个:

$sql = "SELECT * FROM hqfjt_chronoforms_data_addemailtemplate";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
     echo $row['emailformname']; // emailformname is a col name
     echo $row['emailformmessage']; // emailformmessage is a col name
}