onChange function change the displayed data from a table - javascript

I have a table in my website and a dropdown list in my website which according to the selected value from the dropdown list it will change the output of the table.
I did a search and I found this on stackoverflow and I tried to do something similar but it doesn't work. Here is my php file called announcements which I want to display the table.
<?php
include_once 'header.php';
$connection = mysql_connect("localhost", "root", "smogi")?>
<html>
<head>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<?php
$result = queryMysql("SELECT * FROM doctor WHERE username='$username'");
if (mysql_num_rows($result)):
?>
<!-- Koumpi pou se metaferei sti selida gia tin dimiourgia neas anakoinwseis -->
<form action="new_announcement.php">
<input type="submit" value="Create New Announcement">
</form>
<br />
Select Category :<select id="SelectDisease" name="category">
<option value="*">All</option>
<!--emfanizei tis epiloges gia ta specialties me basi auta p exoume sti basi mas -->
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
?>
</select><br><br />
<table border="1" style="width:100%">
<tr>
<td><b>Author</b></td>
<td><b>Category</b></td>
<td><b>Subject</b></td>
<td><b>Content</b></td>
</tr>
<?php
if(isset($_GET["selected"])){
$type = $_GET["selected"];
$query = "SELECT author,category,subject,content FROM announcements WHERE category='" . $type . "'";
$announcements = mysql_query($query, $connection);
$counter = 0;
$z = 0;
if ($announcements == FALSE) {
die(mysql_error()); // To get better errors report
}
while ($row = mysql_fetch_assoc($announcements)) {
while ($row = mysql_fetch_assoc($announcements)) {
$counter++;
?>
<tr>
<td><?php echo $row['author'];?></td>
<td><?php echo $row['category']; ?></td>
<td><?php echo $row['subject']; ?></td>
<td><?php echo $row['content']; ?></td>
</tr>
<?php }
}
}
?>
<?php
else:
?>
Select Category :<select id="SelectDisease" name="category">
<option value="*">All</option>
<!--emfanizei tis epiloges gia ta specialties me basi auta p exoume sti basi mas -->
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
?>
</select><br><br />
<table border="1" style="width:100%">
<tr>
<td><b>Author</b></td>
<td><b>Category</b></td>
<td><b>Subject</b></td>
<td><b>Content</b></td>
</tr>
<?php
if(isset($_GET["selected"])){
$type = $_GET["selected"];
$query = "SELECT author,category,subject,content FROM announcements WHERE category='" . $type . "'";
$announcements = mysql_query($query, $connection);
$counter = 0;
$z = 0;
while ($row = mysql_fetch_assoc($announcements)) {
$counter++;
?>
<tr>
<td><?php echo $row['author'];?></td>
<td><?php echo $row['category']; ?></td>
<td><?php echo $row['subject']; ?></td>
<td><?php echo $row['content']; ?></td>
</tr>
<?php } } endif;?>
</table>
</body>
</html>
And this is my javascript.js file
$(document).ready(function() {
$('#SelectDisease').change(function() {
var selected=$(this).val();
$.get("announcements.php?selected="+selected, function(data){
$('.result').html(data);
});
});
});
Thank you for your time :)
PS: THE INCLUDE_ONCE CODE create the connection with th db

First thing is that unless your user makes a selection, you do not have any $_GET available so it will be undefined. You should get the value if it is available. Like so:
if(isset($_GET['selected'])){
$type = $_GET['selected'];
}
But this is not the only issue here. $.get is an ajax request and it is just sending a request to your php file and gets all the html content of your page.
If you do not care to reload the page each time your user selects an option, instead of an $.get request simply redirect your user to that url. Otherwise if you want to do it without reloading, you need to do an $.get request correctly.
The example that you said you are trying to do something similar, is not sending an $.get request to the same page that the user is viewing. It is sending the get request to another php page which is just designed to get the $_GET["selected"] from its url, send a query to the database, get the result from the database and then just return the result, which will be the data in your $.get request.
See this example: Get data from mysql database using php and jquery ajax
It is trying to do the same thing as you, except with $.POST which you can do the same or change it to a $.GET if you want. See how the other php page return the result and how the $.get request is receiving and viewing the data.

mysql_query() will result in FALSE which is Boolean value if there is any error, do check before while loop, to get better error,
if($announcements == FALSE) {
die(mysql_error()); // To get better errors report
}
while($row = mysql_fetch_assoc($announcements)){
// then you code here
}

mysql_query() returns FALSE in case of error.
You have to choose the data base name.
Like so:
$connection = mysql_connect("localhost", "root", "smogi", "***DATABASE_NAME***");
Remember, mysql functions are deprecated!
Use mysqli or PDO.
Have a nice day

Related

How to display each row data in the database?

I'm having a hard time displaying the title and note on each row of my database. I want to display one row (with the title and note) after each
from a form in a page heading to the displaying of row datas page.
This is my code below:
//
Let's say that we have 4 rows of datas. In my code, I can only display the first row, because it keeps having the first row's data. This is because the form is in the first php file. Then after I submit the form, it's directed to this file, and it keeps getting the first row.
<?php $con=mysqli_connect("localhost","root","","task");?>
<?php $results = mysqli_query($con, "SELECT * FROM note"); ?>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<?php
$id=$row['id'];
echo ' ';
echo '<button class="call_modal" data-id="$id" style="cursor:pointer;">'. $row['title'] . '</button>';
?>
<?php
}?>
<?php $results = mysqli_query($con, "SELECT * FROM note"); ?>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<div class="note" data-id="<?= $row['id'] ?>">
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<?php
echo '<br><br>';
echo '<div class="padding">'.$row['title'].'';
echo '<br><br><br><br>';
echo ''.$row['note'].'</div>';
?>
</div>
</div>
<?php
}?>
<?php
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} ?>
The code below is not tested but it should be correct and give you a better idea of what you are doing right/wrong. I hope it helps..
<?php
$con=mysqli_connect("localhost","root","","task");
$results = mysqli_query($con, "SELECT * FROM note");
while ($row = mysqli_fetch_array($results)) { //starting your data row loop
$id=$row['id'];// you are creating a variable here but not using it two lines down.
echo ' ';
//YOUR OLD CODE echo '<button class="call_modal" data-id="$id" style="cursor:pointer;">'. $row['title'] . '</button>';
echo '<button class="call_modal" data-id="$id" style="cursor:pointer;">'. $id . '</button>';// use the variable "$id" that you created here
// You dont need the next two lines, you already did a query and have the data loaded in the "$results" array
/* $results = mysqli_query($con, "SELECT * FROM note");
while ($row = mysqli_fetch_array($results)) */
?> // close the php tag if you are going to switch to html instead of "echoing html"
/* OLD CODE <div class="note" data-id="<?= $row['id'] ?>"> you were missing the "php" in the php tags */
<div class="note" data-id="<?php echo $id; ?>"> // corrected code
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<?php //switching back to php so create your open tag again...
echo '<br><br>';
echo '<div class="padding">'.$row['title'].'';
echo '<br><br><br><br>';
echo ''.$row['note'].'</div>';// you dont NEED the '' before .$row.... unless you want it but its just essentially a blank string
?>
</div>
</div>
<?php
} // ending your "for each data row" here
?>
<?php
// PS you're not using this function anywhere unless its in ommited code?
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} ?>
In your loop you're using mysqli_fetch_array, which returns an array with each element in that array containing the field value.
What you want is mysqli_fetch_assoc instead, this will return a hash which you can then use the way you're using it now.
Another thing is that you don't need to have 2 loops in there querying the database. And please indent your code, it makes it really hard for you and everyone else to read it.
Here is the updated/cleaned up version of your code. This has been tested, you can find a sample code with instructions to run on my Github here.
<?php
$con = mysqli_connect("localhost", "root", "", "task");
$results = mysqli_query($con, "SELECT * FROM note");
while ($row = mysqli_fetch_assoc($results)) {
$id = $row['id'];
echo ' ';
echo '<button class="call_modal" data-id="' . $id . '" style="cursor:pointer;">'. $row['title'] . '</button>';
?>
<div class="note" data-id="<?= $row['id'] ?>">
<div class="modal">
<div class="modal_close close"></div>
<div class="modal_main">
<?php
echo '<br /><br />';
echo '<div class="padding">' . $row['title'];
echo '<br /><br /><br /><br />';
echo $row['note'];
echo '</div>'
?>
</div>
</div>
</div>
</div>
<?php
}
?>
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

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.

Deleting row from mysql using jquery and php

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.

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', '');
};

Categories

Resources