Multiple deletion & edit of data in PHP - php

When I was trying to delete one data from the database but it would either delete the whole data in the database; it also the same problem for edit.
this code is for delete a user that will show a prompt when deleting a user:
<div id="delete_user<?php echo $id; ?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="alert alert-danger">Are you Sure yuo want to Delete this Data?</div>
</div>
<div class="modal-footer">
<a class="btn btn-danger" href="delete_user.php<?php echo '?id='.$id; ?>"><i class="icon-check"></i> Yes</a>
<button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-remove icon-large"></i> Close</button>
</div>
</div>
and this code here below is the actual delete from the database
<?php
include('dbcon.php');
$id=$_GET['id'];
mysql_query("delete from users where user_id='$id'") or die(mysql_error());
header('location:users.php');
?>

First check if value is set in $_GET['id'] then perform your action.
<?php
include('dbcon.php');
if(isset($_GET['id'])){
$id=mysql_real_escape_string($_GET['id']);
mysql_query("delete from users where user_id='$id'") or die(mysql_error());
}
header('location:users.php');
?>

your code seem to be okay, just check the debug the id value.
But still i strongly believe for such action don't pass id's in GET method. Use POST in ajax.
Below is the code with the ajax using POST method to pass the id to delete_user.php page
<div id="delete_user<?php echo $id; ?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="alert alert-danger">Are you Sure yuo want to Delete this Data?</div>
</div>
<div class="modal-footer">
<a class="btn btn-danger" onclick="deleteUser(<?php echo $id; ?>)" href="javascript:void(0)"> <i class="icon-check"></i> Yes</a>
<button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-remove icon-large"></i> Close</button>
</div>
</div>
Below the jquery ajax part
function deletUser(id) {
$.ajax({
url: 'delete_user.php',
method: 'POST',
data: {"id" : id},
success: function(data) {
// on success alter the div structure.....
}
});
}
below is code for your delete_user.php page
include('dbcon.php');
if(isset($_POST['id']) && $_POST['id'] != ''){
$id = (int)$_POST['id'];
mysql_query("delete from users where user_id=$id") or die(mysql_error());
}
header('location:users.php');

Related

How to delete specific image from bootstrap modal using ajax?

I want to delete a specific image when user selected the red delete icon which is in the right side of each image .
screenshot-
ss after user click on deleted icon this shows up-
My php codes from where i took the img_id to delete and displaying all images-
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ON img_info.estate_infos_id = estate_infos.id where img_info.estate_infos_id = $mdoalid";
$stmt=$dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($datas as $key => $data)
{ $pic = $data['image'];
$a=$data['img_id'];
?>
<img src="../<?php echo $pic ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delimg<?php echo $a; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i></a>
<?php echo $a?> // displays the id of each image displayed (wont display in production)
My modal code -
<!-- Modal -->
<div class="modal fade" id="delimg<?php echo $data['img_id']; ?>" tabindex="-1" aria-labelledby="delimglabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delimglabel">Delete Image</h5>
</div>
<div class="modal-body">
Are you sure you want to delete the image?
<?php echo $data['img_id'] ?>
</div>
<div class="modal-footer">
<button type="button" class="delbtn btn btn-sm btn-secondary text-white btn-danger">Delete</button>
//Here "delbtn" will trigger the ajax delete image from database
</div>
</div>
</div>
</div>
<?php } ?>
My ajax code which is i need to fix -
<script type="text/javascript">
$(document).ready(function() {
$(".delbtn").on("click", function(e) {
e.preventDefault();
alert("Working");
jQuery.ajax({
type: "POST",
url: "image-del.php",
data: < ? php echo $data['img_id'] ? > ,
success: function(response) {
alert('Image Deleted !');
},
error: function(response) {
alert('Image NOT Deleted !')
}
});
});
});
</script>
My mysql pdo code to delete image by id from database , this file name is "image-del.php"-
<?php
include_once 'connection.php';
if (isset($_POST['delbtn'])) {
$img_id = $_POST['img_id'];
$sql = "DELETE FROM img_info WHERE img_id=:img_id";
$stmt = $dbcon->prepare($sql);
$stmt->bindparam(':img_id', $img_id);
$stmt->execute();
?>
So, how can make the specific image get deleted by ajax properly?
-Thank you in advance
This is actually a two step process. Here's the idea:
First, as usual, render all the images along with their button to open the modal (the delete button to open the modal).
<?php foreach ($datas as $key => $data): ?>
<img src="../<?php echo $data['image'] ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delete-modal" data-imgid="<?php echo $data['img_id']; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i>
</a>
<?php endforeach; ?>
You do not need to serve the HTML modal inside the loop. You only need one modal. You don't need each modal for each image.
So just change it to this and put it in the bottom of the page:
<div class="modal fade" id="delete-modal" tabindex="-1" aria-labelledby="delimglabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delimglabel">Delete Image</h5>
</div>
<div class="modal-body">Are you sure you want to delete the image?</div>
<div class="modal-footer">
<button type="button" class="delbtn btn btn-sm btn-secondary text-white btn-danger" data-delete-imgid="">Delete</button>
</div>
</div>
</div>
</div>
After that, you need to trigger an event when the modal opens, get the image id and put it in the data attribute, so that it is used and can be accessed when you make the final request to delete it and send it to the server:
$('#delete-modal').on('show.bs.modal', function(e) { // when the delete modal opens
var imageId = $(e.relatedTarget).data('imgid'); // get the image id
$(e.currentTarget).find('.delbtn').attr('data-delete-imgid', imageId); // and put it in the delete button that calls the AJAX
});
Then like I said above the comments, don't echo the PHP image id in there. Use the ID that you applied in the button:
$(".delbtn").on("click", function(e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "image-del.php",
data: { delbtn: $(this).attr('data-delete-imgid') }
success: function(response) {
alert('Image Deleted !');
},
error: function(response) {
alert('Image NOT Deleted !')
}
});
});
This should serve as a general idea on how to pass the ID from the delete button to the modal, then finally to the server.

how to get the correct value from json (php)?

update_modal(bootstrap)
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit:</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="body">
<input type="text" class="form-control" placeholder="product_title" id="title">
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="login.php">Update</a>
</div>
</div>
</div>
</div>
trigger the update_modal(bootstrap)
<td>
<a data-toggle='modal' data-target='#updateModal'>
<button class='btn btn-success' id='edit' data-id='$product_no'>Edit</button>
</a>
</td>
js
<script>
$(document).ready(function() {
$(document).on('click','#edit',function () {
let id=$(this).attr('data-id');
// console.log(id);
$.ajax({
url:'get_record.php',
method:'post',
data:{
p_no:id
},
dataType:'JSON',
success:function (data) {
// $('#body').html(data);
console.log(data[0]);
console.log(data[1]);
console.log(data[2]);
}
});
});
})
</script>
get_record.php
<?php
include ("db.php");
global $conn;
if (isset($_POST['p_no'])){
$p_no=$_POST['p_no'];
$query="select * from products where p_no='$p_no'";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result)){
$user_data=' ';
$user_data [0]=$row['product_title'];
$user_data [1]=$row['date'];
$user_data [2]=$row['product_price'];
// echo $pro_title;
}
echo json_encode($user_data);
}
My problem is when I click the edit button, the update_modal displays successfully, but it doesn't get correct values from my database. I click F12 on my chrome and it tested like this photo
You are initializing $user_data in get_record.php as a string: $user_data = ' ';
Try initializing that variable as an array instead: $user_data = [];
Because you initialize $user_data as a string, setting $user_data[0] only sets the first character of the string to the first character of the value $row['product_title'].
EDIT: As noted in the comments, you are also opening yourself up to SQL injection attacks by inserting posted data directly into your SQL here:
$p_no=$_POST['p_no'];
$query="select * from products where p_no='$p_no'"
You should escape all user inputs before using them in a query. One way to do that for MySQL in PHP:
$p_no=mysqli_real_escape_string($_POST['p_no']);
$query="select * from products where p_no='$p_no'"
Using prepared statements would be ideal.

Codeigniter - Show Information in Modal Window

I have a Modal Window. It is working good with javascript. I tried something myself but I can't show any information of Customer in Modal Window. When clicking on the info button, I want to show the Customer's information. How can I show any customer information in Modal Window?
Controller:
public function index()
{
$viewData['countries'] = $this->db->get("country")->row();
$viewData['customers'] = $this->customer_model->get_all();
$this->lang->load('content', $this->session->userdata('people_lang'));
$this->load->view('customers', $viewData);
}
public function getInfo(){
$cusId = $this->input->post('cusId');
$viewData['customers'] = $this->db->where("cusId", $cusId)->get("customer")->row();
$this->load->view('customers/getInfo', $viewData);
}
This Ajax Code:
<script type="text/javascript">
function showCustomers(str){
$.ajax({
type: "POST",
data: { cusId: str },
url: "<?=base_url('customers/getInfo');?>",
success: function(data) {
$('#divInfo').html(data);
}
});
}
</script>
This Modal:
<!-- Modal -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal Tittle</h4>
</div>
<div class="modal-body">
<div id="divInfo"></div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
<button class="btn btn-warning" type="button"> Confirm</button>
</div>
</div>
</div>
</div>
<!-- modal -->
This View:
<a data-toggle="modal" href="#myModal3"><button class="btn btn-primary btn-xs" onclick="showCustomers(this.id);" id="<?php echo $customers->cusId; ?>"><i class="fa fa-eye"></i></button>
But This is not working. Where is I do mistake?
I think you can do this by adding a couple of lines.
Note* Code is not tested, i can practically painting the idea to solve this.
In the index function of your controller
public function index(){
$viewData['countries'] = $this->db->get("country")->row();
$viewData['customers'] = $this->customer_model->get_all();
//**new line
// Assuming you already have method in your Model to get customer by id
// Check if there's a GET request of 'customerID' then assign to the $viewDataByID array the data from the model, else nothing.
$viewDataByID['customersById'] = (isset($_GET['cusomterID'])) ? $this->customer_model->get_by_id($id) : '';
//Then you'll have to update the variable sent to the view by storing both in one array
$allData['viewData']= $viewData;
$allData['viewDataByID'] = $viewDataByID;
$this->lang->load('content', $this->session->userdata('people_lang'));
$this->load->view('customers', $allData);// $allData get sent to the view
}
In your modal you can sent the request
Please update the variables in the view. You can do a print_r($allData) or var_dump($allData) to clearly see the data tree and how you can make use of them.
Alternatively if you do not want to use your index for this, you can create another function within your controller to handle the customer by id, json_encode the result and then use jQuery to get the data.
Hope this helps.
Here's one way you could do it:
<!--modify button to include an onclick element, pass a value to it-->
<button class="btn btn-primary btn-xs" id="info_modal" onclick="show_modal('<?=$customer_name;?>')"><i class="fa fa-eye"></i></button>
You could modify your modal to have some id's in anticipation of your data:
<div class="modal fade" id="info_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
....
<div class="modal-body">
View File List According to Customer ID.
<div id="customer_name"></div>
</div>
Then in your script (if using jquery):
//add passed string to the modal and then display it
function show_modal(customer_name){
$("#customer_name").html(customer_name);
$("#info_modal").modal('show');
}
I answered myself this question.
<td data-title="Edit" align="center"><button class="btn btn-primary btn-xs"><i class="fa fa-pencil"></i></button> <a data-toggle="modal" href="#<?php echo $customer->cusId; ?>"><button class="btn btn-primary btn-xs"><i class="fa fa-eye"></i></button></a></td>
I edit a href like that href="#<?php echo $customer->cusId; ?>
Afterthat I just write this code on modal top:
<?php foreach ($customers as $get) { ?>
<div class="modal fade" id="<?php echo $get->cusId; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<?php } ?>
I edit id like that id="#<?php echo $get->cusId; ?>
It works better now!

pass the value of mysql to bootstrap modal

i want to select from a list of data and display the result of the selected data in a modal popup. i just can't figure out how to pass the id to the popup so i can display the result. HELP!!
<td> <button class="btn btn-primary " data-toggle="modal" data-id="<?php $id= $row['id'] ?>" data-target="#myModal" <?php echo"id=$row[id]'";?> >
View Details
</button>
</td>
the modal popup
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Requisition Details</h4>
</div>
<div class="modal-body">
<?php
$id = $_GET['id'];
include('mysql_connect.php');
$query11 = mysql_query ("select * from p_requisition where id = '$id' ") or die(mysql_error());
$rows= mysql_fetch_array($query11);
echo $rows['details'];
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
Firstly, add class to button may be get-data,
then in jquery,
$(document).ready(function() {
$(document).on("click",".get-data"function(){
var val = $(this).attr("data-id");
$.ajax({
url: "path to ajax file",
type: "POST",
dataType: "HTML",
async: false,
success: function(data) {
$('.modal-body').html(data);
}
});
});
});
in ajax file,write query to fetch data from mysql, manipulate the data and display in popup.
ajax.php
<?php
$id = $_POST['id'];
include('mysql_connect.php');
$query11 = mysql_query ("select * from p_requisition where id = '$id' ") or die(mysql_error());
$rows= mysql_fetch_array($query11);
echo $rows['details'];// here you need to manipulate the database data with html and pass it on to popup.
?>
use like
<td>
<button class="btn btn-primary" onclick='openModel(<?php echo"id=$row[id]";?>') >View Details</button>
</td>
open your model like
<script>
function openModel(modelId,rowId){
$('#'+modelId).model('open');
//Ajax call to get data for speciefic id
}
</script>
I think you should use ajax call, when open modal like this:
Your modal:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Requisition Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
Your button:
<button class="btn btn-primary " data-toggle="modal" data-id="<?php echo $row['id'] ?>" data-target="#myModal" id="myButton">
View Details
</button>
When click the button, show the modal:
$('#myButton').click(function() {
$('#myModal').modal('show')
});
If the modal shown, you pass the data with ajax
$('#myModal').on('shown.bs.modal', function(e) {
$.ajax({
method: "POST",
url: "getData.php",
data: {
dataId: $('#myModal').attr('data-id')
},
success: function(data) {
data = jQuery.parseJSON(data);
$('.modal-body', '#myModal').html(data);
}
});
})
Your getData.php like this
<?php
//dataId comes from ajax (POST)
$id = filter_input(INPUT_POST, 'dataId');
include('mysql_connect.php');
$query11 = mysql_query("select * from p_requisition where id = '$id' ") or die(mysql_error());
$rows = mysql_fetch_array($query11);
//you should use json_encode, and you can parse when get back data in ajax
echo json_encode($rows['details']);

how can i pass variable to php after open modal

Hi I want to open modal after I click on button. But I want to display different content on the basis on which button I click.
So in html I have:
<h1>article1</h1>
<div class="btnComment">
<button class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Comment button 1</button>
</div>
<h1>article2</h1>
<div class="btnComment">
<button class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Comment button 2</button>
</div>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Comments</h4>
</div>
<div class="modal-body">
<?php
mysql_query("set names 'utf8'");
$selectConf = mysql_query("SELECT * FROM e_comments WHERE article='".$article."'");
$count = 0;
if($selectConf){
while ($row = mysql_fetch_array($selectConf)) {
$text = $row['text'];
echo $text;
}
}
?>
</div>
</div>
</div>
</div>
So how can I know in modal which button was clicked? And how I can pass some variable throw it? I want to show comments of article. So I need to pass id of article and select all comments where is id of article same.
There's a direct example on the bootstrap page at http://getbootstrap.com/javascript/#modals-related-target. Here is the equivalent code for your dialog
<script>
$(document).ready(function () {
$('.bs-example-modal-lg').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
alert(button.html())
})
})
</script>
edit : you'd have to change the alert() part to whatever if else logic you want.

Categories