I apologize if this is asked already, but I want to take user input in html form and insert it into table using session (without any usage of database) in format given in image attatched. [1]: https://i.stack.imgur.com/W10Ry.png
I tried code below to insert form data into table using php sessions.
<?php
session_start();
if (isset($_SESSION['fname'])) {
$fname = $_SESSION['fname'];
$lname = $_SESSION['lname'];
$username = $_SESSION['username'];
$pswd = $_SESSION['pswd'];
$country = $_SESSION['country'];
$phone = $_SESSION['phone'];
$email = $_SESSION['email'];
$dob = $_SESSION['dob'];
}
else {
$fname = [];
$lname = [];
$username = [];
$pswd = [];
$country = [];
$phone = [];
$email = [];
$dob = [];
}
if (isset($_POST['fname'])) {
$fname[] = $_POST['fname'];
$lname[] = $_POST['lname'];
$username[] = $_POST['username'];
$pswd[] = $_POST['pswd'];
$country[] = $_POST['country'];
$phone[] = $_POST['phone'];
$email[] = $_POST['email'];
$dob[] = $_POST['dob'];
}
$_SESSION['fname'] = $fname;
$_SESSION['lname'] = $lname;
$_SESSION['username'] = $username;
$_SESSION['pswd'] = $pswd;
$_SESSION['country'] = $country;
$_SESSION['phone'] = $phone;
$_SESSION['email'] = $email;
$_SESSION['dob'] = $dob;
?>
<table id="mytable">
<thead>
<th scope="col">#</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Username</th>
<th scope="col">Password</th>
<th scope="col">Country</th>
<th scope="col">Phone</th>
<th scope="col">Email</th>
<th scope="col">DOB</th>
<th scope="col">Delete</th>
</thead>
<tbody>
<?php
$count = 0;
foreach($fname as $key=>$value){
$count ;
// print "<br> $count: $name[$key], $email[$key]";
echo "<tr><td>$count</td><td>$fname[$key]</td><td>$lname[$key]</td><td>$username[$key]</td>
<td>$pswd[$key]</td><td>$country[$key]</td><td>$phone[$key]</td><td>$email[$key]</td>
<td>$dob[$key]</td><td><button class = 'btn btn-danger' onclick = 'deler()'>del</button></td></tr>";
}
?>
</tbody>
</table>
But I can't really figure out a way to click the delete button and delete that particular row from table as well as corresponding data from session array as well.
CodePudding user response:
There are at least two issues here.
One
To use the POST, you have to have a form that posts, put this around the table.
<form method='post'>
...
</form>
Two
Each button should have a unique name, this name is what you use to figure out which row is being deleted. Each button will have the name btn- followed by the key, such as btn-12. This what you use back on the server in PHP to determine the row.
<td>$dob[$key]</td><td><button class = 'btn btn-danger' type='submit'
name='btn-$key'>del</button></td></tr>";
Three
I am not sure what onclick event is for, there appears to be no javascript function here. If this is incorrect, then please show us the javascript.