I have a database table named ‘favoritecats’ with the following fields:
- id
- catName
- catId
I am using Jquery to run this function on click event of an element on DOM Ready.
// Delete a Favorite Category from SQL Database
$('.deleteCatFavs').click(function(){ // On click of .deleteCatFavs
var actionRequested = "AJAX_delFavCat"; // My Personal PHP Controller Identifier
var url = "index.php"; // URL to post to
// Now Im getting the data I want to post into variables.
var catId = $("input[name=FavCats]:checked").val();
var rowId = $("input[name=FavCats]:checked").attr("id");
// Now we make the post
$.post(url, {AJAX_Action: actionRequested, rowId: rowId},
function(data){
$("#favCats").fadeIn().html(data);
});
});
This all Works Fine,
But below I have the PHP Code to delete the selected rowId from above from the database.
Here is where im having the issue, Im sure its a SQL error.
public function AJAX_delFavCat(){
$rowId = isset($_POST['rowId'])?$_POST['rowId']:''; // Get Posted Variable
// Below, I want to delete the posted rowId, from the DB,
$this->database->query("DELETE FROM 'favoritecats' WHERE id='$rowId'");
// My personal Loaders, I need help with the delete query above!!
$data = $this->database->query("SELECT * FROM favoritecats");
$this->load->view('Ajax_addToFavCats.php', $data, $ajax=1);
} // End
The “DELETE FROM ‘favoritecats’ WHERE id=’$rowId'” doesn’t work, what am I doing wrong?
[EDIT]
I get the following error through SQL:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ”favoritecats’ WHERE id=’27” at line 1
Also, How would I write a Jquery function using the $.ajax method instead of the $.post method im using now, does it really make a difference?
You’ve got a SQL-injection security hole.
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
Change this
To this
To properly escape your inputs.
Back to your question
Will fix your error.
Note the use of backticks around tablenames, Normal quotes are not allowed and are in fact a
syntax error.