Jump to content

[SOLVED] While Loop form submit


iceblox

Recommended Posts

Hi All,

 

I have a form which contains multiple rows and i want them all to be inserted into the db with one submit button, as long as the input box isn't zero

 

From what i have understood i need to do a while loop to insert multiple rows of the form.

 

From lots of reading im lost as to how i can get while loop to work in my script.

 

This is my code so far

 

                $result = $db->sql_query("INSERT INTO errordata (error_text, correct_id, MerchantID, type) VALUES
				('".forSql($_POST["error_text"])."', '".forSql($_POST["correct_id"])."', '".forSql($_POST["MerchantID"])."', 'Gift')");

 

Any help would be greatly appreciated.

 

Thanks, Phil

Link to comment
Share on other sites

Those two lines really don't give us enough context to work with so I'll post a simple example instead.

 

Say you have an array, and you want to insert all its content into a new record in your database. For this, you need a loop.

 

<?php

$a = array('foo','boo','bar');

foreach ($a as $v) {
    $sql = "INSERT INTO users (name) VALUES ('$v');";
    mysql_query($sql);
}

?>

 

Hope this helps some otherwise, post some more code.

Link to comment
Share on other sites

Hi Thorpe,

 

Thanks for your input, sorry for not including enough code i have included the form as well hopefully this is enough information?

 


if(!empty($_POST["addbutton"]))
{
                $result = $db->sql_query("INSERT INTO errordata (error_text, correct_id, MerchantID, type) VALUES
				('".forSql($_POST["error_text"])."', '".forSql($_POST["correct_id"])."', '".forSql($_POST["MerchantID"])."', 'Gift')");
            if($result)
		$status = "<fieldset><legend>Message</legend><b>Inserted correctly!</b></fieldset><br>";
	else
	{
		print_r($db->sql_error($result));
		$status = "<b>Error could not add errors<br>. " . var_dump($db->sql_error($result),true);
	}
}


        echo "<input type=\"hidden\" value=\"$row[4]\" name=\"error_text\" /><input type=\"hidden\" value=\"$aff\" name=\"MerchantID\" />";
        echo "<form action=\"$url/admin/?op=gifterrorfixing&aff=$aff\" method=\"post\">";
        echo '<tr bgcolor="' . $bgcolor . '">';
	echo '<td><a title=' . $row[0] . '>' . $row[4] . '</a></td>';
    echo "<td><input type=\"text\" size=\"10\" name=\"correct_id\" /></td>";
	echo "<td><a target=\"_blank\"href=\"$row[5]\">Link</a></td>";
        echo '</tr>';
$rowcounter++;
}
echo "</table><center><input type=\"submit\" name=\"addbutton\" value=\"Finished?\" size=\"20\" /></center></form></fieldset>";
}

 

Thanks for your help,

 

Phil

Link to comment
Share on other sites

This is what i have been able to do so far but obviously this does not work. Is someone able to tell me what im doing wrong?

 

foreach ($_POST["MerchantID"] as $line)
{
                $result = $db->sql_query("INSERT INTO errordata (error_text, correct_id, MerchantID, type) VALUES
				('".forSql($_POST["error_text"])."', '".forSql($_POST["correct_id"])."', '".forSql($_POST["MerchantID"])."', 'Gift')");
}

 

Thanks,

 

Phil

Link to comment
Share on other sites

this is a case where you don't need multiple queries when one will do.

 

I don't like to see queries being run inside loops - better to just build your query in the loop and execute afterwards...

 

try this

 

<?php
$queries = array();
foreach ($_POST["MerchantID"] as $line => $val)
{
                $queries[] = "('".forSql($_POST["error_text"])."', '".forSql($_POST["correct_id"])."', '".forSql($val)."', 'Gift')");
}

$qry = "INSERT INTO errordata (error_text, correct_id, MerchantID, type) VALUES " . implode(',',$queries);

$result = $db->sql_query($qry);

?>

 

you may need to amend something for the forSql to work if its out of scope but otherwise thats a more efficient query.  This depends of course on the merchantid is an array passed from the form (you need to give the html input fields name="merchantid[]")

Link to comment
Share on other sites

Thanks for your input ToonMariner,

 

I have put it into the script and changed the name of MerchantID in the form.

 

I didnt get any errors however it doesnt seemed to have worked correctly,

 

It posted 6 lines of data on this particular test, rather than the 7 there are in the form and the data is that of the last input on the form. So it posted the last row 6 times?

 

Any ideas?

 

Thanks again,

Phil

Link to comment
Share on other sites

This is the code that includes the stuff for the online form aswell.

 

Is this all you need to see?

 

	if(!empty($_POST["addbutton"]))
{
                $result = $db->sql_query("INSERT INTO errordata (error_text, correct_id, MerchantID, type) VALUES
				('".forSql($_POST["error_text"])."', '".forSql($_POST["correct_id"])."', '".forSql($_POST["MerchantID"])."', 'Gift')");
            if($result)
		$status = "<fieldset><legend>Message</legend><b>Inserted correctly!</b></fieldset><br>";
	else
	{
		print_r($db->sql_error($result));
		$status = "<b>Error could not add errors<br>. " . var_dump($db->sql_error($result),true);
	}
}


        echo "<input type=\"hidden\" value=\"$row[4]\" name=\"error_text\" /><input type=\"hidden\" value=\"$aff\" name=\"MerchantID\" />";
        echo "<form action=\"$url/admin/?op=gifterrorfixing&aff=$aff\" method=\"post\">";
        echo '<tr bgcolor="' . $bgcolor . '">';
	echo '<td><a title=' . $row[0] . '>' . $row[4] . '</a></td>';
    echo "<td><input type=\"text\" size=\"10\" name=\"correct_id\" /></td>";
	echo "<td><a target=\"_blank\"href=\"$row[5]\">Link</a></td>";
        echo '</tr>';
$rowcounter++;
}

 

Thanks again,

Phil

Link to comment
Share on other sites

<input type=\"hidden\" value=\"$aff\" name=\"MerchantID\"

 

this line means that you overwrite the previous merchant id in the the post header.

 

you need an array of merchant ids

 

<input type=\"hidden\" value=\"$aff\" name=\"MerchantID[]\"

 

I hope you missed some code off that as I can't see your loop...

Link to comment
Share on other sites

i don't know - should you have a loop in your code? if you are exploring an array I'd suggest you do (in your current set up).  Maybe there are some cross wires here...

 

what ever it is you are doing put print_r($_POST) at the top of your script and you can see what data ou are playing with.

Link to comment
Share on other sites

Hi ToonMariner,

 

Thanks for your continued help with this.

 

So i thought about it and MerchantID isnt unique it's always the same so i think that could have been one of issues. I changed this to error_text and that is working to an extent.

 

The error_text being is posted as it should, correct_id is being put in the database as the same number over and over and it is not posting the first entry in the form. If there is only one line on the form then the is always an error.

 

I added to the code you suggested and got this;

 

Array ( [correct_id] => 64 [error_text] => Array ( [0] => 11 Months £3.99 by redemption [1] => 1 Month FREE by redemption [2] => 1 Month £0.99 by redemption ) [MerchantID] => e2save [addbutton] => Finished?

 

Not too sure what that all means.

 

Thanks again, Phil

Link to comment
Share on other sites

Ok so i have a form on my site with mutliple lines, each line i would like inserterted into the database that way. But if the correct_id is empty then i dont want that row inserted.

 

The form looks like this - see "form.bmp"

 

MerchantID and error_text are set has hidden in the form, correct_id is the input box.

 

The whole code for the page is as follows;

 

$queries = array();
foreach ($_POST["error_text"] as $line => $val)
{
                $queries[] = "('".forSql($val)."', '".forSql($_POST["correct_id"])."', '".forSql($_POST["MerchantID"])."', 'Gift')";
}

$qry = "INSERT INTO errordata (error_text, correct_id, MerchantID, type) VALUES " . implode(',',$queries);

$result = $db->sql_query($qry);

	if($result)
		$status = "<fieldset><legend>Message</legend><b>Inserted correctly!</b></fieldset><br>";
	else
	{
		print_r($db->sql_error($result));
		$status = "<b>Error could not add errors<br>. " . var_dump($db->sql_error($result),true);
	}
}

include("admin/header.php");
        echo "$status";
       print_r($_POST);
        echo '<a href="' . $url . '/admin/?op=dealshome">Mobile Deals Home</a>   > <br><br><fieldset><legend>Mobile Deals Options</legend>[ <a href="' . $url . '/admin/?op=tariffs">Tariffs</a> <a href="' . $url . '/admin/?op=gifts">Gifts</a> <a href="' . $url . '/admin/?op=models">Models</a> <a href="' . $url . '/admin/?op=merchants">Merchants</a>]</fieldset><br><fieldset>';
        
$query1 = "SELECT * FROM error WHERE `affiliate` = '$aff' LIMIT 1";

$result1 = mysql_query($query1);


if (mysql_num_rows($result1) > 0)
{

while($row = mysql_fetch_row($result1))
{

echo '<legend>Manage ' . $row[1] . ' Gifts</legend>';

}
}

$query = "SELECT * 
FROM error 
WHERE affiliate = '$aff' 
AND gift NOT IN (SELECT CONVERT(GiftID, CHAR) FROM deals_gifts) AND gift <> '0' AND gift <> '' GROUP BY gift ORDER BY gift DESC";
$result = mysql_query($query);


if (mysql_num_rows($result) > 0)
{


echo '<table width=100%>';
echo '<tr>';
echo '<td width=60%><b>Gift</b></td>';
echo '<td width=30%><b>Input</b></td>';
echo '<td width=15%><b>Link</b></td>';
echo '</tr>';

while($row = mysql_fetch_row($result))
{

if($rowcounter%2==1)
$bgcolor="#F4F4F4";
else
$bgcolor="#FFFFFF";

        echo "<input type=\"hidden\" value=\"$row[4]\" name=\"error_text[]\" /><input type=\"hidden\" value=\"$aff\" name=\"MerchantID\" />";
        echo "<form action=\"$url/admin/?op=gifterrorfixing&aff=$aff\" method=\"post\">";
        echo '<tr bgcolor="' . $bgcolor . '">';
	echo '<td><a title=' . $row[0] . '>' . $row[4] . '</a></td>';
    echo "<td><input type=\"text\" size=\"10\" name=\"correct_id\" /></td>";
	echo "<td><a target=\"_blank\"href=\"$row[5]\">Link</a></td>";
        echo "</tr>\n\n\n\n";
$rowcounter++;
}
echo "</table><center><input type=\"submit\" name=\"addbutton\" value=\"Finished?\" size=\"20\" /></center></form></fieldset>";
}
else
{
echo 'None!';
}

 

Thanks for your continued help and support, your help is appreciated!

 

Phil

 

[attachment deleted by admin]

Link to comment
Share on other sites

Sorry but your explanation isn't very clear...

 

Are you saying that if the user inputs something into the text box then that row will be inserted into the database?

 

Are there multiple merchant IDs? your description is quite poor - sorry...

Link to comment
Share on other sites

Yeah exactly, i do all the inserts as its an admin form but yeah which ever row i add a value for into the correct_id box i want that row put into the db. If i don't put a correct_id then i don't want any of that row inserted.

 

The merchantid is always the same on the whole form as the merchantid is a var in the url.

 

Sorry for my ropey explanations, hope this helps.

 

 

Link to comment
Share on other sites

yeah - the answer has already been touched on in the thread.

 

you need to make sure that you are passing values to the script are in array format; this means those fields must have [] in the name attribute name="inputname[]".  Do that for each row - check that you are getting suitable results by using print_r($_POST).

 

Once the all the data (not just the last row in your table) is present in the post array you can then start looking at processing the results.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.