Iain Simpson
Iain Simpson

Reputation: 469

Problems trying to get php foreach working

I am trying to do the following... select all columns from the table hqfjt_chronoforms_data_addemailtemplate, then echo the data from each record, from the columns emailformname and emailformmessage. I am using the following code but am getting a bunch of errors, I am just learning php so it is probably a bit wrong :-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;
    }
?>

Upvotes: 0

Views: 123

Answers (3)

Tim Wickstrom
Tim Wickstrom

Reputation: 5701

Try this:

$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
}

Upvotes: 0

Kieran Andrews
Kieran Andrews

Reputation: 5885

As mentioned, it is probably better to learn PDO for those just learning. It is more secure, more information and a tutorial can be found here: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

If you want to use objects with a mysql query, something like this will allow you to do so:

<?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

If you would like to do what Frits mentioned, then something like this will achieve your result:

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

There is also arrays as an alternative:

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

Upvotes: 2

Halcyon
Halcyon

Reputation: 57709

Oh this just make me smile :)

Look at the code samples on: http://php.net/mysql_query

Use a while loop with mysql_fetch_assoc or similar.

Upvotes: 1

Related Questions