Here is my code. There's is a "Edit" link. I want to update data and save with that link
$op_sql = "SELECT * FROM tbl_users";
$result = $con->query($op_sql);
if ($result->rowCount() > 0)
{
echo "<table class='table' style='margin-left: 301px; margin-top: 10px; background-color: white;'>-;
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Email</th>";
echo "<th>Date of Birth<th>";
echo "<th></th>"; echo "</tr>";
while($row = $result->fetch())
{
echo "<tr>";
echo "<td>" . $rowrID1 . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Email']. "</td>";
echo "<td>" . $row['Date of Birth'] . "</td>";
echo "<td><a href='?id=".$row['ID']."'>Edit</a></td>";
echo "</tr>";
}
echo "</table>"; unset($result);
You can add the user_edit.php url in anchor tag href to edit the user details like this.
echo "<td><a href='user_edit.php?id=".$row['ID']."'>Edit</a></td>";
user_edit.php
Here you can get the id of specific user and get the details from database and create update form like this.
if(isset($_GET['id']) && $_GET['id']!='')
{
$op_sql = "SELECT * FROM tbl_users where id=$_GET['id']";
$result = $con->query($op_sql);
if ($result->rowCount() > 0)
{
$row = $result->fetch();
?>
<form action="user_update.php" method="post">
<input type="text" name="Name" value="<?php $row['Name'] ?>" />
.
.
<input type="hidden" name="id" value="$_GET['id']" />
.
.
<input type="submit" name="update" value="update" />
<?php
}
}
user_update.php
Here you can get the updated form data and update in database
if(isset($_POST['update']) && isset($_POST['id']) && $_POST['id']!='' )
{
// here you can get the updated form data and update in database
// update user set Name=$_POST['Name'],.... where id=$_POST['id'];
}
NOTE :
Try to use Prepared statement or PDO
I am giving an answer from This question you can use the same answer in your context here I'm providing the code from the accepted answer.
You can use a get method here in place of the post according to your situation.
HTML form:
<form method="post" action="handler.php">
<button type="submit" name="passed" id="passed" class="btn btn-success btn-flat"><i class="fa fa-check"></i></button>
<button type="submit" name="insufficient" id="insufficient" class="btn btn-danger btn-flat"><i class="fa fa-times"></i></button>
</form>
PHP:
<?php
// db connection
if(isset($_POST['passed'])){
$allowed = mysqli_query($conn," UPDATE users SET Access = "1" WHERE id = '27' ");
}
if(isset($_POST['insufficient'])){
$notallowed = mysqli_query($conn," UPDATE users SET Access = "0" WHERE id = '453' ");
}
Be careful if this has any user interaction at any given point.
Use a prepared statement, or PDO with prepared statements, they're much safer.
Related
this is my first PHP program and I'm kind of stuck in update button code I think the problem is with the Driver_ID I tried many different things but nothing works for me. my problem is how can I get the Driver_ID to make the button work?
in this code below I only get the last row id. If someone can help me I would really appreciate it.
<?php
include("dbconnection.php");
//Fetch the data from tables
$query="SELECT * FROM drivers JOIN users ON users.User_ID = drivers.User_ID";
$result = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($result))
{
echo "<tr>
<td>".$row['Driver_ID']."</td>
<td>" . $row['Driver_Name'] . "</td>
<td>" . $row['User_Name'] . "</td>
<td><p data-placement='top' data-toggle='tooltip' title='Edit'><button class='btn btn-primary btn-xs' data-title='Edit' data-toggle='modal' data-target='#edit'value='".$row['Driver_ID']."' name='editr'><span class='glyphicon glyphicon-pencil'></span></button></p></td>
<td><p data-placement='top' data-toggle='tooltip' title='Delete'><button class='btn btn-danger btn-xs' data-title='Delete' data-toggle='modal' data-target='#delete'><span class='glyphicon glyphicon-trash'></span></button></p></td>
</tr>";
$id=$row['Driver_ID'];
}
mysqli_close($connect);
?>
The html code for the hidden control
<input class="form-control " type="hidden" value="<?php echo $id ?>" name="driverid" >
the code for the update button
<?php
require("dbconnection.php");
if(isset($_POST['update']))
// include Database connection file
{
$driver_id=$_POST['driverid'];
$driver_name = $_POST['txtname'];
$user_id = $_POST['UserN'];
$sql = "UPDATE drivers
SET Driver_Name='$driver_name',User_ID='$user_id'
WHERE Driver_ID='$driver_id'";
if (mysqli_query($connect, $sql)) {
echo "Record updated successfully";
header('Refresh:5 ; url=drivers.php');
}
else {
echo "Error updating record: " . mysqli_error($connect);
}
}
mysqli_close($connect);
?>
Use input like this:
As you need all results you need to store them all
your main while loop could be like
$r=null;
while(){
$r++;
echo '<input class="form-control " type="hidden" value="<?php echo $id ?>" name="driverid[]" >'
}
echo '<input type="hidden" value='".$r."' name="records">';
After that just use some loop to see all results
and then in update /insert
$records=htmlentities($_POST['records'], ENT_QUOTES, "UTF-8");
$i=0;
while ($i <= $records){
$driverid=htmlentities($_POST['driverid'][], ENT_QUOTES, "UTF-8");
//your update/insert query here
$i++;
}
i hope this helps
Here is my code and i need to insert array values in $testar in to the table patients_testings. But it doesn't work with this code, where is the error? if i can do this using one global variable. it will be more helpful. thank you.
<form role="form" method="post" action="" name="testing" onsubmit="return validate_form()">
<?php
$sqltestin = "SELECT * FROM testings";
$querytestin = mysqli_query($dbhandle, $sqltestin);
while ($rowtestin = mysqli_fetch_assoc($querytestin)) {
echo '<input type="checkbox" name="testingar[]" value="' . $rowtestin['TestId'] . '">' . $rowtestin['TestName'] . '<br>';
}
?>
<div class="modal-footer">
<input type="submit" name="submittestin" id="submittestin" class="btn btn-success" value="Add Tests">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div></div>
<?php
$checkBox = '';
$testar = '';
if (isset($_POST['submittestin'])) {
global $checkBox;
global $testar;
$checkBox = $_POST['testingar'];
foreach ($checkBox as $testar1) {
$testar .= $testar1 . ",";
}
$tot = 0.00;
for ($i = 0; $i < sizeof($checkBox); $i++) {
$queryt2 = "SELECT * FROM testings WHERE TestId = $checkBox[$i] ";
$resultt2 = mysqli_query($dbhandle, $queryt2) or die (mysql_error());
while ($rowt2 = mysqli_fetch_assoc($resultt2)) {
echo "<tr><td>" . $rowt2['TestName'] . "</td>";
echo "<td width='100'>" . $rowt2['specimen'] . "</td>";
echo "<td>" . $rowt2['HopePrice'] . "</td></tr>";
//echo '<br/>';
$tot = $tot + $rowt2['HopePrice'];
}
}
echo "<tr><td><b>Total</b></td><td <b>:</b></td><td><b>" . number_format($tot, 2) . "</b></td></tr>";
echo "<tr><td><form role='form' method='post' action=''><input type='submit' name='printinv' id='printinv' class='btn btn-success' value='Print'></form></td></tr>";
//echo $testar;
if (isset($_POST['printinv'])) {
$sqltnum = "INSERT INTO patients_testings VALUES ('$ref_no','$testar')";
if (mysqli_query($dbhandle, $sqltnum) or die (mysql_error())) {
echo "Entered Successfully";
//}
}
}
}
?>
Why your code does not work:
I think the concept that you are missing is that when the page is requested, and on every subsequent form submission, the PHP code is executed then exits which throws out the values of the variables stored in memory. Making the variables global does not make them persist between requests.
Specifics to your code:
The first time the form is submitted isset($_POST['submittestin']) is true and it successfully populates the $testar variable with data. However, on the second post isset($_POST['submittestin']) is false and so you never hit the if (isset($_POST['printinv'])) section. Now, even if you move the if (isset($_POST['printinv'])) outside the first if ... submittestin you still have a problem because the $testar will no longer be populated with data.
Additionally, you use variables which are never initialized anywhere that I can see. $ref_no is an example.
I would also suggest echoing out your DB queries to see if they are properly formatted before you run them. I think that some of them may be missing 's in places.
How to make data persist between requests?
The best way is to start a session. By starting a session you can save variables in the $_SESSION array and then access them durring a different request.
Note: You cannot serialize resorces so you will need to reconnect to the database on each request. I.e., this won't work: $_SESSION['dbhandle'] = $dbhande;
Another way to set <input type=hidden ... elements in your form so that on the second post you can access them again through the $_POST variable.
Attempt to make your code use sessions:
<?php
session_start();
?>
<form role="form" method="post" action="" name="testing" onsubmit="return validate_form()">
<?php
$sqltestin = "SELECT * FROM testings";
$querytestin = mysqli_query($dbhandle, $sqltestin);
while ($rowtestin = mysqli_fetch_assoc($querytestin)) {
echo '<input type="checkbox" name="testingar[]" value="' . $rowtestin['TestId'] . '">' . $rowtestin['TestName'] . '<br>';
}
?>
<div class="modal-footer">
<input type="submit" name="submittestin" id="submittestin" class="btn btn-success" value="Add Tests">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div></div>
<?php
$checkBox = '';
$testar = '';
if (isset($_POST['submittestin'])) {
global $checkBox;
global $testar;
$checkBox = $_POST['testingar'];
foreach ($checkBox as $testar1) {
$testar .= $testar1 . ",";
}
$_SESSION['testar'] = $testar;
$_SESSION['ref_no'] = "This gets used below but I don't see it initialized anywhere?";
$tot = 0.00;
for ($i = 0; $i < sizeof($checkBox); $i++) {
$queryt2 = "SELECT * FROM testings WHERE TestId = '".$checkBox[$i]."'"; // syntax issue here
$resultt2 = mysqli_query($dbhandle, $queryt2) or die (mysql_error());
while ($rowt2 = mysqli_fetch_assoc($resultt2)) {
echo "<tr><td>" . $rowt2['TestName'] . "</td>";
echo "<td width='100'>" . $rowt2['specimen'] . "</td>";
echo "<td>" . $rowt2['HopePrice'] . "</td></tr>";
//echo '<br/>';
$tot = $tot + $rowt2['HopePrice'];
}
}
echo "<tr><td><b>Total</b></td><td <b>:</b></td><td><b>" . number_format($tot, 2) . "</b></td></tr>";
echo "<tr><td><form role='form' method='post' action=''>";
echo "<input type='submit' name='printinv' id='printinv' class='btn btn-success' value='Print'>";
echo "</form></td></tr>";
}
//echo $testar;
if (isset($_POST['printinv'])) {
if(isset($_SESSION['testar']) {
$testar = $_SESSION['testar'];
$ref_no = $_SESSION['refno'];
$sqltnum = "INSERT INTO patients_testings VALUES ('$ref_no', '$testar')"; // Where is $ref_no set?
if (mysqli_query($dbhandle, $sqltnum) or die (mysql_error())) {
echo "Entered Successfully";
}
}
}
?>
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
if(!isset($_POST['submit'])){
$result = mysql_query("SELECT * FROM pleasework ORDER BY ID");
$row = mysql_fetch_array($result);
}
?>
<form action="?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
<img id="close1" src="X.png" width="25" height="25" onclick ="div_hide1()">
<h2><font size="6">Please change existing data</font></h2>
<hr>
<br>
<font color="yellow">Change Name to: </font><input type="text" name="New" value="<?php echo $row['Name'];?>"/><br><br>
<font color="yellow"> Change Cause to: </font> <input type="text" name="New1" value="<?php echo $row['Cause'];?>"/><br><br>
<font color="yellow">Change Symptom to: </font><input type="text" name="New2" value="<?php echo $row['Symptom'];?>"/><br><br>
<font color="yellow"> Change Gene_affected to: </font><input type="text" name="New3"value="<?php echo $row['Gene_affected'];?>" /><br><br>
<input type="hidden" name="id" value="<?php echo $_GET['ID'];?>"/>
<input type="submit" onclick="clicked(event)" />
</form>
<?php
if(isset($_POST['submit'])){
mysql_query("UPDATE pleasework SET Name= '$_POST[New]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Cause= '$_POST[New1]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Symptom= '$_POST[New2]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Gene_affected= '$_POST[New3]' WHERE ID='$_POST[id]'");
echo "Change Successful<br>" ;
header("Location: databse.php");
mysql_close($con);
}
else {}
?>
This is my php file.
while($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . " </TD>";
echo "<TD>" . $row['Cause'] . " </TD>";
echo "<TD>" . $row['Symptom']. " </TD>";
echo "<TD>" . $row['Gene_affected'] . " </TD>";
echo "<TD><font color='red'>Delete row</font> </TD>";
echo "<TD><font color='red'>modify</font> </TD>";
echo "</TR>";
}
And this is the section which has a modify button that links to the edit.php file. The error here is that is doesnt bring over the values in the table to the editing page and then submitting the form doesnt work too. help please
Your code appears a bit confused.
First of all, why to put the modify routine after output the form? Especially since after modify you send the header function, that fails if previously there are some output.
Note also a typo: you forgot to properly open the php tag in the form declaration. Change-it in this way:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
The main problem is that you check if the $_POST[submit] if set, but this is not set, due to the absence of attribute name.
Change it in this way:
<input type="submit" name="submit" onclick="clicked(event)" />
Now your script should work (I don't have tested the sql).
Please also note that your UPDATE routine is redundant: you can reduce the 4 statement to only one in this way:
$result = mysql_query
(
"UPDATE pleasework SET Name='{$_POST[New]}', Cause='{$_POST[New1]}', Symptom='{$_POST[New2]}', Gene_affected='{$_POST[New3]}' WHERE ID={$_POST[id]}"
);
About PHP Original MySQL API:
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0
NOTE: mysql_* deprecated, so try to use PDO or mysqli_*.
Simple way:
<?php
if(isset($_POST['submit'])){
$result = mysql_query("UPDATE pleasework
SET Name='".$_POST['New']."',
Cause='".$_POST['New1']."',
Symptom='".$_POST['New2']."',
Gene_affected='".$_POST['New3']."'
WHERE ID=".$_POST['id'].");
if($result ){
echo "Change Successful<br>" ;
header("Location: databse.php");
}
mysql_close($con);
}
YOUR PHP:
while($row = mysql_fetch_array($result))
{ $spaces = " ";
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . $spaces."</TD>";
echo "<TD>" . $row['Cause'] . $spaces."</TD>";
echo "<TD>" . $row['Symptom']. $spaces."</TD>";
echo "<TD>" . $row['Gene_affected'] . $spaces."</TD>";
echo "<TD><a href='delete.php?id=".$row['ID'] ."'>";
echo "<font color='red'>Delete row</font></a>".$spaces."</TD>";
echo "<TD><a href='edit.php?id=" . $row['ID'] ."'>";
echo "<font color='red'>modify</font></a>".$spaces."</TD>";
echo "</TR>";
}
I am trying to create a table that will allow me to delete a row by clicking a delete button. I did find an article on here at the following link that did provide some help but I am still unable to get it to work: Show all rows in mysql table then give option to delete specific ones .I have written most of the code but I am having problem with line 10 on the delete.php page. Ideas?
Main.php
$result = mysqli_query($con,"SELECT * FROM cs_general_info");
echo "<table><tr><td>Delete</td><td>First Name</td><td>Last Name</td><td>Address</td>td>Phone</td><td>E-Mail Address</td></tr>";
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td>
<form action="delete.php" method="POST">
<input type="hidden" name="delete_id" value="<?php echo $row['id']; ?>">
<input type="Submit" value="Delete"></form>
</td>
<?php
echo "<td>" . $row['id'] ."</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
Delete.php
"DELETE FROM cs_general_info WHERE id=".mysql_real_escape_string($delete_id);
Hopefully delete.php is more than that single line. In delete.php you will want to catch the POST method and the $row[id]; bind it, then delete it.
To get the id of the row you want to delete in your delete.php file, you need to get the variable, like this:
$delete_id = $_POST['delete'];
WARNING: This is the very basic functionality you need to get this to work. However, you will need to implement many other levels of security before this should ever go into any production code.
If that is your delete.php, then you are missing a lot. You need a database connection and you need to execute the SQL command against the database. But that is the least of your worries until you get your parameters via $_POST.
Here is the PDO Manual for the database connection and SQL execution.
And here is the manual for $_POST.
You want to either put a link or inline form within each of your table’s rows, and then have a script that deletes the specified row and returns the user to your page.
<table>
<tbody>
<?php foreach ($results as $result): ?>
<tr>
<td><?php echo $result->title; ?></td>
<td>
<form action="delete.php" method="post">
<input type="hidden" name="id" value="<?php echo $result->id; ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And then delete.php:
<?php
if (isset($_POST['id']) && intval($_POST['id']) > 0) {
// create PDO instance; assign it to $db variable
$sql = "DELETE FROM `table` WHERE `id` = :id LIMIT 1";
$smt = $db->prepare($sql);
$smt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$smt->execute();
}
header('Location: index.php');
I would like to apologize if the duplicate of this question exist. i tried to find and could find anything here that could solve my problem..
I am using a form to get the input and update it in the mysql database, and then retrieve the records in the html form, and have defined the code for deleting the records individually through hyperlinks. however i want to do more, i want to use the checkboxes to delete the multiple records.
my code goes like this.
<?php
//include connection string
include('connection.php');
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"/>
Username : <input type="text" name="user"/><br />
Password : <input type="password" name="pass"/><br />
<input type="submit" name="submit" value="Send"/>
</form>
<?php
// query to insert into database
if(isset($_POST['user']) && isset($_POST['pass'])) {
$user = empty($_POST['user']) ? die(mysql_error()) : mysql_escape_string($_POST['user']);
$pass = empty($_POST['pass']) ? die(mysql_error()) : sha1(mysql_escape_string($_POST['pass']));
$query = "INSERT INTO users(name, pass) VALUES ('$user', '$pass')";
$result = mysql_query($query) or die(mysql_error());
}
if(isset($_GET['id'])) {
//query to delete the records
$query = "DELETE FROM users WHERE id = " . intval($_GET['id']);
$result = mysql_query($query);
}
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>delete";
echo "</tr>";
}
echo "</table>";
}
?>
i would like you to know that i am a newbie to programming world and i am not so sure of how exactly html checkbox work and how do i use it to delete the multiple records. i want to know what extra code do i have to write for it, and i would appreciate a lot if someone explains me that extra code in brief..
thank you..
This is probably a good time for another form:
<?php
// query to insert into database ...
// ... etc...
if(isset($_POST["formDeleteSelected"])) {
//query to delete the records
$query = "DELETE FROM users WHERE id IN (" . implode(", ",$_POST["rowid"]) . ")";
$result = mysql_query($query);
header("Location: mycode.php"); // just so 'refresh' doesn't try to run delete again
exit();
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<?php
//query to retrieve records
$query = "SELECT * FROM users";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ) {
echo "<table cellpadding=10 border=1>";
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><input type="checkbox" name="rowid[]" value=\"" . $row[0] . "\" /></td>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
<input type="submit" name="formDeleteSelected" text="Delete Selected" />
</form>
Or something like that (I haven't actually tried that code so there may be a typo). Also note that you should make sure to sanitize any form/get inputs for SQL Injection (plenty of information on that in other Stack Overflow questions).
First of all you need a checkbox and the id you want to delete:
<input id="delete" type="checkbox" name="delete" /><label for="delete">Delete user</label>
<input type="hidden" name="user_id" value="12345" />
You can then test if the checkbox has been set and then manually set the GET parameter to reuse your existing code:
if(isset($_POST['delete'])){
$_GET['id'] = $_POST['user_id'];
}
That's not the most elegant solution but a really simple one that should work with your code.
try an SQL query with a list of IDs
... WHERE id=$sentIds[0] OR id=$sentIds[1] OR ...
or use a set operation
... WHERE id IN ($i1,$i2 ... );
You sure have to send ids in the form for this to work, but You know that ;)