as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>
Related
Well i got this script
while($row = $result->fetch_assoc()) {
$_SESSION["sup"] = $row['id'];
if ($hi < $row['buytime']) {
} else {
echo " <form action='Action1.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='Action.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
The only problem is hat in line $_SESSION["sup"] = $row['id'];
Keeps sending a fixed value which it's 144 while the $row['id']; is not a fixed value , i'm really lost lol
If session is a bad idea , how can i send ID to action.php without inserting the ID in a hidden input ?
Update the two pages
First PAge
<?php
$conn = mysqli_connect("localhost", "localhost", "localhost", "localhost");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$buyer = $_SESSION['username'];
$sql_shells = "SELECT buytime,id,situation,buyer FROM shells WHERE situation = 'sold' AND buyer = '$buyer' ";
$dt = new DateTime();
$dt->modify('+172799 seconds');
$hi = $dt->format('Y-m-d H:i:s');
$_SESSION["sup"] = [];
$result = $conn->query($sql_shells);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
if ($hi < $row['buytime']) {
}else{
echo " <form action='view_item.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='reportinsert.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
}else {
}
?>
Second page
<?php
session_start();
if (isset($_SESSION['username'])) {
$link = mysqli_connect("localhost", "localhost", "localhost", "localhost");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$trn_date = date("Y-m-d H:i:s");
$seller = $_SESSION['username'];
$id = $_POST['whatever'];
$id = explode(',', $id); // You now have an array of IDs.
$sql = "INSERT INTO reports (reporter,stats,trn_date,itemid) VALUES ('$seller','Opened','$trn_date','$id')";
if(mysqli_query($link, $sql)){
echo $id;
echo $seller;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
} else
{
header("location:/quickshops/login.php");
}
?>
now it gives me Array in insert
Remove inside $row '' from $row['id'].
You will always get the last row's value, the reason is, you set the session in each iteration so whenever you plan to use it out of the loop, you will get the value of last iteration.
In case you want to set the array within the session, that's how you can do that:
$idsArray= array();
while($row = $result->fetch_assoc()) {
$idsArray[] = $row['id'];
}
$_SESSION["ids"] = $idsArray;
You are rewriting the value every time you go through the loop:
// loop through results
while($row = $result->fetch_assoc()) {
// overwrite session variable with the last id
$_SESSION["sup"] = $row['id'];
So if you have 10 results, the session var will be the id of the 10th row.
Without more detail on what you are trying to achieve with your result set, we can't really help much more than that. Maybe update your question with more details if this isn't enough to solvce your problem?
Update Ok so you need ALL Id's
You could make the session var an array, and when it's time to post the ID's, implode() them with a comma. Then in the receiving script, explode on a comma to get all the ids.
$_SESSION["sup"] = [];
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
// etc
}
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
And in the other script
$ids = $_POST['whatever'];
$ids = explode(',', $ids); // You now have an array of IDs.
Incidentally, since you are using a session variable, you probably don't even need to post it, and just access the session in the other script, but then I've no idea what your code is doing
I am trying to remove a string from DB by a Href in a form. Why does this not work for me? The query is right, nothing happens.
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("cms") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM pages")
or die(mysql_error());
echo "<table border='1'>";
while ($row = mysql_fetch_array($result)) {
echo "<li class='list-group-item'>";
echo $row['header'];
echo "<br/>";
echo $row['description'];
echo "<br/>";
echo "<form method='POST'><a href='delete.php?id=".$row['page_id']."'>Remove</a></form>";
echo "</li>";
}
echo "</table>";
?>
delete.php
<?php
$db = new mysqli('localhost', 'root', '', 'cms');
$id = mysqli_query($db, "SELECT page_id FROM pages");
if (isset($_POST['id'])) {
mysqli_query($db, "DELETE FROM pages WHERE id='".$_GET['id']."'");
}
?>
And it still won't work. Just sends me to a blank page with no query.
Change this :
echo "<form method='POST'><a href='delete.php?".$row['page_id']."'>Remove</a></form>";
to
echo "<form method='POST' action='delete.php'><input type='hidden' value=".$row['page_id']." name='id'/><input type='submit' value='Remove'/></form>";
And in delete.php
This :
if (isset($_GET['id'])) {
To
if (isset($_POST['id'])) {
This
mysqli_query($db, "DELETE FROM pages WHERE id='".$_GET['id']."'");
to
mysqli_query($db, "DELETE FROM pages WHERE id='".$_POST['id']."'");
I've got this script where users can see a table of projects. But only the admin can delete said projects.
$query = ("select * from projectlist");
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<tr>";
while( list($key, $value) = each($row)){
//Print value
echo "<td>" . $value . "</td>";
}
if($_SESSION['rights'] == 'administrator'){
echo "<td><i class='fa fa-times-circle-o'></i></td>";
}
echo "</tr>";
}
Every row has an id called projectid, which get called with the $query = ("select * from projectlist");.
You can see that if the admin is logged in, there will be an icon displayed. What I want it to do is that if the user clicks on the icon, the row will be deleted. I'm not really good with php, it took me a while only to get this script working.
If anyobody can help me with this, I'd appreciate it.
try this,
$query = ("select * from projectlist");
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "<tr>";
while( list($key, $value) = each($row)){
//Print value
echo "<td>" . $value . "</td><td id='del".$value."'><button></button></td>";
}
if($_SESSION['rights'] == 'administrator'){
echo "<td><i class='fa fa-times-circle-o'></i></td>";
}
echo "</tr>";
Instead of mysql_fetch_array($result, MYSQL_ASSOC) you can use mysql_fetch_array($result)
$query = ("select * from projectlist");
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
$id = $result['id']; // you unique column in table
$col1 = $result['col1']; //similarly all other columns
echo "<td>$col1</td>";
if($_SESSION['rights'] == 'administrator'){
echo "<td><a href='your_current_page.php?id=$id'><i class='fa fa-times-circle-o'></i></a></td>";
}
echo "</tr>";
}
Code To Delete Row
if(isset($_GET['id']))
{
$id= $_GET['id'];
mysql_query("delete from table where id='$id'");
echo "deleted";//whatever you want to do
}
Ajax is not complicated at all.
I prefer jQuery when I need Ajax:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.11.0.js'></script>
<script type='text/javascript'>
$(function() { // when page loded
$(".del").on("click",function(e) { // clicking on a class=del thing
e.preventDefault(); // stop any submission from the button
$.post("delete.php",{ "id":$(this).val()},function(data) {
$("#somemessageDiv").html(data);
});
});
);
</script>
using class instead of ID since ID must be unique
echo "<td>" . $value . "</td>";
if($_SESSION['rights'] == 'administrator'){
echo "<td><button class='del' value='".value."'>DELETE</button></td>";
}
Now you need delete.php to take an id and return success or error
Create a form for delete particular row.
Create one hidden field with value will be id of that row.
Create one deleterow.php and write code for delete that row from database using delete query of mysql.
if($_SESSION['rights'] == 'administrator') {
<form type='post' action ='deleterow.php'>
<input type="hidden" name='rowid' value='<?php echo $rowid ;?>' />
echo "<td><input type='submit' name="submit" value="delete" /></td>";
</form>
}
I want to add "update", "delete" and "view" in the other page button in the right side of the table rows of my php table. Please help me to add it. Here is my code:
<?php
$conn = mysqli_connect('localhost','root','','dbname');
if(mysqli_connect_errno()){
echo 'Failed to connect: '.mysqli_connect_error();
}
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo '</tr>';
}
echo '</table>';
mysqli_close($conn);
?>
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Actions</th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
Update
Delete
View
</td>";
echo '</tr>';
}
echo '</table>';
You should use jquery/Ajax for delete. It is better option.
For delete write this function: Need to add min jquery file
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function deleteRow(id)
{
$.ajax({
url: 'delete.php',
type: "POST",
data: {
'id' : id,
},
success : function(response) {
alert('Record deleted');
},
error : function() {
},
complete : function() {
}
});
}
</script>
write your delete record code in 'delete.php'.
This is one option. You can do this in more good and specific way. Everything to say here is not possible for me.
for view you can do this in two ways.
1) If you want to display in same format, redirect it on self page and put condition like.
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
else
{
$query = "SELECT * FROM table";
}
2) If you want in different format, Do same thing in view.php select only that record.
One simple thing i want to ask what is the need for view? when it is already in table above.
For Update write in your update.php :
if(isset($_POST['id'])
{
$id = $_POST['id'];
$query = "SELECT * FROM table where id=$id";
}
and set form action
<form method="post" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
fetch value of above result in input box like and also fetch id as hiiden field:
<input type='text' name='firstname' value='<?php echo $row['firstname']; ?>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>
and for update you can go like:
if(isset($_POST['firstname'] && isset($_POST['lastname'] ) // Here you can use your any required field
{
//Your update logic go here like:
$id = $_POST['id'];
$query = "UPDATE table SET firstname=$_POST['firstname'] where id=$id"; // Your whole update query.
}
i see some mistake in your code:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$results);
should be:
$query = "SELECT * FROM table";
$results = mysqli_query($conn,$query);
try this
echo '<table border="1">';
echo '<tr>';
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th></th>";
echo '</tr>';
while($row=mysqli_fetch_array($results)){
echo '<tr>';
echo '<td>'.$row['Firstname'].'</td>';
echo '<td>'.$row['Lastname'].'</td>';
echo "<td>
<input type='submit' value='update'>
<input type='submit' value='delete'>
<input type='submit' value='view'>
</td>";
echo '</tr>';
}
echo '</table>';
Try this functions:
<?php
Class Db {
protected $connection;
public function __construct() {
$this->connection = $connection;
}
function insert($table,array $data) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$fields.= $col.",";
}
foreach($data as $col => $value) {
$values.= "'".replace_str($value)."',";
}
$fields = substr($fields,0,-1);
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"insert into ".$table."(".$fields.") values(".$values.")")) {
HandleDBError("Error inserting data to the table\query:$query");
}
return $query;
}
function update($table, array $data, $where) {
$fields = '';$values = '';
foreach($data as $col => $value) {
$values.= $col."='".replace_str($value)."',";
}
$values = substr($values,0,-1);
if(!$query = mysqli_query($this->connection,"update ".$table." set ".$values." where ".$where)) {
HandleDBError("Error updating data to the table\query:$query");
}
return $query;
}
function delete($table, $where = '') {
if ($where)
return mysqli_query($this->connection,"delete from ".$table." where ".$where);
return mysqli_query($this->connection,"delete from ".$table);
}
function get($strQuery) {
if(!$query = mysqli_query($this->connection,$strQuery)) {
HandleDBError("Error inserting data to the table\query:$query");
}
$data = [];
while($row = mysqli_fetch_assoc($query)) {
$data[] = $row;
}
return $data;
}
}
?>
I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().