How to make buttons modify data from database - php

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 */
}
?>

Related

Value not saving after form is submitted

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);
}
?>

Why is the last iteration given, instead of the current one?

I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )
The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!

Dynamic form input names allocated to $_POST

I have a form that has the name value of the input element dynamically populated from a mysql query. Problem I am having is that I dont know to assign the value to a valid variable on form submission for later use, i cant declare the variable earlier in the scrip because i dont know it until the query is executed? how do i assign the name value to a $_POST variable? thanks.
my code
$con = new mysqli('localhost', 'jolly' ,'xxxx', 'jolly');
$query = 'SELECT * FROM names ORDER BY name ASC';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<p align="right"><?php echo $row['name'] ?>:
<input type="int" name="<?php echo $row['name'].'_score' ?>" />
</br>
<?php } ?>
<p align="right">
<input type="submit" name="submit" value="Next" />
</p>
</form>
Just use the value attribute of tag like this
<input type="text" name="somename" value="<?php echo $row['name'].'_score' ?>">
i am sure this will help
One possibility to solve your conundrum would be to run the sql query before generating the html and storing the query results in an array / object / session. Once the values are stored you can generate the html but by that stage would know the names and values from the db call.
$con = new mysqli( 'localhost', 'jolly' ,'xxxx', 'jolly' );
$query = 'select * from `names` order by `name` asc';
$result = mysqli_query( $con, $query );
$data = array();
/* add content from db to storage object */
while( $row = mysqli_fetch_assoc( $result ) ) $data[]=$row['name'];
/* possibly save as a session? */
$_SESSION['names']=$data;
/* generate the html */
<form method='post' name='names' action='/path/to/script.php' enctype='application/x-www-form-urlencoded'>
<?php
foreach( $data as $i => $name ){
echo "<p align='right'>{$name}<input type='int' name='{$name}_score' /></p>";
}
?>
<p align="right">
<input type="submit" name="submit" value="Next" />
</p>
</form>
if you stored the data in a session you should be able to access it in the form handler script if required.
You do not need to assign an explicit name to an input. What you have to is distinguish the forms. When submitting the post, the entire form is submitted.
your.php:
<?php
$var = $_post['data'];
...
>
form.php:
...
$con = new mysqli('localhost', 'jolly' ,'xxxx', 'jolly');
$query = 'SELECT * FROM names ORDER BY name ASC';
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<form id = "form_<?php echo $row['name'].'_score' ?>" name = "form_<?php echo $row['name'].'_score' ?>" action = "your.php" method = "POST">
<p align="right"><?php echo $row['name'] ?>:
<input type="int" name="data" value= "<?php echo $row['name'].'_score' ?>" />
</br>
<?php } ?>
<p align="right">
<input type="submit" name="submit" value="Next" />
</p>
</form>

Deleting something in a mysqli database with a button?

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 */
?>

How to trigger a sql query by clicking a button in PHP?

so I am trying to make a a online shop , basically what isn't working is to execute a query when the buy clicks the "BUY" button.The query is :
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
and the button is
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
The whole code :
<?php
$id = $_SESSION['SESS_MEMBER_ID'];
include ('config2.php');
$result = mysql_query("select * from shop_vehicule ORDER BY id DESC");
$result2 = mysql_query("select * from accounts where id = '$id'");
while($row = mysql_fetch_array($result2))
$credit = $row['credits'];
while($row = mysql_fetch_array($result)){
$name = $row['nume'];
$price = $row['pret'];
$left = $credit - $price;
$vehid = $row['vehid'];
echo "<p><center><b>$name</b> | $price </center>
More information about $name</p>
<div id=\"toPopup\">
<div class=\"close\"></div>
<span class=\"ecs_tooltip\">Press Esc to close <span class=\"arrow\"></span></span>
<div id=\"popup_content\"> <!--your content start-->
<p>
The $name costs $price, after you'll have $left !</p>
<form action=\"\" method=\"post\">
<input type=\"submit\" value=\"BUY\">
</form>
</div>
</div>
<div class=\"loader\"></div>
<div id=\"backgroundPopup\"></div>";
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
}
mysql_close();
?>
Here's my attempt to help, I didn't test the codes but it should be working. Please read the comments in the codes. It explains what it does.
$id = $_SESSION['SESS_MEMBER_ID'];
/* To use PDO the following line must be included in your config2.php
define('DB_HOST', 'localhost');
define('DB_NAME', 'database');
define('DB_USER', 'username');
define('DB_PASS', 'password');
$db = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
You can either use define or put the info straight into the PDO() function but I like it when it's easy to read and modify if needed.
*/
include ('config2.php');
$query = $db->prepare("SELECT * FROM accounts WHERE id = :id"); //Please use PDO or MySQLi, MySQL is outdated and unsecure. For this example, I am using my favorite method which is PDO.
$query->execute(array(':id' => $id));
$account = $query->fetchObject(); //Since we only need one line, we're going to use fetchObject object.
$query2 = $db->prepare("SELECT * FROM shop_vehicule ORDER BY id DESC");
$query2->execute();
$vehicules = $query2->fetchAll(); //I am using fetchAll due to multiple row will be returned.
foreach ($vehicules as $row) {
echo '<p><center><b>'.$row['nume'].'</b> | '.$row['pret'].' </center>
More information about $name</p>
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p>The '.$row['nume'].' costs '.$row['pret'].', after you\'ll have '.$account->credit - $row['pret'].' !</p>
BUY
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>';
}
// Basically what this part does is whenever the user click on the link, purchase will be set and it'll trigger the query to insert into the vehicule table then return a message if it was successful or not.
if ( isset($_GET['purchase']) ) {
$query = $db->prepare("INSERT INTO vehicles (model,owner) VALUES (':vehid',':id');");
$query->execute(array(':vehid' => $_GET['purchase'], ':id' => $id));
if ($query) {
echo 'Congratulations! You have successfully purchased the vehicule!';
} else {
echo 'An error has occured, the purchase was not complete.';
}
}
Use action=$_SERVER['PHP_SELF'] in the form tag and make a write the MySQL Insert Code in condition where isset($_POST['Buy']) is true.
you can do this in php, but in 2 different files.
The first will have the form, and the second will read the POST value and perform the query
Example(please fill missing pieces)
File 1 . php
<form action="file2.php" method="post">
<input type="hidden" value=<?php echo $vehid;?>" name="vehid">
<input type="hidden" value=<?php echo $id;?>" name="id">
<input type="submit" value="BUY">
</form>
File2.php
$vehid=$_POST['model'];
$id=$_POST['id'];
$sql = mysql_query("INSERT INTO vehicles (model,owner) VALUES ('$vehid','$id')");
For a complete tutorial see http://www.w3schools.com/php/php_mysql_insert.asp

Categories