Jump to content

[SOLVED] foreach loop problem


bluebyyou

Recommended Posts

So I have a form that takes a number or emails based on a users input, then if the user exists it updates the table or if the user does not exist creates a new row in the db for that user. The problem is that if the user doesnt already exist in the table the query does not work. I don't know if its the query thats not working or my loop or what.

 

<?php for($i = 1; $i <= $_POST['numtravel']; $i++) {?>
<input name="email[]" type="text" size="18" />
<?php }?><br />

 

 

	
<?php
foreach($_POST['email'] as $email ) 
{
// NEED TO ADD CHECK FOR EMAIL FORMAT HERE!!!

	$query = "SELECT * FROM member WHERE email = '$email'"; // THIS IS THE ONE NOT WORKING!!
	query_db($query);
	$num = mysql_num_rows($result);
	if ($num > 0) // User exists, Update enrollment in year.
	{
		$query2 = "UPDATE member SET `$_POST[year]` = 1 WHERE email = '$email'";
		query_db2($query2);
	}
	else
	{
		$code = mt_rand(11111,999999);
		$query3 = "INSERT INTO member(email,$year,code) VALUES('$email','1','$code')";
		query_db($query3);
	}

}
?>

Link to comment
https://forums.phpfreaks.com/topic/56870-solved-foreach-loop-problem/
Share on other sites

replace this line:

<?php
query_db($query);
?>

 

With this:

<?php
$result = query_db($query);
?>

 

I'm assuming that query_db() is a function you created.

 

The reason I told you to change the above code is because on this line of your code:

$num = mysql_num_rows($result);

 

Where did you define $result?

$result is returned from my function. I dont think thats the problem.

<?php
function query_db($query)
{
$user = "*****";
$host = "*****";
$password = "******";
$database = "******";

global $result;

$connection = mysql_connect($host,$user,$password) or die ("Couldn't connect to server.");
        $db = mysql_select_db($database,$connection) or die ("Couldn't select Intern database.");
$result = mysql_query($query) or die ("Couldn't execute query");

return $result;
}

?>[code]

[/code]

I guess what im am thinking the problem is that if the user doesnt exist the query isnt working. However I thought it should just not be returning any rows, that way when I use mysql_num_rows() on it i should get 0. Instead it is just saying "Couldn't execute query"

Why don't you try catching the error?

 

Change this line in your function:

$result = mysql_query($query) or die ("Couldn't execute query");

 

To:

$result = mysql_query($query) or die (mysql_error());

 

Then post what error it returns.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.