when specific user login it will display what he has books.. and inside each book delete button .. i want delete row when i clicked on delete button ... but when i clicked on delete button it reload the page please i need help
this getbooks function
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
//SELECT loginUser.username, Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username="loay";
$query = "SELECT Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
//,':start' => $start, ':limit' => $limit
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<form method='POST'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' name='delete' value='Delete' method='post' >" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</form";
if(isset($_POST['delete'])){
die("SS");
}
}
I made the delete functionality using jquery and ajax.
Above your form code add:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function deleteBook(b) {
$(document).ready(function() {
var book = $(b).parent('td').prev('td').html();
if(confirm("Are you sure you want to delete book - "+book+"?") == false){
return;
}
var ids = $(b).attr('id').substr(6).split('-');
var book_id_to_delete = ids[0];
var user_id = ids[1];
//alert("book_id is " + book_id_to_delete + ", user_id is " + user_id);
$.ajax({
type: "POST",
url: "" + "deletebook.php",
data: {
'book_id': book_id_to_delete,
'user_id': user_id,
submit: 'submit',
},
success: function(res) {
if (res == "deleted") {
$(b).closest('tr').remove();
} else {
alert(res);
}
}
});
});
}
</script>
In getBooks() function, I added id attribute (containing book and user ids) in delete button so our js code will know which books of a user should be deleted.
Replace your getBooks() function with:
<?php
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
$query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "";
if(isset($_POST['delete'])){
die("SS");
}
}
?>
Create a class function that handles user's book deletion.
In your User class in User.php, add the following function:
public function deleteBook($book_id, $user_id)
{
$stmt = $this->db->prepare("DELETE FROM userBook WHERE book_id = :book_id AND user_id = :user_id");
$stmt->bindValue(":book_id", $book_id);
$stmt->bindValue(":user_id", $user_id);
return $stmt->execute();
}
The below code will be executed by via ajax so that the chosen book will be deleted from database.
Create a file named - deletebook.php
And add this code:
<?php
include_once('User.php');
if(isset($_POST['submit'])){
$object = new User();
if($object->deleteBook($_POST['book_id'], $_POST['user_id'])){
die('deleted');
}
else {
die("fail");
}
}
?>
Related
I want to access this function and change the variable from the URL how can i Do that . i try this to echo something and its work
http://test.local/UUser.php
<?php echo '<p>'. 'Hello Husam' . '</p>'; ?>
but how i can access this function inside UUser.php .
For example i need to change $order = "ASC" to $order = "DESC".
public function getBooks($start = 0, $limit = 2, $order = "ASC")
{
$sql_start = $start * $limit;
$sql_limit = $limit;
$sql_order_by = $order;
$query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username ORDER BY Library.nameOfBook $sql_order_by LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
]);
$result = $statment->fetchAll();
echo "<table id='myTable' border='1'>
<tr>
<th><a id='sorter' href='#'>Books</a></th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "";
return count($result);
echo '<p>'. 'Hello Husam' . '</p>';
}
my case: after user login ... it will display in table what the book he has ... i added delete link in side each book ... for example i clicked on the link delete in side Math book i want to delete it .. how i can do that please.
i get the books but when i click on delete link nothing happen.
this function display books when user login
public function getBooks($start = 0, $limit = 2)
{
$sql_start = $start * $limit;
$sql_limit = $limit;
//SELECT loginUser.username, Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username="loay";
$query = "SELECT Library.nameOfBook FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
//,':start' => $start, ':limit' => $limit
]);
$result = $statment->fetchAll();
echo "<table border='1'>
<tr>
<th>Books</th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' name='delete' value='Delete' method='post' " . "</td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['delete'])){
deleteBooks($id1, $id2);
}
}
And this function deleteBooks
public function deleteBooks($id1, $id2)
{
$id1 = $_GET['user_id'];
$id2 = $_GET['book_id'];
$query = "Delete FROM userBook WHERE userBook.user_id=id1 AND userBook.book_id =id2";
$statment = $this->db->prepare($query);
$statment->execute([$id1, $id2]);
$result = $statment->rowCount();
$this->deleteBooks= ($result == "1");
return $this->deleteBooks;
}
First of all you have to add book.id on the link
echo "Delete";
After you click yes you will have a get request.
Not sure where delete function is called after but you can pass $_GET
parameter on it deleteBooks($_GET['id]).
and the function it self
public function deleteBooks($book_id) {
$query = "Delete FROM userBook WHERE userBook.user_id=? AND userBook.book_id =?";
$statment = $this->db->prepare($query);
$statment->bind_param("ss", $user_id, $book_id);
$statment->execute();
//
}
You should store user_id on a session i guess.
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");
?>
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 the following page, which works with MySQL, PHP and AJAX
if I click a NAME (id="orderN") it gives me back the result of the consult, which orders the names descending or ascending.
Is there any way that if you refresh(F5) the page, the result is saved as it was before closing, (ASC or DESC)?
I heard about cookies and HTML5 Storage, which is better than cookies.
if you can do it with either of them, let me know please
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
</head>
<body>
<table>
<tr><th>Name</th></tr>
</table>
<?
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "SELECT NAME
FROM STUDENTS";
$query = mysql_query($consult);
echo "<div id='DivConsult'><table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['NAME'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
<script>
$(document).ready(function() {
var contName = 0;
$('#orderN').click(function() {
contName++;
if (contName % 2 !== 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=ASC",
success: function(data) {
$('#DivConsult').html(data);
}});
}
if (contName % 2 == 0) {
$.ajax({
type: "POST",
url: "reOrder.php",
data: "tipOrder=DESC",
success: function(data) {
//alert(data);
$('#DivConsult').html(data);
}});
}
});
});
</script>
</body>
AJAX:
<?php
$Conn = mysql_pconnect('localhost', 'root', '1234') or die('Error"');
mysql_select_db('DATA');
$consult = "";
if (isset($_POST['tipOrder'])) {
if ($_POST['tipOrder'] == 'ASC') {
$consult = "SELECT NOMBRE
FROM STUDENTS ORDER BY NAME ASC";
}
if ($_POST['tipOrder'] == 'DESC') {
$consult = "SELECT NAME
FROM STUDENTS ORDER BY NAME DESC";
}}`
$query = mysql_query($consult);
echo "<table>";
while ($table = mysql_fetch_assoc($query)) {
echo "<tr>";
echo "<td>" . $table['Name'] . "</td>";
echo "</tr> ";}
echo "</table>";
?>
You can do it but just saving a container (any div, span or even body) as
localStorage.variableName = document.getElementById("id");
And then you can access by using
if(Storage!=="undefined" && localStorage.variableName!=null)
now you can set value as
container.val = localStorage.variableName