Woonghee Woonghee - 1 month ago 6
Ajax Question

Delete function in php using ajax

I am trying to make a dynamic table with ajax/jquery.

other functions such as add, update are working but my delete function seem to be not working. I am digging into this problem but with no result.

Below is the snippet which fetches data from the database and form up a table.
Each row has update/delete buttons which lead into appropriate functions.



if(mysqli_num_rows($result) > 0)
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['Surname'].'</td>
<td>'.$row['Name'].'</td>
<td>'.$row['Address'].'</td>
<td>'.$row['Telephone'].'</td>
<td>'.$row['PurchaseDate'].'</td>
<td>'.$row['Model'].'</td>
<td>'.$row['SerialNumber'].'</td>
<td>'.$row['Notes'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-warning">Update</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}





here is my delete function it receives the id of the row from the other php where it loads table from database.

Delete Function script


function DeleteUser(id) {
var conf = confirm("Are you sure, do you really want to delete User?");
if (conf == true) {
$.post("ajax/deleteUser.php", {
id: id
},
function (data, status) {
// reload Users by using readRecords();
readRecords();
}
);
}
}





deletefunction php



<?php
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// include Database connection file
include("db_connection.php");

// get user id
$client_id = $_POST['id'];

// delete User
$query = "DELETE FROM Clients WHERE id = '$client_id'";
if (!$result = mysqli_query($query)) {
exit(mysqli_error($result));
}
}
?>





I even tried going into mysql instead of mysqli, and it somehow worked. I am kinda assuming that mysqli has different function than mysql? Well I heard mysql is deprecated but it seems I am doing wrong something here...

I am not good at programming, I am learning as it became my new hobby. Any tips would be thankful.

Answer

mysqli_* is more object oriented and imporved version of MySQL.

You need to pass connection id to mysqli_query()

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

So, the corrected code:

if (!$result = mysqli_query($conn, $query)) {
// Where $conn is the connection identifier.

Documentation