Do not display the array taken from the database without sending data - php

Why the database isn't displayed without send form?
when I submit using the form, all the data is displayed, but when I open this page at new, it doesn't display table of database, even when refreshed.
all codes are in a page
SQL, connect
<?php
include '../../database/db.php';
if(isset($_POST['submit'])){
$title = $_POST['title'];
$sort = $_POST['sort'];
$result = $conn->prepare("INSERT INTO menu SET title=?, sort=?");
$result->bindValue(1, $title);
$result->bindValue(2, $sort);
$result->execute();
$all = $conn->prepare("SELECT *FROM menu");
$all->execute();
$menus = $all->fetchAll(PDO::FETCH_ASSOC);
}
?>
form
<form method="POST">
<input type="text" name="title">
<input type="number" name="sort">
<input type="submit" name="submit" value="save">
</form>
show database
<?php
foreach ($menus as $menu){ ?>
<tr>
<td><?php echo $menu['title']; ?></td>
<td><?php echo $menu['sort']; ?></td>
</tr>
<?php } ?>

Related

php page to list and update sqlite

I have the following code to display and modify a simple sqlite table
<?php
$db = new SQLite3("my_sqlite.db");
$query = "SELECT rowid, * FROM students";
$result = $db->query($query);
if( isset($_POST['submit_data']) ){
// Gets the data from post
$name = $_POST['name'];
$email = $_POST['email'];
$query = "UPDATE students set name='$name', email='$email'";
if( $db->exec($query) ){
echo "Data is updated successfully.";
}else{
echo "Sorry, Data is not updated.";
}
}
?>
<table border="1">
<form action="" method="post">
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php while($row = $result->fetchArray()) {?>
<tr>
<td><input name="name" type="text" value="<?php echo $row['name'];?>"></td>
<td><input name="email" type="text" value="<?php echo $row['email'];?>"></td>
</tr>
<?php } ?>
<input name="submit_data" type="submit" value="Update Data">
</form>
</table>
PROBLEM: When I change some of the information and update, the whole column changes into the same change. E.g.: if I write a the name Nick, every name changes into Nick.
First, you should only do updates for one record at a time so each record needs its own update button. Attached is the corresponding rʔwid of the record. you can use:
<input type="hidden" name="rowid" value="$row['rowid]">
You should add a WHERE clause to the update statement to know exactly which records should be updated.If you omit the WHERE clause, ALL records will be updated!

Why last row deleted when refresh page in wordpress

When I refresh page table row deleted and last query deleted when I click on any delete button of other row. Why is this happened?
This is table which I displayed
<?php
global $wpdb;
$table= 'wp_contact_form';
$result = $wpdb->get_results ( "SELECT * FROM $table" );
if(!empty($result)){
foreach ( $result as $print ) {
?>
<tr>
<td><?php echo $print->id;?></td>
<td><?php echo $print->names;?></td>
<td><?php echo $print->emails;?></td>
<td><?php echo $print->gender;?></td>
<td><?php echo $print->age;?></td>
<td><input type="submit" value="Edit" id="" name="update"></td>
<td><input type="submit" value="delete" id="delete" name="delete"></td>
</tr>
<?php
}
}
?>
this is delete query
$id= $print->id;
if(isset($_POST['delete']))
{
$result = $wpdb->delete($table, array('id' => $id));
if(!empty($result))
{
echo "success";
}
}
error screenshot - https://prnt.sc/wdg3xv
You're not specifying which ID should be deleted if $_POST['delete'] is set, right now you're asking WP to just delete something.
You need to wrap your elements in a form and add a field that contains the exact ID of the element you want to delete, like this:
<td>
<input type="submit" name="delete" value="delete" />
<input type="hidden" name="targetItem" value="<?php echo $print->id;?>" />
</td>
Then in your PHP use that field's ID to delete it from the DB:
if (isset($_POST['delete']))
$result = $wpdb->delete($table, array('id' => $_POST['targetItem']));

PHP Form to delete records in mySQLi when displaying then in a table

I'm making a system to display pages in the system in a table and one of the columns is the action column giving people the option to delete the page. I did this:
listpages.php
<?php
$sql = "SELECT * FROM Pages";
$result = $conn->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
$pages[] = array_map('htmlspecialchars', $row);
}
}
// PHP is finished now, here's the HTML
?>
<form method="post" action="utils/delpage.php">
<table>
<thead>
<tr>
<th>Page Name</th>
<th>Page Type</th>
<th>Registered on</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach($pages as $page):?>
<tr>
<input type="hidden" name="targetid" value="<?= $page['id'] ?>"></input>
<td><?= $page['pagename'] ?></td>
<td><?= $page['pagetype'] ?></td>
<td><?= $page['regdate'] ?></td>
<td><input type="submit" value="delete" class="red-text material-icons tooltipped" data-tooltip="Delete"><td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</form>
delpage.php
<?php
include ('../../php/db.php');
$id = $_POST['targetid'];
$target = htmlentities($id);
$stmt = $conn->prepare("DELETE FROM Pages WHERE id = (?)");
$stmt->bind_param("i", $page);
$page = $target;
$stmt->execute();
?>
This partially works: I get the trash icon I set to delete records. The problem is, when I click it, it will always delete the last record instead of the record it was said to delete. This is a problem, an not how it was really supposed to work. I don't see why it's doing this as the id is being "displayed" the same way the other information is. I searched SO for an answer but nothing worked and I didn't see many options but creating a question. Any help?
Thanks in advance
If this is one big form then you will have multiple fields all named targetid. That's a problem and the browser is sending the value of the last field. Try small forms like below. Each form could have it's own name by numerating them.
Remove the form from above an place it in the loop.
<?php foreach($pages as $page):
?>
<tr>
<form method="post" action="utils/delpage.php">
<input type="hidden" name="targetid" value="<?= $page['id'] ?>"></input>
<td><?= $page['pagename'] ?></td>
<td><?= $page['pagetype'] ?></td>
<td><?= $page['regdate'] ?></td>
<td><input type="submit" value="delete" class="red-text material-icons tooltipped" data-tooltip="Delete"><td>
</tr>
</form>
<?php endforeach ?>
Here is a simple example of inputs with the same name and the value that is received by PHP:
<form method="post" action="#">
<input name="a" value="1">
<input name="a" value="2">
<button type="submit" value="delete">Always prints second.</button>
</form>
<form method="post" action="#">
<input name="a" value="1">
<button type="submit" value="delete">Returns 1</button>
</form>
<form method="post" action="#">
<input name="a" value="2">
<button type="submit" value="delete">Returns 2</button>
</form>
<?php
if (isset($_POST['a'])) {
echo $_POST['a'];
} else {
echo 'page loaded';
}
There is mistake in your delpage.php, you are passing wrong variable to sql query id parameter.
Look into this for bindParam.
Try this:
delpage.php
<?php
include ('../../php/db.php');
$id = $_POST['targetid'];
$target = htmlentities($id);
$stmt = $conn->prepare("DELETE FROM Pages WHERE id = :id");
$stmt->bindParam(":id", $target);
$page = $target;
$stmt->execute();
?>

Form action not allowing the delete of a record

I had to add a form action to go to a different page to edit a specific record, but with doing that, it won't allow me to delete a record because it is taking me away from it before it will do the query. I am unsure of how to make this work and still get to the new page when I hit the "Edit" button.
<table id="tableid">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Product</th>
<th>Save</th>
<th>Delete</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$stmt = $dbc->query("SELECT `id`,`first`,`last`,`product` FROM users");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
?>
<form method="POST" action="edit-product">
<tr>
<td><?php echo $row['id'];?>"</td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<input name="id" type="hidden" value="<?php echo $row['id'];?>" readonly>
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<td><input name="save" type="submit" value="Save"></td>
<td><div class="delete-class" name="delete" id="<?php echo $row['id']; ?>">Delete</div></td>
<td><input name="edit" type="submit" value="Edit"></td>
</tr>
</form>
<?php } ?>
</tbody>
</table>
PHP DELETE query
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
How can I change the markup to still get both the edit (going to another page with the action) and the delete to work on this page?
UPDATE AJAX code:
$(function() {
$(".delete_class").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete-product.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // DO SOMETHING
} else { // DO SOMETHING }
}
)); //here
});
});
This is not very ideal but one way to do it. You change the HTML markup to create two forms, one for edit case and another one for Delete. The delete case sends the request to the current page like this:
while($row = $stmt->fetch()) {
?>
<tr>
<td><?php echo $row['id'];?></td>
<td><?php echo $row['first'];?></td>
<td><?php echo $row['last'];?></td>
<td><?php echo $row['product'];?></td>
<td>
<form method="post" action="edit-product">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="first" type="hidden" value="<?php echo $row['first'];?>">
<input name="last" type="hidden" value="<?php echo $row['last'];?>">
<input name="product" type="hidden" value="<?php echo $row['product'];?>">
<input name="save" type="submit" value="Edit">
</form>
</td>
<td>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="id" type="hidden" value="<?php echo $row['id'];?>">
<input name="delete" type="submit" value="Delete">
</form>
</td>
</tr>
<?php }
?>
</tbody>
</table>
<?php
// the delete code goes here
if(isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
I left out the save case but it will be similar to edit case.
Rather than having a form you could just have links instead of form submit buttons. That way each link could take you to a specific page that performs a specific task. By passing query string variables and using $_GET rather than $_POST, you can retain the product ID information.
Example:
<td>Save</td>
<td>Delete</td>
<td>Edit</td>
These individual pages could then perform your tasks in the database. Both save and delete could use Header re-directs to get back to your original page with your product list.
delete_product.php Example:
// delete product from database
$id = $_GET['id']; // Note that it's a $_GET
$stmt = $dbc->prepare("DELETE FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
// re-direct to original list page
header("Location: product_list.php"); // or whatever you have your list page named.
The edit_product.php page would then have your typical form for making changes to a specific product. You will need to lookup the product again in the database using $_GET['id'] value to match it with.
As it was suggested in the comments, using AJAX would make the whole process appear to be seamless, rather than jumping around between pages and being re-directed.

Insert to database when the button is click

im currently displaying all the information from the table product in a tabular format, i have a button ADD which when click should add only the id, name and price from the table product to the table product_add in the same database. but my problem is that when i click on the button ADD, nothing is entered in the product_add table.
<?php
include'connect.php';
$image =$_GET['image'];
$id =$_GET['id'];
$name =$_GET['name'];
$price=$_GET['price'];
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0)
{
?>
<form method="post" id="form" name="form">
<table border='1'>
<?php
while ($row = mysql_fetch_array($result))
{
extract($row);
?>
<tr>
<td><?php echo $row['id']?></td>
<td><img src=<?php echo $row['image'] ?> /></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['price']?></td>
<td><input type='button' value='ADD' id="insert" name="insert"/></td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if(isset($_REQUEST['insert']))
{
$insert = "INSERT INTO product_add(id, name, price)
VALUES ('$row[id]','$row['name']','$row['price']')";
$insertQuery=mysql_query($insert);
}
?>
</body>
</html>
I have updated the codes as shown below but the last row from the table product is being added to the table product_add. I want to add only a specific row when i click on the button submit.
<?php
include'connect.php';
$image = isset($_GET['image']) ? $_GET['image'] : "";
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<form method="POST" id="form" name="form">
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
extract($row);
?>
<tr>
<td><input name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
</td>
<td><img src=<?php echo $row['image'] ?> width='120' height='100'/></td>
<td><input name="name" value="<?php echo htmlspecialchars($row['name']);
?>"></td>
<td><input name="price" value="<?php echo htmlspecialchars($row['price']);
?>"></td>
<td>
<input id="submit" type="submit" name="submit" value='Add to cart' />
</td>
</tr>
<?php
}
?>
</table>
</form>
<?php
}
if (isset($_REQUEST['submit']))
{
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id',
'$name','$price')";
$insertQuery=mysql_query($insert);
}
?>
Apart from the method (if your form uses POST, you should use $_POST in php), you do not have any form fields.
For example:
<?php echo $row['id']?>
Should be something like:
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
and:
<?php echo $row['name']?>
should be:
<input name="name" value="<?php echo htmlspecialchars($row['name']); ?>">
etc.
You should also switch to PDO or mysqli and prepared statements as the code you have now is vulnerable to sql injection. And ID's in html need to be unique.
One point is, you have multiple
<input type='button' ...>
with the same id="insert". ids must be unique within a web page.
The other thing is, you need a submit input to send the form
<input type="submit" ...>
From Submit Button state (type=submit)
The input element represents a button that, when activated, submits the form.
With <input type='button' ...> nothing happens, because it has no default action, see Button state (type=button)
The input element represents a button with no default behavior.
If you want an <input type='button' ...> to submit the form, you must do so by using some Javascript code.
One idea is to load content once the button is clicked.
js
$("#button").click(function() {
$("#holder").load("insert.php");
});
insert.php
$db->query("INSERT INTO table VALUES('one','two','three')");

Categories