I have made some code. I'm using noty little framework.
<script type="text/javascript">
function generateNormal(type, text, layout)
{
if (typeof(layout)==='undefined') layout = 'topRight';
var n = noty(
{
text: text,
type: type,
dismissQueue: true,
theme: 'default',
layout: layout
}
);
}
function generateButtonDelete(id)
{
if (typeof(layout)==='undefined') layout = 'topRight';
var n = noty(
{
text: 'Are you sure you want to delete the record?',
type: 'alert',
dismissQueue: true,
theme: 'default',
layout: 'center' ,
buttons: [
{addClass: 'btn btn-primary', text: 'Ok', onClick: function($noty) {
$noty.close();
$.post("delete.php", {id: id },
function(data) {
if (data)
{
generateNormal('success', 'The record is deleted with succes!')
}
else
{
generateNormal('error', 'There is a problem with the database, please try again.')
}
});
}
}
]
}
);
}
</script>
The code above will be used by a table generated by PHP:
<table>
<tr>
<th>
Delete
</th>
<th>
ID
</th>
<th>
Description
</th>
</tr>
<!-- This section will be created by PHP -->
<tr>
<td>
<a href="#" onclick="generateButtonDelete(1)">Delete</a>
</td>
<td>
1
</td>
<td>
Description row 1
</td>
</tr>
<tr>
<td>
<a href="#" onclick="generateButtonDelete(2)">Delete</a>
</td>
<td>
2
</td>
<td>
Description row 2
</td>
</tr>
<!-- End of section that will be create by PHP -->
In the delete.php file, the query for deleting a record, will be executed by using PHP. And echo true or false, if the query executed well or not.
The code works perfect without any errors in the console. But I'm not sure if this is safe, it is just a proof of concept. The html and the PHP page will be secured with a login script.
I hope someone can say me if this is safe?
Sorry for my bad English.
EDIT: I have made some PHP code. But it's just a proof of concept so I don't test the code, buth Eclipse doesn't give any errors.
<?php
if (isset($_POST['id']))
{
if (is_int($_POST['id']))
{
if ($_POST['id'] > 0)
{
$con = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
$sql = "DELETE FROM table_name WHERE id=?";
$q = $con->prepare($sql);
$execution = $q->execute(array($_POST['id']));
if ($execution) echo true;
else echo false;
}
else echo false;
}
else echo false;
}
?>
$.post() usage seem okay to me, you follow the main (recommended) usage of it - to post data to the server.
There is nothing unsafe about your usage of $.post()
.
Safety needs to be taken care of in your delete.php
where you have to make sure, that your $_POST['id']
is sanitized in some way before you use it eg in MySQL queries.
As far as SQL injection goes, your code is secure, you could tidy up those if else statements a bit like so:
if (isset($_POST['id']) && (int) $_POST['id'] > 0) {
The only issue I see is that there is no checking that the user is allowed to delete a record, I'd guess you'd have some session logic in there as well and maybe a query to check the current user is the owner/admin of the record you're deleting.