Forum Moderators: coopster

Message Too Old, No Replies

foreach() from a database?

how to do a foreach loop from data from a DB..

         

ahmedtheking

10:04 am on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, I am making a script to insert data into a database (via a html form). But instead of me making a form with about 30 fields (cos thats so boring), i tried making a foreach loop that would print out a field for each field in the DB, but it didnt work! Heres the script, can anyone tell me where i went wrong?

<?php
require ("config.php");

// create loop
$Query = "SELECT * from $TableName"; // set query to get everything from the db
$Result = mysql_db_query ($DBName, $Query, $Link);
print ("<form action=\"HandleForm.php\" method=POST>");
while ($Row = mysql_fetch_array ($Result))
{

// begin for each loop

foreach($Row as $value) {

print ("$value <textarea name=\"Array[$value]\" rows=5 cols=40></textarea><br>\n\n");

}

}
mysql_close ($Link);

print ("<input type=SUBMIT name=\"SUBMIT\" value=\"Submit!\"></form>");
?>

dreamcatcher

10:52 am on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Maybe try:


while ($Row = mysql_fetch_array ($Result))
{

$rows[] = $Row['rowname'];

}

foreach($rows as $value)

{

print ("$value <textarea name=\"$value\" rows=5 cols=40></textarea><br>\n\n");

}

ahmedtheking

11:13 am on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



with the var '$row[rowname]', that would just print that row won't it?

I want it to print out all the fields so i can enter rows into the db.

instead of using $row, would $field work?

dreamcatcher

11:28 am on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



with the var '$row[rowname]', that would just print that row won't it?

No, the $rows[] array contains all your row names. Much the same as the original while loop. When the loop runs, it adds the value of each row to the array. The foreach loop displays the array.

Give it a try and you`ll see how it works.

ahmedtheking

11:38 am on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



ok, thank you! :D

ahmedtheking

11:42 am on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



it returned this error:

Warning: Invalid argument supplied for foreach() in /home/firestar/public_html/peter/insertintodatabase.php on line 20

dreamcatcher

12:03 pm on Sep 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The error means that the $rows[] array held no values. Have you used the correct row name in your while loop? Is your database query correct? Use mysql_error() to root out any problems.

ahmedtheking

1:06 am on Sep 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



sorry to ask this, but how do i use the mysql_error() function?

dreamcatcher

7:27 am on Sep 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry for being vague.

$Result = mysql_db_query ($DBName, $Query, $Link) or die(mysql_error());

ahmedtheking

1:01 pm on Sep 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Fatal error: Cannot use [] for reading in /home/firestar/public_html/peter/insertintodatabase.php on line 16

do u want the database details?

dreamcatcher

6:32 pm on Sep 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



No thats ok. Sorry, I have no idea why you are receiving that error. Maybe some of the other guys know. :(

jatar_k

7:02 pm on Sep 7, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well first thing is don't use mysql_db_query

This function has been deprecated since PHP 4.0.6. Do not use this function. Use mysql_select_db() and mysql_query() instead.

and to be sure, what's on line 16

also maybe give the snippet of code that you are using now, that would help also.

ahmedtheking

6:43 pm on Sep 8, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok, heres the PHP code (from line number 6 - 32)

<?php
require ("config.php");

// create loop
$Query = "SELECT * from $TableName"; // set query to get everything from the db
$Result = mysql_db_query ($DBName, $Query, $Link) or die(mysql_error());
print ("<form action=\"HandleForm.php\" method=POST>");
while ($Row = mysql_fetch_array ($Result))
{

$rows[] = $Row[];

}

foreach($rows as $value)

{

print ("$value <textarea name=\"$value\" rows=5 cols=40></textarea><br>\n\n");

}

mysql_close ($Link);

print ("<input type=SUBMIT name=\"SUBMIT\" value=\"Submit!\"></form>");
?>

Do you want SQL/table fields?

jatar_k

7:07 pm on Sep 8, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



>> Do you want SQL/table fields

No. I am having a hard time understanding the point of this whole script so I will go through it line by line. It would also help me if you could explain verbally what you want this little script to accomplish.

require ("config.php");

I assume that connect statement and the select_db statement are in there

$Query = "SELECT * from $TableName"; // set query to get everything from the db

Ok so you are selecting everything from the db. Is there only 1 row in there? If not you may need to add a primary key and use that in a where clause. That will depend on what you are actually doing with this form. If you just want any 1 row to find out your column names then use LIMIT 1.

$Result = mysql_db_query ($DBName, $Query, $Link) or die(mysql_error());

don't use mysql_db_query use mysql_query and select the proper db using mysql_select_db after you connect. You also don't need to specify the $link in each call because it will use the last opened and I hope you only have one open. So change the above line to $Result = mysql_db_query ($Query) or die(mysql_error());

print ("<form action=\"HandleForm.php\" method=POST>");

ok printing the form tag

while ($Row = mysql_fetch_array ($Result)) {
$rows[] = $Row[];
}

now i am lost. Are we outputting a form to the browser for each row in the db? I also think that $rows[] = $Row[]; should be $rows[] = $Row; That will pop the row into your array and ultimately create a multi dimensional array with all of your data returned from your query.

foreach($rows as $value) {
print ("$value <textarea name=\"$value\" rows=5 cols=40></textarea><br>\n\n");
}

This all depends on what exactly you are trying to do. I have some ideas but it would be better if you could clarify what you are actually trying to do. This may work for the first iteration but it will probably blow up on the second because you are building a multidimensional array and will have to reference more this way
foreach($rows[$somecounter] as $value) {

mysql_close ($Link);
print ("<input type=SUBMIT name=\"SUBMIT\" value=\"Submit!\"></form>");

close the link and echo the closing form tag, easy enough.

ahmedtheking

1:19 am on Sep 9, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ok, what i want the script to do is to echo every field into a textarea so that i don't have to keep updating the script when/if i add new fields!

the form that will be echoed is going to be used to add data 2 the DB!

ergophobe

2:51 pm on Sep 9, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Okay, I assume that you want the form to have some nice labels right? So you don't want to just run through with a counter and have

field1 [current data]

but rather
lastname [current data]

Furthermore, you certainly do not want to output all fields to the form, because then users would be able to modify primary keys and your whole DB would be screwed.

So first, I would grab the names of the fields, then build the form using that. Maybe that's more complicated than you want, but it has some advantages
- post array indexes will correspond to field names in the DB
- you'll have semi-meaningful labels for your fields.
- you'll be able to filter out certain fields by building an "exclude_field" array, which could go in your config file.

So, once again, we'll assume that your connection and all that is made in your config file and you've opened your form with the proper <form> tag higher up. We're now trying to get the individual fields. Now you need to get the field names.


$field_names = array();
$exclude_fields = array('id', 'last_updated');
$fields = mysql_list_fields("my_database", "my_table");
$num_fields = mysql_num_fields($fields);
for ($i = 0; $i < $num_fields; $i++)
{
$new_field = mysql_field_name($fields, $i);
if (!in_array($new_field, $exclude_fields)
{
$field_names[] = $new_field;
}
}

Now you have a list of all fields in your database, minus those fields that the user should not edit. You don't want them editing your primary key ('id') or the last update because you would set that with now(), so you don't want to output that to a form.

Now get your data from the table

$query = "SELECT * from my_table WHERE id=$id";
$result = mysql_query($query);
$data = mysql_fetch_array($result);

Now we get our data and put it in the form


foreach ($fieldnames as $field)
{
$form .= "<p>$field" . '<input type="text" name="field" value="{$row[$field]}">';
}

Now you add in your submit button and all that and close your form.

Caveats:
- not tested, just typed into the WebmasterWorld window
- you may need to do some checking to account for the cases when, say, the query returns no rows. Basic error control and so on.

PS - I see you wanted textarea, not input fields, but I assume that the change is clear enough.
Tom

SkyDog

3:41 pm on Sep 10, 2004 (gmt 0)

10+ Year Member



I assume you want to make a blank input form based upon your table structure. Here is an easy way:

$sql="show columns from table_name;
$result=mysql_query($sql);
while($row=mysql_fetch_assoc($result)){
if($row['Key']=="PRI")continue;//skip primary key, probably auto_increment
echo $row['Field'],"<br>\n"; //this is the column name to be used for your input field
}