hope you fine and well,
i have the following form:
<form class="hidden-print" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tr>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * from persons";
$i=0;
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo'<input type="hidden" name="id[]" value="' . $row['id'] . ' ">';
echo '<td>'. $row['Name'] . '</td>';
echo'<input type="hidden" name="name[]" value="' . $row['Name'] . ' ">';
$i++;
}
Database::disconnect();
?>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Send" >
</form>
let me explain what happening here, my form is PHP_SELF so i post the data to the same page, i created a table inside the form which contains ID's and Names, i loop through the selected data and each row in the table will contain id and name of person, as you see, i defined the inputs name and id as arrays eg. name[] and id[] , and i have a submit button at the end of the form will post the arrays id[] and name[].
now what i want is to put an submit input in each row ! so when i click the submit button it will post just the id and the name of the person in this row !
is this possible ?!
regards.
You are already using associative array in names e.g. name[]
Use counters:
name[<?php echo $i;?>]
And add submit buttons with the same
<input type="submit" name="submit[<?php echo $i;?>]"/>
In PHP, loop over $_POST.
And check index of submit button using foreach loop.
Use the same index for name, id, etc.
Hope it helps.
Answer updated with code:
<form class="hidden-print" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tr>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * from persons";
$i=0;
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo'<input type="hidden" name="id['.$row['id'].'" value="' . $row['id'] . ' ">';
echo '<td>'. $row['Name'] . '</td>';
echo'<input type="hidden" name="name['.$row['id'].'" value="' . $row['Name'] . ' ">';
?>
<td>
<input class="btn btn-primary" type="submit" value="Send" name="send<?php echo $rowp['id'];?>" >
</td>
</tr>
<?php
++$i;
}
Database::disconnect();
?>
</tr>
</table>
</form>
<?php
if (! empty($_POST['send'])) {
foreach ($_POST['send'] as $key => $posted) {
$id = isset($_POST['id'][$key]) ? $_POST['id'][$key] : '';
$name = isset($_POST['name'][$key]) ? $_POST['name'][$key] : '';
// Do your SQL here.
}
}
?>
Note: HTML mark ups are used as it is, please correct it as per your needs.
Related
I am trying to update the rank column in the users table in my database by presenting data in a PHP form and using a button to submit. However once i edit the data in my PHP form and press submit, the data in the database remains unchanged. I'm adding a (link to the) picture of the webpage, and the code is posted below.
Webpage image
<!DOCTYPE HTML>
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
Displays all data from 'users' table
*/
// connect to the database
include('../db/connect.php');
// get results from database
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Username</th> <th>Email</th> <th>Rank</th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = $result->fetch_array()) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['user_id'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td><input type="hidden" name="user_id[]" id="newrank" width="20px" min="0" max="100" value="' . $row['user_id'] . '"></td>';
echo '<td><form method="POST" action=""><input type="number" name="newrank[]" id="newrank" width="20px" min="0" max="100" value="' . $row['rank'] . '"></form></td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
if(isset($_POST['btn-update'])) {
for($i = 0; count($_POST["user_id"]); $i++) {
$_POST['newrank'][$i] = $MySQLi_CON->real_escape_string($_POST['newrank'][$i]); # If this function exists either, if not comment or remove this line!
$_POST['user_id'][$i] = $MySQLi_CON->real_escape_string($_POST['user_id'][$i]); # If this function exists either, if not comment or remove this line!
$MySQLi_CON->query('UPDATE users SET rank=' . $_POST['newrank'][$i] . ' WHERE user_id=' . $row['user_id'][$i] . '');
}
echo "Updated the rows.";
}
?>
<br>
<button type="submit" class="btn btn-default" name="btn-update" id="btn-update">Update</button></a>
<p>Add a new record</p>
</body>
</html>
Seems there is an error in your query statement
Modify this : if ($$MySQLi_CON->query($sql) === TRUE) {
with if ($MySQLi_CON->query($sql) === TRUE) {
You need to parse the id you wish to modify to the $_POST. Also, you need to use <form action="" method="POST"> in your code.
Didn't tested it, but the following should work:
<!DOCTYPE HTML>
<html>
<head>
<title>View Records</title>
</head>
<body>
<table border='1' cellpadding='10'>
<thead> <th>ID</th> <th>Username</th> <th>Email</th> <th>Rank</th> <th colspan="3"></th></thead>
<tbody>
<?php
//Displays all data from 'users' table
// connect to the database
include('../db/connect.php');
// get results from database
$result = $MySQLi_CON->query("SELECT * FROM users")
or die(mysql_error());
// loop through results of database query, displaying them in the table
while($row = $result->fetch_assoc()) {
// echo out the contents of each row into a table
?>
<form action="" method="POST">
<tr>
<td><?php echo $row['user_id']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['email'];?></td>
<td><input type="number" name="newrank" id="newrank" value="<?php echo $row['rank']; ?>"></td>
<td><input type="hidden" name="id" value="<?php echo $row['user_id']; ?>"><button type="submit" class="btn btn-default" name="btn-update" id="btn-update">Update</button></td>
<td>Delete</td>
</tr>
</form>
<?php
}
?>
</tbody>
</table>
<?php
if(isset($_POST['btn-update']))
{
$sql = 'UPDATE users SET rank=' . $_POST['newrank'] . ' WHERE user_id=' . $_GET['id'] . '';
if ($MySQLi_CON->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $MySQLi_CON->error;
}
}
?>
<p>Add a new record</p>
</body>
</html>
This is a table of students' ID numbers, with a button after each ID.
When I click on a button, I want it to open a new page called "score.php", and display the selected ID.
But the code doesn't work. It only show the text "ID", but not the number.
Here is "index.php"
<html>
<head>test</head>
<body>
<form method="post" action="score.php">
<?php
$result = mysql_query("SELECT * FROM term3_2556")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Student ID</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['student_id'] . '<input type="hidden" name="student_id" value=" ' . $_POST['student_id'] . ' " /> <button type="submit" name="btn_student_id" >Select</button> </td> ';
echo '</tr>';
}
echo "</table>";
?>
</form>
</body>
</html>
And here is "score.php"
<head>test</head>
<body>
<?php
$student_id = $_POST["student_id"];
echo '<p> ID: '.$student_id.'</p>';
?>
</body>
Since you are using a <button>, there is no need to use a <input type="hidden">. Just add the student_id as the button value -
<button type="submit" name="btn_student_id" value=" ' . $row['student_id'] . ' " >Select</button>
Then in you php just get the value from the clicked on button -
<?php
$student_id = $_POST["btn_student_id"];
echo '<p> ID: '.$student_id.'</p>';
?>
your index.php file will be:
<html>
<head>test</head>
<body>
<form method="post" action="score.php">
<?php
$result = mysql_query("SELECT * FROM term3_2556")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Student ID</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>' . $row['student_id'] . '<input type="hidden" name="student_id" value=" ' . $row['student_id'] . ' " /> <button type="submit" name="btn_student_id" >Select</button> </td> ';
echo '</tr>';
}
echo "</table>";
?>
</form>
</body>
</html>
I have a MySQL DB table as users.
I am populating a html table using php and ajax.(working fine)
but I want to search for specific data, written some code also, but not getting what is my mistake.
my index.html
<body>
<div class="container">
<h3>Product List</h3>
<div id="users-grid">
</div>
</div>
</body>
<script>
function getresult(url) {
$.ajax({
url: url,
type: "POST",
success: function(data){ $("#users-grid").html(data);}
});
}
getresult("getresult.php");
</script>
my getresult.php(used to populate the #users-grid )
<?php
include 'database.php';
$pdo = Database::connect();
$product = "";
$queryCondition = "";
?>
<form name="frmSearch" method="post" action="index.php">
<div class="search-box">
<p>
<input type="text" placeholder="Product Name" name="product" value="<?php echo $product; ?>" />
<input type="button" name="go" class="btnSearch" value="Search" onclick="getresult('getresult.php')">
<input type="reset" class="btnSearch" value="Reset" onclick="window.location='index.php'"></p>
</div>
<table class="table table-striped table-bordered" class="tablesorter">
<thead>
<tr>
<th>Date</th>
<th>Product</th>
<th>Quantity</th>
<th>Gross Price</th>
<th>Profit</th>
</tr>
</thead>
<tbody>
<?php
$queryCondition = "";
if(!empty($_POST["product"])) {
$queryCondition .= " WHERE product LIKE '" . $_POST["product"] . "%'";
}
$orderby = " ORDER BY id desc";
$sql = "SELECT * FROM users " . $queryCondition . $orderby;
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['date'] . '</td>';
echo '<td>'. $row['product'] . '</td>';
echo '<td>'. $row['quantity'] . '</td>';
echo '<td>'. $row['grossprice'] . '</td>';
echo '<td>'. $row['profit'] . '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</form>
Thank you
this code will search anything start with your search query
$queryCondition .= " WHERE product LIKE '" . $_POST["product"] . "%'";
i think you should change it to this for haveing full search
$queryCondition .= " WHERE product LIKE '%" . $_POST["product"] . "%'";
when you put onclick on your submit button it will fire only when user click on the button but when user put something on text and press enter it will submit your form so you have to change your code to this
<form name="frmSearch" method="post" onsubmit="return getresult('getresult.php')">
<div class="search-box">
<input type="text" placeholder="Product Name" name="product" value="<?php if(isset($_POST["product"])) echo $_POST["product"]; ?>" />
<input type="button" name="go" class="btnSearch" value="Search">
<input type="reset" class="btnSearch" value="Reset" onclick="window.location='index.php'">
</div>
</form>
i changed input value to show your search query. and the return part is for stop page reload
and to send POST data you have to change your ajax code to this
function getresult(url) {
$.ajax({
url: url,
type: "POST",
data: {product: $('input[name=product]').val()},
success: function(data){ $("#users-grid").html(data);}
});
return false
}
I have a database containing books. On a page, I have loop that prints each record in the database which each book's title, author, publisher, date, and rating. I want to use a delete button at the bottom of each record in order to delete it.
When I click on the delete button, the page is updated, but the record is not deleted.
I have tried to find solutions to this problem, but have yet to. I tried to use the book_id category in my database table as my index, in order to identify each record and delete it but it does not work.
Here is the code for my button form, as it appears with html code:
while ($row = mysqli_fetch_array($result))
{
echo '<div id="forminput">';
$timestamp = strtotime($row['date']);
echo '<div id = "bookpicture">';
echo '<img src="images/Book Cover 8crop.jpg" alt="Book Cover">';
echo '</div>';
echo '<div id = "bookinfo">';
echo '<div id = "titleauthor">';
echo '<h3>' . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . '</h3>';
echo '<p>' . htmlspecialchars($row['author'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '</div>';
$id = htmlspecialchars($row['book_id'], ENT_QUOTES, 'UTF-8');
echo '</div>' ;
echo '<div id = "publisher">' ;
echo '<p>' . 'Published on' . " " . htmlspecialchars(date('F j, Y,', $timestamp),
ENT_QUOTES, 'UTF-8') .
" " . 'by' . " " . htmlspecialchars($row['publisher'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '<div id = "formDelete">';
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="submit" value="Update" name="myAdd" id="myAdd" style = "width:
100px" required>';
echo '<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:
100px" required>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '<hr>' ;
echo '</div>';
}
?>
Here is the code from my index.php file.
else if (isset($_POST['myDelete']))
{
$ids = mysqli_real_escape_string($link, $_POST['$id']);
$sql="DELETE FROM readbooks WHERE book_id = '$ids'";
if (!mysqli_query($link, $sql))
{
$error = 'Error with submission: ' . mysqli_error($link);
include 'php/error.html.php';
exit();
}
}
Here is the updated code.
The Problem is you are not trying to send the row ID from the form.
In Form try sending row id from the form
echo '<input type="hidden" name="id" value="$id">'
try receiving that parameter
$id = $_POST['id'];
$con = mysql_connect("host address","mysql_user","mysql_pwd");
$query = "DELETE FROM readbooks WHERE id = $id";
mysql_query($query,$con);
Moving from comment, you're not actually getting the $id anywhere. Add a field to your form:
<input type='hidden' name='id' value='$id'>
and then refer to it in your php:
$ids = mysqli_real_escape_string($link, $_POST['id']);
Since your using mysqli now, use prepared statements. Do not directly use your user input to the query! Example:
$books = array();
// connection
$con = new mysqli('localhost', 'your_username', 'password_of_username', 'your_database');
if(isset($_POST['myDelete'])) {
$book_id = $_POST['myDelete']; // get the variable id
$stmt = $con->prepare('DELETE FROM readbooks WHERE book_id = ?');
$stmt->bind_param('i', $book_id);
$stmt->execute();
}
$result = mysqli_query($con, 'SELECT * FROM readbooks');
while($row = $result->fetch_assoc()) {
$books[] = $row;
}
?>
<form method="POST">
<table border="1" cellpadding="10">
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th></th>
</tr>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['title']; ?></td>
<td><?php echo $book['author']; ?></td>
<td><?php echo $book['publisher']; ?></td>
<td><button type="submit" name="myDelete" value="<?php echo $book['book_id']; ?>">Delete</button></td>
</tr>
<?php endforeach; ?>
</table>
</form>
I think you're having problem with the id that you are passing to your PHP code. Try to use var_dump($_POST) to see what is the content of your $_POST variable. As I can see, the index of $_POST is wrong.
<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:100px" required>';
Try to change this to
<input type="submit" name="book_id" value="$id" style = "width:100px" required>';
In your php use this $_POST["book_id"] to get the value of book_id you posted.
Note : The attribute "name" of the input tags will be the index of your $_POST variable
I understand that you want to have a delete and update button at the same time. The problem is your logic behind the situation. You need to have a hidden field and put the id inside it. Try to use this.
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="hidden" value="$id" name="book_id" id="myAdd" required>';
echo '<input type="submit" value="Update" name="action" id="myAdd" required>';
echo '<input type="submit" value="Delete" name="action" id="$id" required>';
echo '</form>';
In your php code use try to have a condition like this :
$book_id = $_POST["book_id"];
if($_POST["action"] == "delete")
{
//do your deletion code here. use the variable $book_id
}
else{
//do your update code here.use the variable $book_id
}
I'm trying to create insert, update and delete relate to shopping, all of them are working fine except update page.
Please see sample code of list of product from index.php page ...
<?php
$sql = "SELECT product_id, product_name, product_category, product_retail_price, product_price, product_detail FROM product";
$result_db = $db->query($sql) or die('Error perform query!');
?>
<table border="1">
<tr>
<th>product name</th>
<th>product category</th>
<th>product retail price</th>
<th>price</th>
<th>detail</th>
<th>Update</th>
<th>Delete</th>
<th>Insert</th>
</tr>
<?php
while ($r = $result_db->fetch_object()) {
$update = "update_form.php?product_id={$r->product_id}&
product_name={$r->product_name}&
product_category=$r->product_category&
product_retail_price={$r->product_retail_price}&
product_price={$r->product_price}&
product_detail={$r->product_detail}";
$delete = "delete.php?product_id={$r->product_id}";
$insert = "insert.php";
echo '<tr>';
echo '<td>' . $r->product_id . '</td>';
echo '<td>' . $r->product_name . '</td>';
echo '<td>' . $r->product_category . '</td>';
echo '<td>' . $r->product_retail_price . '</td>';
echo '<td>' . $r->product_price . '</td>';
echo '<td>' . $r->product_detail . '</td>';
echo "<td><a href='{$update}'>Update</a></td>";
echo "<td><a href='{$delete}'>Delete</a></td>";
echo "<td><a href='{$insert}'>Insert</a></td>";
echo '</tr>';
}
$db->close();
?>
</table>
</body>
As you can see above code where it said
while ($r = $result_db->fetch_object()) {
$update = ......
This sending the data of relate to product using "product_id" sending sending to the updateform.php page ... that updateform.php page is the code showing
<body>
<form action="update.php" method="post">
<input type="hidden" value="<?= $_GET['product_id'] ?>" name="product_id"/>
product name: <input type="text" name="product_name" value="<?= $_GET['product_name'] ?>">
product category: <input type="text" name="product_category" value="<?= $_GET['product_category'] ?>">
product retail price: <input type="text" name="product_retail_price" value="<?= $_GET['product_retail_price'] ?>">
product price: <input type="text" name="product_price" value="<?= $_GET['product_price'] ?>">
product detail: <input type="text" name="product_detail" value="<?= $_GET['product_detail'] ?>">
<input type="submit" name="submit">
</form>
</body>
</html>
When I run the code, the updateform.php showing the text field with <?= $_GET['xxxxxx'] ?>"
Why am I getting this result?
Is it this code?
$update = "update_form.php?product_id={$r->product_id}&
product_name={$r->product_name}&
product_category=$r->product_category&
product_retail_price={$r->product_retail_price}&
product_price={$r->product_price}&
product_detail={$r->product_detail}";
Is it the right code to get right information from database using "product_id" number? Is there better code to write than this?
Try using :
<?php echo $_GET['xxxxxx']; ?>
and if it works, it means that in your php configuration the use of short opening tags is restricted. meaning no