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.
if(isset($_POST['id']) && isset($_POST['id']) != "")toif(isset($_POST['id']))deletefunction.phpbut themysqlquery fails? You are correct, don't usemysql_*functions. This is open to SQL injections currently.db_connection.phpopen amysqliormysql_*connection? Themysqli_queryrequires the connection string as its first parameter. See php.net/manual/en/mysqli.query.php. Also @RazibAlMamun is correct.issetwill never return'', you probably could useif(!empty(trim($_POST['id']))) {.