Click here to Skip to main content
15,922,894 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have developed html simple form called dbdata and there is a submit button and once click it, it goes to a page called displaydb.php

PHP
<?php

	define('DB_NAME', 'phpdatabase');
	define('DB_USER', 'root');
	define('DB_PASSWORD', 'root');
	define('DB_HOST', 'localhost');

	$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
	
	$filename = 'Uploads/'.strtotime("now").'.csv';
	
	
	$sql = mysqli_query($link,"SELECT * FROM userdb") or die(mysqli_error());
	$num_rows = mysqli_num_rows($sql);
	
	if($num_rows >= 1)
	{		
	$row = mysqli_fetch_assoc($sql);
	$fp = fopen($filename,"w");
	$seperator = "";
	$comma = "";
	
	foreach($row as $name => $value){
	
	$seperator .= $comma . '' .str_replace('','""',$name);
	$comma = ",";
	
	}
	$seperator .= "\n";
	echo $seperator;
	
	fputs($fp,$seperator);
	
	mysqli_data_seek($sql, 0);
	
	while($row = mysqli_fetch_assoc($sql));
	{
	$seperator = "";
	$comma = "";
    
	foreach($row as $name => $value){
	$seperator .= $comma . '' .str_replace('','""',$value);
	$comma = ",";
	}
	
	$seperator .= "\n";

	fputs($fp,$seperator);
	}
	fclose($fp);
	}


?>


but this gives me an error called

Quote:
Warning: Invalid argument supplied for foreach() in C:\wamp64\www\Websites\displayDB.php on line 41


which is second foreach loop.

PHP
foreach($row as $name => $value){
	$seperator .= $comma . '' .str_replace('','""',$value);
	$comma = ",";
	}


when i try this with one foreach loop. it will print database data on a differant page. but only database header only.

id, name, address
like that.
and it will creates a csv file as well with database header.
but i want all data to be printed on the file.
that's why i have created a second foreach loop.

What I have tried:

before i add this second foreach loop code, i have compiled and it compiled well.
now its not working.

i think there is an error on second foreach loop.
Posted
Updated 7-Mar-17 12:26pm
v3
Comments
ZurdoDev 28-Feb-17 11:45am    
The error says "Invalid argument supplied for foreach()". So, you'll have to debug the code and verify what you are passing in.

1 solution

According to the error, the value of
$row
may be empty.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900