So I am displaying multiple html forms on a page - works great because I am just using a simple loop to display it 80 times but the issue I am facing is I would like to take all 80 forms and submit them into multiple rows in my database. It's only submitting the last form (which is 80)
If anyone can help me find the issue... I would really appreciate it! I've done some searching before submitting this question but I can't seem to find a answer.
Here is what my table looks like:
Here is my form builder
<?php
// Counts the number of forms
$counter = 1;
echo '<form action="insert.php" method="post">';
// Loop through forms
for ($i = 1; $i < 81; $i++) {
$username = 'admin';
$title = 'test';
$name = 'a';
$image_src = '<img src="image/'.$i.'.jpg">';
$transition = 'fade';
$group_name = '0';
echo '<hr>' . '('. $counter .')'. '<br>';
echo "
<label>Username:</label>
<input type='text' name='username' id=' required='required' value='".$username."'/>
<br /><br />
<label>Title:</label>
<input type='text' name='title' id=' required='required' value='".$title."'/>
<br/><br />
<label>Name:</label>
<input type='text' name='name' id=' required='required' value='".$name."'/>
<br/><br />
<label>Content:</label>
<input type='text' name='content' id=' required='required' value='".$image_src."'/>
<br/><br />
<label>Image:</label>
<input type='text' name='image' id=' required='required' value='images/".$i.".jpg'/>
<br/><br />
<label>CSS Animate:</label>
<input type='text' name='cssanimate' id=' required='required' value='".$transition."'/>
<br/><br />
<label>Group Name:</label>
<input type='text' name='group_name' id=' value='0'/>
<br/><br />
";
$counter++;
}
echo '<input type="submit" value="Submit" name="submit"/>';
echo '</form>';
?>
Here is my php code: (insert.php)
<?php
$con=mysqli_connect("localhost","admin","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO table_name (username, title, name, content, image, cssanimate, group_name, group_sort) VALUES ('".$_POST["username"]."', '".$_POST["title"]."', '".$_POST["name"]."', '".$_POST["content"]."', '".$_POST["image"]."', '".$_POST["cssanimate"]."', '".$_POST["group_name"]."', '".$_POST["group_sort"]."') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
} echo "Added!";
mysqli_close($con);
?>
If you have 80 elements with this name:
name='username'
Then how will this code know which one to use?:
$_POST['username']
Essentially, as your browser builds the form submission, each successive element of the same name over-writes the previous one. So you end up with only the last record.
Instead, give them an array-style name:
name='username[]'
(Repeat for all your duplicated form elements.)
Then in the PHP code, this would itself be an array:
$_POST['username']
You could loop over that array:
for ($i = 0; $i < count($_POST['username']); $i++) {
$username = $_POST['username'][$i];
$title = $_POST['title'][$i];
// etc.
}
This assumes that all of your arrays will be the same length. Which, given this HTML, I suppose they should be. But you can add error checking for that just in case. Either way, each iteration of the loop would build variables equating to that "record" which was submitted.
From there you should be able to build your SQL query with those variables. However, please note that your current way of doing that is extremely unsafe and wide open to SQL injection. To correct that, this is a good place to start.
Side note: Your HTML has invalid id attributes. Additionally, if you want to specify id attributes in that loop, you're going to need to ensure that they are somehow different. Duplicated ids in HTML is invalid.
Related
I have an array that is created from a mysqli query.
The array then goes through a for loop to display a table.
Within the table there is a form submit that needs to take the selected row and pass the information into a variable to be modified.
I tried to take a screenshot, but I just joined and have no rep. In theory, the user needs to be able to select Modify and the array elements for that row need to pass into text input boxes with a preset value of $row[$j][0] where $j is fixed based on the row selected to modify.
Here is what this part of the code looks like.
if (isset($_POST['Select']) &&
isset($_POST['Search']))
{
$Select = get_post($con,'Select');
$Search = get_post($con,'Search');
if ($Select == "Invalid")
{
echo "<br /><br />Please select a search catagory";
}
else if ($Search == NULL)
echo "<br /><br />Please enter search field";
else
{
$query = "SELECT * FROM table WHERE $Select LIKE '$Search%'";
$result = mysqli_query($con,$query);
if (!mysqli_query($con,$query)) {
die('Error: ' . mysqli_error($con));
}
$rows = mysqli_num_rows($result);
echo "<table id='myTable' class='tablesorter'>
<thead><tr>
<th>Modify</th>
<th>Field1</th>
<th>Field2</th>
<th>etc...</th>
</tr></thead><tbody>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
$modrow[$j] = $row;
echo <<<_END
<tr>
<td><form action="Lookup.php" method="post"><input type="submit" value="Modify" /><input type="hidden" name="submitted" value="$modrow[$j]"</form></td>
<td>$row[0]</td>
<td>$row[1]</td>
<td>etc...</td>
</tr><br />
_END;
}
echo "</tbody></table>";
if (isset($_POST['submitted']))
{
echo <<<_END
<form action="Lookup.php" method="post"><pre>
Field1 <input type="text" name="Field1" size="50" **value="$modrow[$j][0]"** />
...more of the same...
From what I gather, you're wanting to pass a request to the server containing some form of identifier for the row so that you may create a form for users to modify that row's data. Sorry if I misunderstood - I would ask first if I understood you correctly as a comment, but don't have enough rep.
You can use an id to submit to the server.
<button type="submit" name="modify" value="<?= $theRowsId ?>">Modify</button>
Think of the values of name and value attributes as a function/method and value being passed respectively.
Now when Modify is clicked, you can get retrieve the ID, perform a query for the ID and populate the input with the rows data.
$rowId = $_POST['modify'];
New to PHP and reading through Robin Nixon's PHP, MySQL, Javascript book. I am having trouble with an example of inserting and deleting data using a PHP script, specifically with how the author uses $_POST.
The example is a pretty simple add records/delete records of books with multiple inputs. Here's the code:
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category = get_post('category');
$year = get_post('year');
$isbn = get_post('isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
When you refer to an element in $_POST with if (isset($_POST['delete']) && isset($_POST['isbn'])), where delete and isbn are used as names multiple times, how does $_POST know which element to reference to delete? I assume that since you can only delete one record at a time, the element in the array will automatically point to the one that's already set. However, how does the second condition of isset($_POST['isbn']) know which "isbn" element to check for? Does the && make the $_POST['isbn'] "inherit" the correct row?
Thanks for the help! And apologies for any possible misuse of the vocab. Still getting used to everything.
Your question is actually well thought out. And the example given in the book seems quite sloppy to me. I am assuming in later chapters he will delve into the use of arrays in $_POST values. But anyway, here is the key to the functionality of the whole script:
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
See that <form action="sqltest.php" method="post">? And see that closing </form>? And note that they are being rendered each time the for ($j = 0 ; $j < $rows ; ++$j) loop happens? There is one individual form element for each line. That is messy code, but it works. When one clicks submit on each individual listing, the wrapping form responds & parses the variables nested inside it.
Like I said, sloppy code. But works. And it’s because if you have 30 ISBNs listed this program will spit out 30 individually wrapped <form> items. Uggh! Seriously if the book does not address arrays later on in a way that addresses this face-palm of a coding mess find a new book.
Since there are multiple forms, the input elements of only one form are submitted.
So basically, sqltest.php receives only one array of $_POST containing ['delete'] and ['isbn'] with the corresponding values only once.
You can check this out by using print_r($_POST) in sqltest.php.
Can anyone let me know how to assign different names for each textbox in loop in php for the following code..
while($data=mysql_fetch_array( $sql )){
print "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td><td> <input type=text name=obtmarks</td></tr>";
}
You can use a counter nice and simple:
$i=0;
while($data=mysql_fetch_array( $sql ))
{
echo "<tr><td>".$data['idno']." </td>
<td>".$data['name'] . " </td>
<td> <input type='text' name='obtmarks_".$i."'></td></tr>";
$i++;
}
Note: I also corrected your open/close brackets and put quotes where they needed to go inside the elements.
$i = 0;
while($data=mysql_fetch_array( $sql ))
{
Print "<tr><td>{$data['idno']}</td><td>{$data['name']}</td><td> <input type=\"text\" name=\"obtmarks{$i++}\"/></td></tr>";
}
Keep your code clean and readable. Make proper use of "",{} and ''.
Edit:
while($data=mysql_fetch_array( $sql ))
{
Print "<tr><td>{$data['idno']}</td><td>{$data['name']}</td><td> <input type=\"text\" name=\"obtmarks[]\"/><input type=\"hidden\" name=\"obtmarks_id[]\" value=\"{$data['idno']}\"/></td></tr>";
}
And then on second page you will have 2 arrays waiting in $_POST, obtmarks[] containing user input and obtmarks_id[] containing corresponding ID's
$obtmarks = $_POST['obtmarks[]'];
$obtmarks_id = $_POST['obtmarks_id[]'];
foreach($obtmarks as $k => $v) {
// PSEUDO SQL: INSERT $v .... WHERE id=$obtmarks_id[$k]
}
The easiest way to do this is to create form elements that are in an array.
This is documented at php.net.
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Thus, you could perhaps use:
$fmt = "<tr><td>%s</td><td>%s</td><td>input type='text' name='obtmarks[]'></td></tr>\n";
?><table><tr><th>ID</td><th>Name</th></tr><?php
while ( $data=mysql_fetch_array( $sql ) ) {
printf($fmt, $data['idno'], $data['name']);
}
?></table>
If it doesn't matter what the name is, you can do something as simple as this:
$counter = 0;
while($data=mysql_fetch_array( $sql ))
{
print "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td><td> <input type='text' name='obtmarks{$counter}' /></td></tr>";
$counter += 1;
}
<input type=text name=" .$variable." /></td></tr>" $variable could come from the mysql TABLE, field having different values or you may use a counter as the answers below.
Sorry, newbie question I know, however I've currently got mySQL results only showing when using the echo command through PHP etc..
Now, I am able to source the information fine, however I would like the result of a query to show up in a form e.g.
Rather than :-
$loggedinuser = $session->username;
//$query = "SELECT surname, firstname FROM PASSENGER WHERE username = '$jared'";
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
echo $row['surname'] ." ". $row['destination'];
}
echo mysql_error();
I would like to print the SQL result in a HTML form...e.g. one that follows the convention of:-
Surname: <input type="text" name="firstname" value="echo $row['surname']/>
If you see where I am coming from. Is this really bad practice using forms to display mySQL results, or can it be done? If not really, what ways would you recommend I print the data? In a table of some sort, but how can I then use fields?
Regards,
Tom.
Something like this work:-
<?php
$loggedinuser = $session->username;
//$query = "SELECT surname, firstname FROM PASSENGER WHERE username = '$jared'";
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
"<form>"
<input type="text" name="firstname" value="<?php echo {$row['surname']} ?>" disabled />
"</form>"
}
echo mysql_error();
?>
How can a new line be added between echo's in the following code please?
echo ' Surname: <input type="text" name="surname" value="'.$row['surname']. "\" disabled /> ";
echo 'Forename: <input type="text" name="surname" value="'.$row['forename']. "\" disabled />";
echo 'Email Address: <input type="text" name="surname" value="'.$row['emailAddress']. "\" disabled />";
echo 'Preference ID: <input type="text" name="surname" value="'.$row['dob']. "\" disabled />";
echo 'Seat Number: <input type="text" name="surname" value="'.$row['seatNo']. "\" disabled />";
echo 'Group ID: <input type="text" name="surname" value="'.$row['groupID']. "\" disabled />";
<input value="<?php echo $row["firstname"]; ?>">
<input type="text" name="firstname" value="<?php print($row['surname']); ?>"/>
or
<input type="text" name="firstname" value="<?=$row['surname']?>"/>
Using anything to display the information is good, until you are not allowing the users to be able to change those values. You can also display using tables/divs or anything else you can think of. Forms are a very good method too(imo). Also, you can use a disabled property, to not to allow anyone to change those values you put in your Form's input boxes.
<input type="text" name="firstname" value="<?php echo {$row['surname']} ?>" disabled />
EDIT Putting up the while loop here:
while($row = mysql_fetch_array($result)) {
echo "Surname: <input type=\"text\" name=\"firstname\" value=\"" . {$row['surname']} . "\" disabled />"
}
If you are merely needing to display data in a read-only fashion, you don't really want to "show the query", you want to print the results of said query in a readable fashion. I'm sure there are certain instances where you would need to print SQL to the users, but those situations are probably rather slim. As others have said, it is also extremely poor practice to allow the user to submit any type of SQL and use it - the mantra is that any user input should always be considered malicious user input - you must validate and sanitize everything before you send it to your database.
This being said, it looks like you just want to show a form with results from your query, which you were incredibly close on. The only issue you may have is if your query returns 2 or more rows, in order to get PHP to automatically bind the submitted values to an array, you'll have to sequentially name them so they show up as: firstname[0] , firstname[1] and so on. Just start an int that you can increment through each time:
$loggedinuser = $session->username;
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
$i = 0;
while($row = mysql_fetch_array($result)) {
$surname = $row['surname'];
$destination = $row['destination'];
echo '<input type="text" name="firstname[$i]" value="$surname" />';
echo '<input type="text" name="destination[$i]" value="$destination" />';
$i++;
}
Let's say you had two rows show up in your query, here's what would result (with added formatting):
<input type="text" name="firstname[0]" value="Bill" />
<input type="text" name="destination[0]" value="Rococo" />
<input type="text" name="firstname[1]" value="Mandy" />
<input type="text" name="destination[1]" value="Philadelphia" />
EDIT: To add newlines to the HTML being outputted, just add a <br /> tag for each newline:
echo '<input type="text" name="firstname[$i]" value="$surname" /><br />';
$query2 = "SELECT p.surname, f.destination FROM PASSENGER p, FLIGHT_INFO f WHERE p.username = '$loggedinuser' AND p.flightNo = f.flightNo";
$result = mysql_query($query2);
while($row = mysql_fetch_array($result))
{
echo '<form>';
echo ' Surname: <input type="text" name="surname" value="'.$row['surname'].'/><br/>';
echo ' Below is my Destination<br/>';
echo ' Destination: <input type="text" name="surname" value="'.$row['destination '].'/>';
echo '</form>';
}
Try this
I am trying to update multiple rows here.However I fail to point the right ID of the row.
<?php
$table = 'DynamicPage';
$query = mysql_query(Query::SelectAllFrom($table));
// Count table rows
$count = mysql_num_rows($query);
while ($row = mysql_fetch_array($query)) {
$id[] = $row['ID'];
echo '
<h3>Column name: </h3><input type="text" name="name" maxlength="30" value="' . $row['Name'] . '" />
<h3>Tekst: </h3><textarea type="text" name="fulltext[]" maxlength="2000">' . $row['FullText'] . '</textarea>';
}
echo '<input name="Submit" type="submit" value="Submit" />
</form>';
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
for ($i = 0; $i < $count; $i++) {
$queryUP = mysql_query("UPDATE $table SET Name='" . $_POST['name'] . "' WHERE id='??????????????'");
$result = mysql_query($queryUP);
}
if ($result) {
header("location:index.php");
}
}
?>
So far I can update the first row (if id='1') from the last <h3>Column name: </h3><input type="text" name="name"... I know that I am not passing the ID's in the right way, but I have to idea about the syntax. If anyone has an idea, please let me know :)
Thanks
Perhaps you should add a hidden input field with IDs:
HTML part
<input type="hidden" name="id[]" value="'.$row['ID'].'" />
<h3>Column name: </h3><input type="text" name="name[]" maxlength="30" value="'.$row['Name'].'" />
<h3>Tekst: </h3><textarea name="fulltext[]" maxlength="2000">'.$row['FullText'].'</textarea>';
PHP
for($i=0; $i<count($_POST['ID']); ++$i){
//query goes here
}
SQL QUERY
UPDATE $table SET Name='{$_POST['name'][$i]}', Tekst='{$_POST['fulltext'][$i]}' WHERE id='{$_POST['id'][$i]}'
This is from top off my head, not tested, but should give you an idea.
And of course, escape all the input fields.
Try this after your $_POST['Submit'] isset test:
for($i=0;$i<sizeof($id);$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id = " . $id[$i]);
$result = mysql_query($queryUP);
}
input type="text" ids="id[]" maxlength="30" value="'.$row['id'].'"
//then submit part
for($i=0; $i<count($_POST['id'];$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id='$_POST['id'][$i]'");
$result = mysql_query($queryUP);
}
You may concatenate $row['ID'] and $row['Name'] to create a name you can parse later
<h3>Column name: </h3><input type="text" name="name" maxlength="30"
value="' . $row['ID'] . '_' . $row['Name'] . '" />
then you can use something like:
list($name, $id) = explode($_POST['name'], '_');
** also note you have a security risk using user input directly inside SQL statement