$.get gives no error but doesn't work - php

I'm trying to create an employee management system, and right now I managed to create a table populated with some database content.
Now what I want is to delete the selected row on click of a button situated at the end of every row.
To do that I'm trying to use the Jquery $.get method, which calls a file named delete.php, that will do the job, and then animate and remove the row from the html.
The problem is: the animation starts, but the php file doesn't remove the record from the database! I even tried to console.log for errors, but as you can see in the below screenshot, it just gives me the html code of the page instead of an error code...
screenshot
here's the code I used to generate the table:
<?php
$sql = "SELECT * FROM dipendente";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table class='table table-striped table-hover'>".
"<thead>".
"<tr>".
"<td>id</td>".
"<td>nome</td>".
"<td>cognome</td>".
"<td>impiego</td>".
"<td>permessi</td>".
"<td>contratto</td>".
"<td>inizio</td>".
"<td>fine</td>".
"<td>edit</td>".
"</tr>".
"</thead>";
echo "<tbody>";
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo "<tr id=".$row["id"].">".
"<td>" . "#". $row["id"]. "</td>" .
"<td contenteditable='false'>" . $row["nome"]. "</td>".
"<td contenteditable='false'>" . $row["cognome"] . "</td>".
"<td contenteditable='false'>" . $row["impiego"] . "</td>".
"<td contenteditable='false'>" . $row["permessi"] . "</td>".
"<td contenteditable='false'>" . $row["contratto"] . "</td>".
"<td contenteditable='false'>" . $row["inizio"] . "</td>".
"<td contenteditable='false'>" . $row["fine"] . "</td>".
"<td>" .
"<span class='glyphicon glyphicon-pencil' aria-hidden='true'></span>" .
" " .
"<span class='glyphicon glyphicon-remove-sign' aria-hidden='true'></span>" .
"<a href='#' id='$id' class='delete'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></a>".
" ".
"<span class='glyphicon glyphicon-ok-sign' aria-hidden='true'></span>".
"</td>".
"</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
here is my jquery code:
$(".delete").click(function(){
var del_id = $(this).attr("id");
var tr = $(this).parent().parent();
console.log(del_id);
console.log(tr);
$.get("php/delete.php", { id: del_id } , function(error){
//console.log(error);
tr.fadeOut("1s",function(){
$(this).remove();
});
});
});
and there's my delete.php code:
<?php
$id = $_GET['del_id'];
$dbc = mysqli_connect('localhost', 'root', 'root', 'gestione_personale') or die('Connection error!');
$query = "DELETE FROM dipendente WHERE id = '$id'";
mysqli_query($dbc, $query) or die('Database error!');
header('location:../index.php');
Am I doing something wrong?

Based on what I see I'm going to give this answer. But you really need to get off using mysqli_* with the way you're using it. The answer I'm giving you is in prepare statement which is much more secure than the way you're using it.
$dbc = mysqli_connect('localhost', 'root', 'root', 'gestione_personale') or die('Connection error!');
$query = $dbc->prepare("DELETE FROM dipendente WHERE id = ?");
$query->bind_param("i", $_GET['id']);
if($query->execute()){
header('location:../index.php');
}else{
die('Database error!')
}
Hope this works for you.

Try access in URL delete.php passing del_id as arg, like this: delete.php?del_id=1
Then you'll see if the record is deleted or if you get some error, also check if php display_errors is enabled.

Related

Why does a PHP file not get included in the file when run by the server?

I have one file called showRelayTeams.php and another called databaseSELECTOperation.php
I am trying to put the one with the database function into the one called showRelayTeams.php
showRelayTeam.php
<?php
$House = $_GET['q'];
$Data = "No Data";
$Query = "SELECT Firstname, Lastname, AgeGroup, Event, Value FROM tblEventEntries WHERE House = '" . $House . "' ORDER BY Value ASC;";
require("http://127.0.0.1/phpscripts/databaseOperations.php");
$Data = databaseSELECTOperation($Query);
$Counter = 0;
if (mysqli_num_rows($Data) > 0) {
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Age Group</th>";
echo "<th>Event</th>";
echo "<th>Time</th>";
echo "<th>Select?</th>";
echo "</tr>";
while ($Row = mysqli_fetch_assoc($Data)) {
$Counter++;
echo "<tr>";
echo "<td>" . $Row["Firstname"] . " " . $Row["Lastname"] . "</td>";
echo "<td>" . $Row["AgeGroup"] . "</td>";
echo "<td>" . $Row["Event"] . "</td>";
echo "<td>" . $Row["Value"] . "</td>";
echo "<td><input type='checkbox' id='" . $Counter . "'
onclick='boxChecked(this.id)'></td>";
echo "</tr>";
}
}
echo "</table>";
?>
databaseSELECTOperation.php
<?php
//use the SQL SELECT command and return the data
function databaseSELECTOperation($Query) {
//this file will include the host, username, password and the database name
include "http://127.0.0.1/includes/variables.php";
//start a connection to the database using the credentials
$Connection = mysqli_connect($DatabaseHost, $Username, $Password, $DatabaseName);
//if the connection to the database was not successfully made then
if (!$Connection) {
//end the script and then print an error
die("Could not connect to the database: " . mysqli_error());
} //end if
//run the query and put the data returned in to a variable
$DataReturned = mysqli_query($Connection, $Query);
//return the data to the script that called it
return $DataReturned;
}
?>
I get the following error:
Fatal error: Uncaught Error: Call to undefined function databaseSELECTOperation()
When I insert the following code just after the require statement, I get
function not found
<?php
if (function_exists('databaseSELECTOperation')) {
echo "function found.<br />\n";
} else {
echo "function not found<br />\n";
}
?>
Any ideas on how to solve this?
That is the error:
require("http://127.0.0.1/phpscripts/databaseOperations.php");
When you are referring to the file via URL, it is including the output which is already processed by a web server, while you need to include the source PHP code.
Instead, you need to specify the path to the file on the file system like in the following examples:
require('../phpscripts/databaseOperations.php');
require('/var/www/html/phpscripts/databaseOperations.php');
require('C:\inetpub\html\phpscripts\databaseOperations.php');

PHP download a specific row from database table

I'm learning PHP right now and connecting to MySQL. I'm able to connect to a table called "info" and display the "date", "time", and "data" of each row, along with 2 extra columns that will allow the user to download the respective "data" into a txt and csv. This is where I'm completely lost on how to achieve that.
My understanding is that since it'll be a clickable link, I will have to use "href=" and will link that to a separate php that I create that will download that row's data, right? But then how does that new php file know which row to download from? I'm guessing I need to pass the row number it is to the other file?
Greatly appreciate it if anyone can lead me in the right direction or have examples. Thanks!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date, time, data FROM info";
$result = $conn->query($sql);
echo "<table border='1'>";
echo "<tr><td> Date </td><td>Time</td><td>Data</td><td> Download text </td><td> Download csv</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" . $row["time"]. "</td><td>" .$row["data"] ."</td><td><a href='NEEDTXTFILE.php'>".$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
} else {
echo "0 results";
}
Assuming you select also the id value
$sql = "SELECT id, date, time, data FROM info";
....
you could add the id to your href eg:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" .
$row["time"]. "</td><td>" .
$row["data"] .
"</td><td><a href='NEEDTXTFILE.php?id=" . $row["id"] . "'>".
$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".
$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
then in your NEEDTXTFILE.php you can obtain the id in $_GET['id']

Create tabe from mysql data with hyperlink to point to report page

Ok i am playing around with this idea for a system i am working on. I want to display data from mysql into a table. I can do this easy. What i would like to do is this. For the ID i would like to make it a link where i pass the id to the next page.
<?php
$con=mysqli_connect("example.com","username","password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Address</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Address'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
What i want to do is in the (echo "" . $row['ID'] . "";) I would like to convert it to a link so it would be something like this: example.com/report.php=24 or something like that. What i need to do is find out how to pass the ID and also how to convert the echo to a hyperlink.
Also on the report page it will display all data for id=24 or what ever the id is into a form that i have setup.
Can anyone help me with this.
Try This
echo '
<td>'.$row["ID"].' </td>';
To make a clickable link you use an anchor tag <a></a> In the href attribute you add the form name report.php and follow that with a ? to seperate that from the parameter list. You then add name=value pairs after the ? for the data you wish to pass eg href="report.php?id=24"
So to make the first page contain a clickable link you do something like this
echo '<td><?php echo $row['ID']; ?></td>';
Now in the report.php script you access the passed data by looking at the $_GET array in PHP
<?php
// check incoming params exist
if ( ! isset($_GET['id'] ) {
// missing param, go to an error page for example
header('Location: error.php');
exit;
}
// You can now use $_GET['id'] which will be the id number passed
// any way you want.
// For example using a PDO connection called $pdo
$table = "table1";
$sql = "SELECT * FROM $table WHERE id = :id";
try {
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->FetchAll(); // $rows now contains all the results of the query
}
catch( PDOException $e) {
echo $e-getMessage();
}
foreach ( $rows as $row ) {
// do things with the $row['column_name'] data
}
I always prefer using direct HTML for something like this.
<td>Link Name</td>
Try this -
while($row = mysqli_fetch_array($result))
{
$link = "example.com/report.php?id=".$row['ID'];
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Address'] . "</td>";
echo "</tr>";
}
echo "</table>";

How to display new rows without refresh using AJAX

I'm actually a little bit confused with all these AJAX techniques. The aim is to display the new rows on my site when new rows are inserted into my database, but i dont know how. The following code has been inserted into my Joomla site threw an extension:
<!-- You can place html anywhere within the source tags -->
<script language="javascript" type="text/javascript">
// You can place JavaScript like this
</script>
<?php
$today = date("d/m/Y");
$sql = "SELECT * FROM queue WHERE";
$sql =$sql . " Date>='$today' ORDER BY Qnumber Desc LIMIT 3";
// echo $sql;
$con=mysqli_connect("localhost","root","db","pass");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Αριθμός Εξυπηρέτησης</th>
<th>Πελάτες σε Αναμονή</th>
<th>Ώρα</th>
<th>Ημερομηνία</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Qnumber'] . "</td>";
echo "<td>" . $row['WaitingCustomers'] . "</td>";
echo "<td>" . $row['Time'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Call PHP function from a button to delete row from a table

I have the following code inside PHP page that displays data from a table. In the last column I have a delete button that calls a function to delete the corresponding row from the table:
// Print data from db
$result = mysql_query("SELECT * FROM questions");
echo "<table border='1' align='center'>
<tr>
<th>ID</th>
<th>Multiple Choice Question</th>
<th>Correct answer</th>
<th>The Tip You Give</th>
<th>Edit Question</th>
<th>Delete Question</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td align='center'>" . $row['ID'] . "</td>";
echo "<td>" . $row['Question'] . "</td>";
echo "<td align='center'>" . $row['Answer'] . "</td>";
echo "<td>" . $row['Help'] . "</td>";
echo "<td align='center'><button type='button' onclick='edit_question()'><img src='images/Edit.png'></button></td>";
echo "<td align='center'><button type='button' onclick='delete_question($row)'><img src='images/delete.png'></button></td>";
echo "</tr>";
}
echo "</table>";
the function is the following:
<script>
function delete_question(int $row_id)
{
var r=confirm("Are you sure you want to delete this question?");
if (r==true)
{
alert('<?php
$con=mysql_connect("localhost","stesia","stesia","stesia");
// Check connection
if (mysql_errno())
{
echo "Failed to connect to MySQL: " . mysql_error();
}
mysql_query($con,"DELETE FROM questions WHERE ID='".$row_id."'");
echo "You want to delete the " . $row_id['ID'] . " question!";
echo "Question deleted!";
mysql_close($con);
?>');
}
else
{
alert("Question not deleted!");
}
}
</script>
The problem is that the function is called and displays the messages, but the row is not deleted (checked that in mysql also). I have tried some things but no luck. What am I doing wrong here?
You cannot do this on client side. You should send an AJAX request to the server (PHP-) side to handle the deletion.
You can find related information here (though these are not showing the best practices, but it helps understanding the concepts):
PHP - AJAX and MySQL
As far as i know onclick only executes JavaScript Code. You could try to put your PHP function into a JavaScript function and execute this from the onclick tag

Categories