Jump to content

Recommended Posts

Hi everyone,

 

I just new with PHP and I need some help. I am doing a simple script where in there's a add and submit button. When I click on add button, a new row of text boxes will appear, then for submit button, it will add the entries of the text boxes on MySQL database. Below is my code;

 

----

<?php

if($_POST["addbutton"] == "ADD") {

if (isset($_POST['count'])) $count = $_POST['count'] + 1;

else $count = 1;

}

?>

<html>

<body>

<form name ="1" action="<?php $_PHP_SELF ?>" method="post">

Firstname:<input type="text" name="firstname" />

Age:<input type="text" name="age" />

<?php

// print $count rows

for ($i=1; $i<=$count; $i++) {

echo 'Firstname: <input type="text" name="firstname">';

echo 'Age: <input type="text" name="age">';

}

?>

<?php

?>

<input type="submit" name="addbutton" id="addbutton" value="ADD">

<input type="hidden" name="count" value="<?php echo $count; ?>">

</form>

<form name ="2" action="connect.php" method="post">

<input type="submit" name="submitbutton" id="submit" value="SUBMIT">

</form>

</body>

</html>

----

 

connect.php is the connection to the database. Add button is working, but submit button is not. When I hit submit, there is only 1 entry being sent. I suspect that the issue is with this code [echo '<input type="text" name="firstname"/>'; echo '<input type="text" name="age">'; ]. It seems that the name of the textbox is not being recognized. I am not really sure. Can someone please advise me?

 

Thank you in advance. [/font]

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/
Share on other sites

well all the boxes will have the same name, so they can only have one value

 

 

instead of:

<?php
for ($i=1; $i<=$count; $i++) {
echo 'Firstname: <input type="text" name="firstname">';
echo 'Age: <input type="text" name="age">';
}
?>

 

try:

<?php
for ($i=1; $i<=$count; $i++) {
echo 'Firstname: <input type="text" name="firstname'. $i. '">';
echo 'Age: <input type="text" name="age'. $i. '">';
}
?>

 

which will give them each a name that adds a number ($i) at the end, so they all have a different name.

eg:

firstname1, age1

firstname2, age2

firstname3, age3

 

however, i don't know about that second form being below the first. if it's saving a single result i guess it works but i've not seen that. i don't see how it can send ANY data as it only has the submit button as it's input...

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314565
Share on other sites

Hey digibucc Thanks. However, still not working. :((( With your code, there's no data sent to the database while with the code before, only the entries on the first row of textboxes are being sent. Any idea?

 

Umm, might be the code on my db connection will help.

 

---

$sql="INSERT INTO Persons (FirstName, Age)

VALUES

('$_POST[firstname]','$_POST[age]')";

---

 

:)))))

 

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314569
Share on other sites

yeah that would be why.

 

you're going to need something like this

<?php
$sql = "INSERT INTO Persons (FirstName,Age) VALUES($_POST['FirstName1'],$_POST['Age1']),($_POST['FirstName2'],$_POST['Age2']),($_POST['FirstName3'],$_POST['Age3'])";
?>

 

your statement was only inserting one row, this inserts multiple by means of a VALUES statement:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

otherwise you would need to do multiple insert statements.

 

you can build a foreach on your _POST to have it build your sql query, that way it's not trying to insert values that don't exist, and it accounts for all values the user created.

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314573
Share on other sites

but im thinking that if I have the same name of the textboxes, it will be okay? since what i should have is any user can add rows, depending on them how many will they add. What you advised i think will work but what if they exceeded? it would be the same thing.

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314576
Share on other sites

post will just send the last box's info with the name. they NEED to have different names in order to be saved as individual values, otherwise you just have multiple input boxes each over-writing the one before it.

 

that is one reason why it was only saving one entry before, the other being your INSERT statement. both need to reflect multiple names or it won't work.

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314579
Share on other sites

you could do something this for your sql statement, freehand so check it:

 

<?php
$sets = count($_POST) / 2;
$x = 0;
$sql = "INSERT INTO Persons (FirstName,Age) VALUES";
while ($sets > 0){
$sql .= '('. $_POST['FirstName'. $x]. ','. '('. $_POST['Age'. $x]. '),';
$sets --;
$x++;
}
$sql= substr($sql,0,-1); // trim trailing ","
?>

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314584
Share on other sites

I would use a little javascript to make it user friendly, and then treat the inputs as arrays.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') { //if form was submitted through post
foreach($_POST['firstname'] as $i => $name) { //cycle the data, both the name and age are arrays, so treat them as such.
	echo (empty($name) ? 'undefined' : $name) . ' is ' . (empty($_POST['age'][$i]) ? 0 : $_POST['age'][$i]) . '<br />';
}
}
?>
<html>
<head>
<script type="text/javascript"> <?php //lets use a little javascript to make it more usable. ?>
	function addInput() {
		var input = document.createElement('div');			
		input.innerHTML = 'Firstname: <input type="text" name="firstname[]"> Age: <input type="text" name="age[]">';
		document.getElementById('div1').appendChild(input);
	}			
</script>
</head>
<body>
<form id="form1" name ="1" action="" method="post">
<div id="div1">
<div id="element1">
	Firstname:<input type="text" name="firstname[]" />
	Age:<input type="text" name="age[]" /><br />
</div>
</div>
<a href="javascript:void(0)" onclick="addInput();">Add Another User</a><br />
<input type="submit" name="submitbutton" id="submit" value="SUBMIT">
</form>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314688
Share on other sites

To keep it in line with the rest of the replies, my script would change:

<?php
$sql = "INSERT INTO Persons (FirstName,Age) VALUES($_POST['FirstName1'],$_POST['Age1']),($_POST['FirstName2'],$_POST['Age2']),($_POST['FirstName3'],$_POST['Age3'])";
?>

 

To:

if($_SERVER['REQUEST_METHOD'] == 'POST') { //if form was submitted through post
foreach($_POST['firstname'] as $i => $name) { //cycle the data, both the name and age are arrays, so treat them as such.
	if(!empty($name)) {                  
                  $query[] = sprintf("('%s','%d')",mysql_real_escape_string($name),(int)$_POST['age'][$i]);
                }
}
if(!empty($query)) {
   $sql = 'INSERT INTO table (firstname,age) VALUES ' . implode(' , ', $query);
}
}

 

edit: typo

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314695
Share on other sites

jcbones if i could ask, how does that compare to this:

 

<?php
$sets = count($_POST) / 2;
$x = 0;
$sql = "INSERT INTO Persons (FirstName,Age) VALUES";
while ($sets > 0){
$sql .= '('. $_POST['FirstName'. $x]. ','. '('. $_POST['Age'. $x]. '),';
$sets --;
$x++;
}
$sql= substr($sql,0,-1); // trim trailing ","
?>

 

i know mine's messy and your's is cleaner, but that's why i'm asking. i am looking for a better understanding of your code vs mine. functionally how different are they? is mine a bad solution or is yours just a better one? thank you :)

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314747
Share on other sites

Yours just takes a few more steps to complete.  Nothing really wrong with doing it that way (in the coding department), it is just more coding.  The good thing about PHP is that there is no ONE definitive way to do anything.  For instance, I only use while loops for results returned by a function, otherwise if I need to go through an array, I use a for loop.

 

Now saying that, when posting code snippets on here, you must realize that a lot of the people that come here for help have no idea about sanitation and validation.  So always include that in your snippets.  Your code doesn't have any of that shown.  You must always escape string data in SQL, as well as make sure that data is of the proper type that you expect.

 

Bad solution?  No, just different.

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314828
Share on other sites

Yours just takes a few more steps to complete.  Nothing really wrong with doing it that way (in the coding department), it is just more coding.  The good thing about PHP is that there is no ONE definitive way to do anything.  For instance, I only use while loops for results returned by a function, otherwise if I need to go through an array, I use a for loop.

 

Now saying that, when posting code snippets on here, you must realize that a lot of the people that come here for help have no idea about sanitation and validation.  So always include that in your snippets.  Your code doesn't have any of that shown.  You must always escape string data in SQL, as well as make sure that data is of the proper type that you expect.

 

Bad solution?  No, just different.

 

thank you :) I am trying to improve my own skills and i find helping people is a great way to do that - however i don't want to give bad info. thanks again :)

Link to comment
https://forums.phpfreaks.com/topic/256417-php-code-help/#findComment-1314881
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.