Deleting row from mysql using jquery and php - javascript

I want to create delete feature using function and jquery
My jquery works and show messages but nothing happen "Nothing Deleted"
Jquery Code
<script type="text/javascript">
$(".remove").click(function(){
var id = $(this).parents("tr").attr("id");
if(confirm('Are you sure to remove this record?'))
{
$.ajax({
url: 'delete.php',
type: 'GET',
data: {id: id},
error: function() {
alert('Something is wrong');
},
success: function(data) {
$("#"+id).remove();
alert("Record removed successfully");
}
});
}
});
PHP Function Code
function delete($table,$id) {
global $connect;
mysqli_query($connect, "DELETE FROM `$table` WHERE `id` = $id ");
}
Delete.php Code
include ('function.php');
$id = $_GET['id'];
$table = 'msg';
delete($table,$id);
HTML Code
<table class="table table-striped" style="background-color: #ffffff;">
<tr>
<th>ID</th>
<th>From</th>
<th>Title</th>
<th>Date</th>
<th>Action</th>
</tr>
<?php
$i = '1';
$username = $user_data['username'];
$query = "SELECT * FROM msg WHERE `go_to` = '$username' Order by id";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['come_from']; ?></td>
<td>
<a href="read_message/<?php echo $row['id']; ?>"><?php if(count_msg_not_opened($username, $row['id']) > '0')
{
echo $row['title'];
}
else
{
echo '<b>' . $row['title'] . '</b>';
} ?></a></td>
<td><?php echo $row['date']; ?></td>
<td>
<button class="btn btn-danger btn-sm remove">Delete</button>
</td>
</tr>
<?php } ?>
</table>
I also include "jquery.min.js"
When I press "Delete" bottom this message appears "Are you sure to remove this record?"
I pressed "Yes" then this message appears "Record removed successfully", but nothing was deleted.
I don't know where the problem is.

You forgot to add the id attribute to the <tr>
<tr id="<?php echo $row['id']; ?>">
You should also add error checking and prepared statements to your PHP code.

Are you sure that you have connected your PHP-code to your SQL-database?
function delete($table,$id) {
global $connect;
mysqli_query($connect, "DELETE FROM `$table` WHERE `id` = $id ");
}
The code above is relying on a connection already existing within your PHP-file. See this to find out how to apply a connection.

Related

PHP & MySQL & JS editable table won't update records

So I'm trying to use a table to update some records in my database but each time I click on update it won't work and it won't do anything. A part of the code below was found in an another topic but it was incomplete so I added some other things.
Js script
$(function(){
$("#loading").hide();
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
This is the table fetching the rows from the database, however everything works besides updating.
HTML & PHP
<form method="post" action="update.php">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-striped table-dark">
<tr bgcolor="#df4662" style="color:#FFFFFF;">
<td>ID</td>
<td>Nickname</td>
<td>Name</td>
<td>Rank</td>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td contenteditable="true" id="id:<?php echo $row["id"]; ?>"><?php echo $row["id"]; ?></td>
<td contenteditable="true" id="username:<?php echo $row["username"]; ?>"><?php echo $row["username"]; ?></td>
<td contenteditable="true" id="name:<?php echo $row["steamid"]; ?>"><?php echo $row["steamid"]; ?></td>
<td contenteditable="true" id="ranks:<?php echo $row["ranks"]; ?>"><?php echo $row["ranks"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</form>
After a few errors I've been able to have a clean error_logs, but now I don't get any error even after pressing the update button.
update.php
<?php
include '../database.php'
?>
<?php
if(!empty($_POST))
{
foreach($_POST as $field_name => $val)
{
$field_id = strip_tags(trim($field_name));
$split_data = explode(':', $field_id);
$id = $split_data[1];
$field_name = $split_data[0];
if(!empty($id) && !empty($field_name) && !empty($val))
{
$affected_rows = mysqli_query($mysqli,"UPDATE users SET $field_name = '$val' WHERE id = $id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Request";
}
}
}
else {
echo "Invalid Requests";
}
?>
EDIT: Thanking Sam now the problem is just that the record won't update at all

Delete from database using javascript

I have a page containing a database table with all the rows and columns.
What I am trying to do is to select all the rows I want and then delete them when I click on the button.
This is what I've done so far in the table.php page:
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<button id="button_apaga" type="button" onclick="delete()" > DELETE </button>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td><input type="checkbox" name="check" id="checkbox" /></td>
</tr>
<?php } ?>
</table>
<?php }
else{
echo "0 resultados";
} ?>
JavaScript Page (home.js):
function delete(id){
var check = document.getElementById('checkbox');
if(check.checked) {
// sql query
}
My question is how can I do que sql query considering it's in a different page. Can I just open php and put the query inside?
Also how can I receive all the IDs from the selected rows to the function?
Thank you in advance.
One approach would be to use AJAX. For the purpose of condensing the code, I'm going to also incorporate jQuery into this solution. I am also going to change your checkbox to an individual button link for the sake of making this a bit less code. A solution to delete multiple at the same time could work similarly to this, but since you're using AJAX most likely this is going to be easier for your users.
Modify table.php
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row" class="palavras_row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1"></script>
<script type="text/javascript">
(function($) {
$(document).on('click', '.palavras_row a.palavras_delete', function() {
var _id = $(this).attr('data-id');
var _row = $(this).parent().parent();
$.ajax({
url: 'delete.php',
data: {
idpalavras: _id
},
type: 'POST',
dataType: 'json',
success: function(__resp) {
if (__resp.success) {
_row.remove(); // Deletes the row from the table
}
}
});
});
})(jQuery);
</script>
Create a new file in the same folder as your table.php and name it delete.php
<?php
$idpalavras = filter_input(INPUT_POST, 'idpalavras', FILTER_SANITIZE_NUMBER_INT);
$success = false;
if ($idpalavras) {
include "config.php"; //connection to database
$funcao="delete from palavras where idpalavras = " . $idpalavras;
$result=mysqli_query($link, $funcao);
$success = true;
}
header('Content-Type: application/json');
echo json_encode(array('success' => $success));
The solution above sends a simple command to your PHP backend where the delete query can be run by PHP. You cannot run a mysql command directly from javascript since that is frontend code.
This code is a functional solution, but it is abbreviated; a more complete solution would have more detailed handling of potential errors (either via AJAX or processing your delete query). It should also have some security on your delete.php to make sure unauthorized users aren't able to delete records without the proper permission to do so.

Adding and accessing buttons IDs in a PHP-generated table

I have problems with my php that generates a table, requests data from a SQL database, and stores data in the table.
The first cell of each row in the table contains a dropdown button which links to a delete.php script that deletes the row. It also links to a modif.php script used to modify the row's cells.
My problem is that i need to access the dropdown buttons with IDs to know which row to delete.
And i don't really know how to link my dropdown buttons with IDs and access them in my scripts.
Here's the code :
<?php
$con=mysqli_connect("localhost","root","icare","icare1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM magasin");
echo "<table border='1'>
<tr>
<th>code</th>
<th>ip</th>
<th>ads</th>
<th>region</th>
<th>adress</th>
<th>name</th>
<th>email</th>
<th>number</th>
<th>gtc</th>
<th>date</th>
</tr>";
$indexB = array();
$i = 0;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>
<div class='dropdown'>
<button id=$indexB[$i] class='dropbtn'>▶</button>
<div class='dropdown-content'>
<a href='modif.php'>Modifier</a>
<a href='delete.php'>Supprimer</a>
</div>
".$row['code']."
</div>
</td>";
echo "<td><div>" . $row['ip'] . "</div></td>";
echo "<td><div>" . $row['ads'] . "</div></td>";
echo "<td><div>" . $row['region'] . "</div></td>";
echo "<td><div>" . $row['adress'] . "</div></td>";
echo "<td><div>" . $row['name'] . "</div></td>";
echo "<td><div>" . $row['email'] . "</div></td>";
echo "<td><div>" . $row['number'] . "</div></td>";
echo "<td><div>" . $row['gtc'] . "</div></td>";
echo "<td><div>" . $row['date'] . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
mysqli_close($con);
?>
And here is the delete.php :
<?php
$connection = mysqli_connect("localhost", "root", "icare", "icare1");
if($connection === false){
die("Connection failed " . mysqli_connect_error());
};
//$id =
$sql = "DELETE FROM magasin WHERE Code=".$id;
//$result = mysqli_query($connection,$sql);
if(mysqli_query($connection, $sql)){
echo "Done !";
} else{
echo "Failed : $sql. " . mysqli_error($connection);
}
mysqli_close($connection);
?>
I started an indexB[] to store the dropdowns IDs but i'm not sure that i'm doing it right.
In the end I want to link my buttons to the code attribute and then delete the row with my sql query using the code attribute.
I'm new to this so ... sorry if i did or ask something plain stupid.
UPDATE :
To mikrafizik :
I tried your answer but it doesn't work. I only get "1">Supprimer". It seemsi have a problem with the href but i just can't find why.
I don't know what i forgot, so if you see something wrong :
<?php
$con=mysqli_connect("localhost","root","icare","icare1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM magasin");
echo "<table border='1'>
<tr>
<th>Code</th>
<th>Adresse IP</th>
<th>Adresse ADS</th>
<th>Région</th>
<th>Adresse</th>
<th>Nom du directeur</th>
<th>Mail</th>
<th>Téléphone</th>
<th>GTC</th>
<th>Date d'installation</th>
</tr>";
$data = mysqli_fetch_array($result);
?>
<table>
<?php foreach ($data as $key => $row):?>
<tr>
<td>
<div class='dropdown-content'>
<button class='dropbtn'>▶</button>
<!-- Modifier -->
Supprimer
</div>
</td>
<td><div><?php echo $row['AdresseIP'];?></div></td>
<td><div><?php echo $row['AdresseADS'];?></div></td>
<td><div><?php echo $row['Region'];?></div></td>
<td><div><?php echo $row['Adresse'];?></div></td>
<td><div><?php echo $row['NomDirecteur'];?></div></td>
<td><div><?php echo $row['Mail'];?></div></td>
<td><div><?php echo $row['Tel'];?></div></td>
<td><div><?php echo $row['Gtc'];?></div></td>
<td><div><?php echo $row['DateInstall'];?></td>
</tr>
<?php endforeach; ?>
</table>
<?mysqli_close($con);?>
delete.php :
<?php
$connection = mysqli_connect("localhost", "root", "icare", "icare1");
if($connection === false){
die("Connexion échouée " . mysqli_connect_error());
};
$id = $_GET['id'];
$sql = "DELETE FROM magasin WHERE Code=".$id;
$result = mysqli_query($connection,$sql);
if($result){
echo "Enregistrement réussi !";
} else{
echo "Enregistrement échoué : $sql. " . mysqli_error($connection);
}
mysqli_close($connection);
?>
At first, divide query and form building like that
$data = mysqli_fetch_array($result)
then
<?php foreach ($data as $key => $row): ?>
<tr>
<td>
<div class='dropdown-content'>
<a href='modif.php?id=<?=$row['id']?>'>Modifier</a>
<a href='delete.php?id=<?=$row['id']?>'>Supprimer</a>
</div>
</td>
</tr>
<?php endforeach ?>
And in your modif.php
$id = $_GET['id'];
(Concerns Flumble_'s answer, that I can't comment because of my low rep)
Maybe the <?= ?> are the problem. Try replacing them with <?php ?>
UPDATE :
You should also never use short open tags (<? ?>) : See the answer to this question.
Also, when you write <?php $row['id'] ?>, you are not printing the value. You must write <?php echo $row['id']; ?>.
The same thing applies with short open tags (but not with the <?= syntax).
Hope this helps further. I will continue reviewing your code.
UPDATE 2 :
Alright I think I got it.
mysqli_fetch_array returns a row, not the entire result set. So you have to loop through the rows until mysqli_fetch_array returns NULL :
while($data = mysqli_fetch_array($result)) {
?>
<tr>
<!-- ... -->
</tr>
<?php
}

PHP Dynamic Table with edit/delete links to open a popup

I built a form where user can enter Country Name and Country's Dialing Code. That form submits to Database and then I pull the record from database in a Table showing Country Name, Country's Dialing Code and two more options of EDIT and DELETE (having GET URL Link e.g. www.abc.com/country.php?country=Pakistan)
I want to add AJAX to it so that when user clicks on EDIT or DELETE link a relevant pop-up open with data from GET URL.
Following is my Dynamic Table in PHP
<div>
<?php
$q = "SELECT * FROM country";
$result = mysqli_query($conn, $q);
echo "<table border=2><tr><th>Country Name</th><th>Country Code</th><th></th><th></th></tr>";
while($a = mysqli_fetch_array($result)) {
$cn = $a['cname'];
$cc = $a['ccode'];
?>
<tr>
<td><?php echo $cn ?></td> <td><?php echo $cc; ?></td>
<script type="text/javascript">
var a = 0;
var cname = new Array("<?php echo $cn;?>");
a++;
</script>
<td>
<a href='#' onclick='javascript:editWin(cname[a]); return(false);'>Edit</a>
</td>
<td id="<?php echo $cn;?>">
<a href='#' onclick='javascript:delWin(); return(false);'>Remove</a>
</td>
</tr>
<?php
}
?>
</div>
My external Javascript Function is as follows
function editWin(e) {
window.open('edit.php?country='+e,'','height=400, width=600, top=100,
left=400, scrollable=no, menubar=no', '');
};
In GET Url it says undefined when popup window opens.
I got the solution
My PHP Code is as follows
<div> <?php
$q = "SELECT * FROM country";
$result = mysqli_query($conn, $q);
echo "<table border=2><tr><th>Country Name</th><th>Country Code</th><th></th><th></th></tr>";
while($a = mysqli_fetch_array($result)) {
$cn = $a['cname'];
$cc = $a['ccode'];
?>
<tr>
<td><?php echo $cn ?></td> <td><?php echo $cc; ?></td>
<td><a href='#' id="<?php echo $cn; ?>" onclick='javascript:editWin(this.id); return(false);'>Edit</a></td>
<td><a href='#' id="<?php echo $cn; ?>" onclick='javascript:delWin(this.id); return(false);'>Remove</a></td></tr>
<?php
}
?>
</div>
and my Javascript is as follows
function editWin(e) {
window.open('edit.php?country='+e,'','height=400, width=600, top=100, left=400, scrollable=no, menubar=no', '');
};
function delWin(e) {
window.open('del.php?country='+e,'','height=400, width=600, top=100, left=400, scrollable=no, menubar=no', '');
};

integrate an image with link

Well, I think it might be easier to explain my question by the image below:
As can be seen in the picture, if user select "By title", a textbox will be appeared where user can write a movie title (I also used jQuery auto-completion for this textbox). Then, if user click on the button "Movies by this title", a new window will be shown where there is a list of movies containing the term in the textbox.
My question:
I would like to integrate a small image of each of these movies beside them (and maybe some other information like movie year, genre..) like what amazon does (Please see here). I used renderitem for the auto-complete part and it works fine, but actually I have no idea how to do the same in the new window.. I would be very grateful if someone can help me.
This is my code:
<div id="m_scents" class="field">
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" placeholder="Enter movie titles here" />
<input type="button" value="Movies by this title" id="btnMove" style="display:none;"/>
</div>
<script type="text/javascript">
var selected;
$(document).ready(function () {
$("input[id='selectType']").change(function(){
if ($(this).val() == "byTitle") {
$("#m_scents2").hide();
$("#btnMove").show();
$("#m_scents").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay:5,
source: "query.php",
focus: function( event, ui ){
event.preventDefault();
return false;
},
select: function( event, ui ) {
window.selected = ui.item.movieName;
return false;
}
}).data("uiAutocomplete")._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<a>" + (item.posterLink?"<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />":"") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>" )
.appendTo( ul );
};
}
});
$('#btnMove').on('click', function (e) {
popupCenter("movieBytitle.php","_blank","400","400");
});
</script>
This is movieBytitle.php:
<body>
<div id= "field"
</div>
<script type="text/javascript">
var selected = parent.window.opener.selected;
$.ajax({
url: 'childfilm.php',
datatype: "json",
data:{p:selected},
success: function(response) {
$("#field").html(response);
}
});
</script>
</body>
and this is childfilm.php:
<?php
if(isset($_GET['p']) && !empty($_GET['p'])){
try{
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM films WHERE movieName LIKE :p");
$sql->execute(array(':p' => '%'.$_GET['p'].'%'));
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$option = '' . $row['movieName'] . '<br />';
$html .= $option;
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html;
exit;
}
?>
UPDATE:
This is the new childfilm.php (Thanks to #ghost help):
if(isset($_GET['p']) && !empty($_GET['p'])){
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM films WHERE movieName LIKE :p");
$sql->execute(array(':p' => '%'.$_GET['p'].'%'));
}
?>
<table>
<tr>
<th></th>
<th>Title</th>
<th>Year</th>
<th>Genre</th>
</tr>
<?php while($row = $sql->fetch(PDO::FETCH_ASSOC)): ?>
<tr>
<td><img class='imdbImage' src='imdbImage.php?url="<?php echo $row['posterLink'];?>'</td>
<td><?php echo $row['movieName']; ?></td>
</tr>
<?php endwhile; ?>
</table>
and this is imdbImage.php:
<?php
header("Content-type: image/jpeg");
$url = rawurldecode($_REQUEST['url']);
echo file_get_contents($url);
?>
New problem:
This is the result (Still, the image is not shown properly):
If you already got those information in the table, then just include it in the fetching and present it in tabular form:
<?php
if(isset($_GET['p']) && !empty($_GET['p'])){
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM films WHERE movieName LIKE :p");
$sql->execute(array(':p' => '%'.$_GET['p'].'%'));
}
?>
<table>
<tr>
<th></th>
<th>Title</th>
<th>Year</th>
<th>Genre</th>
</tr>
<?php while($row = $sql->fetch(PDO::FETCH_ASSOC)): ?>
<tr>
<td><img src="path/to/images/<?php echo $row['filename']; ?>" alt="" /></td>
<td><?php echo $row['movieName']; ?></td>
<td><?php echo $row['year']; ?></td>
<td><?php echo $row['genre']; ?></td>
</tr>
<?php endwhile; ?>
</table>

Categories

Resources