insert values to database after looping through a form - php

Briefly, my script includes form ask how many images to enter ,,the entered value will be in a while loop that will display a form with inputs equally to image value entered . okey , I made the submit button outside the loop ,I want now to add them to database ,,I used again a while loop with the query as I did in the form ,,but it only inserts the last item ..What could the problem be ? This is part of the script :
if (isset($_POST["chooseimagen"])) {
$i=0;
$imgvl = $_POST["imgvl"];
$cid = $_POST["cid"];
while($i<$imgvl){
echo '<form name="finalform" method="post" action="">
id of content :<input type="text" name="idcontent" value="'.$cid.'"/><br><br>
Enter id of image :<input type="text" name="imgid" value=""/><br><br>
Enter name of image : <input type="text" name="imgname" value=""/><br><br>
-----------------------------------------------------------------------<br>
';
$i++;
}
echo "<br><br><input type='hidden' name='imgvl' value='".$imgvl."'/><input type='submit' name='addto' value='insert images'/></form";
}
?>
<?php
if(isset($_POST["addto"])){
$imgvl = $_POST["imgvl"];
$i=0;
while ($i < $imgvl){
$idcontent = $_POST["idcontent"];
$imgid = $_POST["imgid"];
$imgname = $_POST["imgname"];
$queryin = "insert into content_images values ('$imgid','$idcontent','$imgname','ok')";
mysqli_query($con,$queryin);
$i++;
}
}
?>

Still new to development, but I think I know..
A few things, you are creating a new form with every loop, but only closing it once. Also you are missing a >, so technically you are not closing the forms at all.
while($i<$imgvl){
echo '<form name="finalform" method="post" action="">
...
$i++;
}
echo "<br><br><input type='hidden' name='imgvl' value='".$imgvl."'/>
<inputtype='submit' name='addto' value='insert images'/></form";
But I think the reason you are getting this problem is each form you create has the same names for the inputs. That's why you are only getting the last item, because every item you are inserting is just the last input set.
Because you have no action on the form, every form is essentially combined. This means there is no way to distinguish which input name you are reffering to and therefore it takes the last value that was assigned.
Hope this helps

Related

Process PHP form on hidden page, but stay on same page. No Ajax, pure php only (project)

I'm new to PHP, and I'm sure this is a common think to do, but 99% of the answers I have found to this involve AJAX, JQuery and/or JavaScript.
I am only allowed to use HTML/CSS and PHP in my project, so I need a working option that does not involve anything else.
I have the following setup:
index.php, this holds my form structure
insert.php, this sanitizes/validates and inserts form data into a database table
Leaving action as insert.php sends me to my insert.php page, which I want to keep private and for developer eyes only...no good.
form action=" " method="post"
// OR
form action="index.php" method="post">
Leaving action blank or as index.php keeps me on the same page, but...
I want to keep my form processing in a separate file (insert.php) and NOT on the same page, if at all possible.
Do I have any options for this that are not excessively complex in pure PHP?
Thanks for any advice.
(PS. If there's any blatant errors or poor form here, I'm all ears to constructive criticism)
Here's a snapshot of my insert.php file if its helpful. I can upload my form as well, but its very basic (just select a course, input first/last name, input student id).
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
Something like this might be what you want:
<?php
if (!empty($_POST)) {
require "insert.php";
}
?>
<html><head></head><body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
</body></html>
It's possible to submit the page to itself and check if the $_POST is empty or not. If it's empty show the form of the page if not insert the data into the database.
<?php if (!empty($_POST)):
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
<?php endif; ?>

Prevent form reset after submit php

I have a dynamically populated table. Up on form submit I would like to keep the new values in the textfield of the form. After a search on Stack Overflow I found this
<form name="test" method="post">
Your Name: <input type="text" name="YourName" <?php if (isset($_POST['YourName'])) echo 'value="'.$_POST['YourName'].'"';?> >
I tried to adapt in to my form but was unable to do so. The textfield is still reset after button is clicked.
echo "<td width=40%><input type=text value='$location'";
if (isset($_POST['$dynamic_location'])) echo "value=".$_POST['$dynamic_location'];
echo "name='$dynamic_location'></td>\n";
For the new values to keep up in the fields you how to add another query to fetch the data from the database and echo it in its individual fields.
And remember to fetch only the fields needed that will increase your execution time.
If action="" or not set at all, following should work
if (isset($_POST['$dynamic_location'])) echo "value=".$_POST['$dynamic_location'];
echo "name='$dynamic_location'/>";
If action="another_file.php" , you can do this
In another_file.php
header("location:previous_page.php?dynamic_location=".$_POST['$dynamic_location']);
On current file or previous_page.php
if (isset($_GET['dynamic_location'])) echo "value=".$_GET['dynamic_location'];
echo "name='$dynamic_location'/>";

Inputting multiple values in database from HTML form using PHP

I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?

PHP multiple variables in a form

I'm trying to ask a user how many guests. Once the user has entered a number then a number of fields should appear where the user can then add guest1, guest2 etc. However every time I try and create a for loop it doesn't seem to be working. This is the current source code for entering the number of guests.
<? echo "<input type='text' name='guestnumber' size='6' value='$guestnumber'>" ?>
What I would like to happen is that the name of the textfields would be guest1, guest2 etc based on the number of guests they have entered. I'm sure it's a pretty simple for loop that needs to be done but I'm not sure how to do it.
Here is a basic example. Submitting the form does not reset the fields.
You can either store all values in separate variables such as $guest1, $guest2, etc, but an array is much easier to use when handling the $_POST data.
Before touching any of the variables we check if the variable is set with isset to prevent errors.
<?php
// Set up the number of guests
if(isset($_POST['guestnumber'])) {
$numGuests = (int)$_POST['guestnumber'];
if ($numGuests < 1) {
$numGuests = 1;
}
}
if (isset($_POST['guests'])) {
// Handle guest data
}
?>
<form method="POST" action="">
<input type="text" name="guestnumber" size="6" value="<?php
// Retain field value between refreshes
if(isset($numGuests)) echo $numGuests; ?>"><br>
<?php
// Echo out required number of fields
if (isset($numGuests)) {
for ($i = 0; $i < $numGuests; $i++) {
// Store field information in a 'guests' array
echo "<input type='text' name='guests[]' value='";
// Retain the guest names between refreshes
if (isset($_POST['guests'])) {
echo $_POST['guests'][$i];
}
echo "'><br>";
}
}
?>
<input type="submit" value="Submit">
</form>

Two forms with multiple submit buttons in single PHP file

I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.

Categories