So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>
Related
I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
I have a page which connects to the database and gets some data including title and content. I use a while loop to echo the data inside this page, what I'm trying to do is to have 2 buttons under every result that comes from database which is the "Edit" and "Delete" buttons. The problem is I don't know how to make buttons remove or edit the right column.EDITAdded the PHP part:
$sql = "SELECT * FROM posts ORDER BY date DESC, time DESC $limit";
$query = mysqli_query($conn, $sql);
<?php
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
?>
<section>
<b>Title: </b>
<p><?php echo $row['name'] ?></p><br>
<b>Content: </b><br>
<p><?php echo $row['content'] ?></p><br>
//want to have two buttons here which can be used to edit or delete the colunm that they are under it
</section>
<?php
}
Assuming you have an id column in posts table i.e. you have a unique id value associated with each row, create a <form>...</form> block encapsulating both Edit and Delete buttons, like this:
$sql = "SELECT * FROM posts ORDER BY date DESC, time DESC $limit";
$query = mysqli_query($conn, $sql);
<?php
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
?>
<section>
<b>Title: </b>
<p><?php echo $row['name'] ?></p><br />
<b>Content: </b><br>
<p><?php echo $row['content'] ?></p><br />
<form action="YOURPAGE.php?id=<?php echo $row['id']; ?>" method="post">
<input type="submit" name="edit" value="Edit" />
<input type="submit" name="delete" value="Delete" />
</form>
</section>
<?php
}
So once you hit Edit or Delete button of a particular row, the form will get submitted and you will be able get that particular row id using $_GET['id'] on YOURPAGE.php page. Based on that row id, perform the edit or delete operation accordingly.
YOURPAGE.php
<?php
/* get row id */
$id = isset($_GET['id']) ? $_GET['id'] : null;
if(isset($id) && isset($_POST['edit'])){
/* Edit button has been clicked */
/* create a prepared statement */
$stmt = mysqli_prepare($conn, "SELECT name, content FROM posts WHERE id = ?")
if($stmt){
/* bind parameters */
mysqli_stmt_bind_param($stmt, "i", $id);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $content);
/* fetch value */
mysqli_stmt_fetch($stmt);
/* close statement */
mysqli_stmt_close($stmt);
?>
<form action="" method="post">
<b>Title: </b><input type="text" name="title" value="<?php echo $name; ?>" /><br />
<b>Content: </b><br />
<textarea name="content" ><?php echo $content; ?></textarea><br />
<input type="submit" name="editrow" value="Edit" />
</form>
<?php
}else{
/* error */
}
}
if(isset($id) && isset($_POST['editrow'])){
$title = $_POST['title'];
$content = $_POST['content'];
/* edit row details based on the row id i.e. $id */
}
if(isset($id) && isset($_POST['delete'])){
/* Delete button has been clicked */
/* Delete row based on the row id i.e. $id */
}
?>
Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}
after trying to debug this snipet of code for hours, I find I cannot figure out why my edit form wont update for the life of me. I'm not sure if it's because I'm not using GET or POST methods correctly, I'm mis-using mysql, or a combination of the both. I cant even figure out why a line of print "hi"; wont show up. if i take out the line of code testing when the edit submit button is hit the print lines come out but my database wont update. So I figure I'm stuck where I can't do anymore print line debugging untill I figure out what I'm doing wrong. here is my code.. I commented next to the "print "hi";" line that doesnt show up. keep in mind I'm pretty sure I tried every combination of GET and POST and it still doesnt show up...
<html lang="en">
<head>
<title>Employee</title>
</head>
<body>
Clean <br>
<form method="post" action="employ.php">
<input type="text" name="fname">First Name<br>
<input type="text" name="lname">Last Name<br>
<input type="text" name="email">email<br>
<input type="text" name="zip">zip code<br>
<input type="submit" name="add" value="Add"> <!-- button itself -->
</form>
<br>
<?php //server login name password database
$link = mysqli_connect("server", "login", "password", "database") or die(mysqli_error());
if(isset($_POST['add'])) //this processes after user submits data.
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
$querycheck = "select * from employees where fname='$fname' and email='$email'";
$resultcheck = mysqli_query($link, $querycheck); //link query to database
if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
{//if not process the insert query
$query = "insert into employees values('', '$fname', '$lname', '$email', '$zip')";
mysqli_query($link, $query); //link query to database
print "Employee Added"; // print confirmation
}
else
{
print "That record already exists!";
}
}
else
{
print "You did not fill out the form correctly!";
}
} ////////////////////////////////edit portion/////////////////////////////
if(isset($_GET['edit']))
{
print "teseting edit<br><br>";
?>
<form method="get" action="employ.php">
<input type="text" name="fname" value = "<?php echo $_GET['fname']?>">First Name<br>
<input type="text" name="lname" value = "<?php echo $_GET['lname']?>">Last Name<br>
<input type="text" name="email" value = "<?php echo $_GET['email']?>">email<br>
<input type="text" name="zip" value = "<?php echo $_GET['zip']?>">zip code<br>
<input type="hidden" name="employeeid" value = "<?php echo $_GET['employeeid']?>">
<input type="submit" name="endedit" value="Edit"> <!-- button itself -->
</form>
<?php
print "teseting end edit <br><br>";
if(isset($_POST['endedit'])) //this processes after user submits edited data
{ //tried get and post
print "hi"; // DOESNT APPEAR
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$employeeidtemp = $_POST['employeeid'];
$re = "/^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/";
$reEmail = "/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/";
$reZip = "/^\d{5}$/";
//if user passes re test
if( preg_match($re, $fname) && preg_match($re, $lname)
&& preg_match($reEmail, $email) && preg_match($reZip, $zip) )
{ //display current table
//$querycheck = "select * from employees where employeeid='$employeeidtemp'";
//$resultcheck = mysqli_query($link, $querycheck); //link query to database
// if(mysqli_num_rows($resultcheck) == 0)// test if query does "nothing"
// {
$query = "UPDATE employees SET fname='$fname', lname='$lname', email='$email', zip='$zip' WHERE employeeid='$employeeidtemp'";
mysqli_query($link, $query); //link query to database
print "Employee Updated"; // print confirmation
// }
// else
// print "huh?";
}
else
{
print "You did not fill out the form correctly!";
}
}
}
if(isset($_GET['delete']))
{
print "teseting delete<br><br>";
}
showemp();
function showemp()
{
global $link;
if(isset($_GET['choice']))
{
$choice = $_GET['choice'];
}
else
{
$choice = "lname";
}
$query = "select * from employees order by $choice";
$result = mysqli_query($link, $query);
// print table (happens first before input)
// first print row of links/headers that sort
print "<table border='1'>
<tr>
<th>Edit</th>
<th>Delete</th>
<th><a href='employ.php?choice=fname'>FNAME</a></th>
<th><a href='employ.php?choice=lname'>LNAME</a></th>
<th><a href='employ.php?choice=email'>EMAIL</a></th>
<th><a href='employ.php?choice=zip'>ZIP</a></th>
</tr>";
//while the next row (set by query) exists?
while($row = mysqli_fetch_row($result))
{
list($employeeid, $fname, $lname, $email, $zip) = $row;
print "<tr>
<td><a href='employ.php?edit=yes&employeeid=$employeeid&fname=$fname&lname=$lname&email=$email&zip=$zip'>Edit</a></td>
<td><a href='employ.php?delete=yes&employeeid=$employeeid
onclick='return confirm(\"Are you sure\")'>Delete</a></td>
<td>$fname</td>
<td>$lname</td>
<td>$email</td>
<td>$zip</td>
</tr>";
}
print "</table>";
}
?>
</body>
</html>
You have several errors:
You do not check the result of queries, use at least
code mysqli_query($link, $query) or die(mysqli_error($link));
When I kick your code with checking errors, I found that adding query does not work - your empty string value for employeeid does not accepted for my integer field.
Do not use GET in forms. Always POST. If you need reaction on GET-url, write it separately or use $_REQUEST var.
In INSERT query always write fields. When you will decide to change list of fields in mysql table, then you can get the strange behavior of this code.
Your main error is that your condition with print 'hi' is inside the condition if(isset($_GET['edit'])), it does not work when user sublim form.
I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.