I am trying to delete a entry from a table named project in Laravel 4.2 query based on a input data.
What I have done is -
DB::table('project')->where('project.id', '=', Input::get('id'))->delete();
But the problem is, how can I know that if the data is deleted or not?
Can anypne please help?
$id = Input::get('id');
$entryObj = ProjectModel::findorfail($id); // Assuming you have model
// It's bad practise to delete on DB:table because you won't be able to use
//soft-deletes or observers won't trigger if you don't use models.
if($entryObj){
if(!$entryObj->delete()){
throw new Exception('Now we know that it failed to delete');
}else{
echo "100% record is deleted.";
}
}
But let's say you don't care for models/observers/soft-deletes in that case
if(DB::table('project')->where('project.id', '=', Input::get('id'))->delete()){
echo "successfully deleted";
}
Mind you it's very very very bad practise first we not testing what Input::get('id') going to have it could be elephant or a cat in there or let's say it was supposed to have userId=1 but since they wanted to mess your data they modified on client side html to say it's 50. Boom there goes data of user 50 which is disaster if you think about it.
Forgot to mention shortcut
If it is id then you can also use
ProjectModel::destroy($id); //to delete
The delete statement returns a number of how many records where affected. Hence you can check if the return value is greater than zero. In your case it should be always 1 assuming the id is unique. So an if statement if equals one then delete was successfull
Related
I know it is a frequently asked question, but let me explain a bit why I need to ask that again.
Most answers out there suggests using
$this->db->affected_rows()
This is not working in my situation as I may have situation that the update data is the same as the data in the database, so it will return 0 even if the update is success.
I know I can write another query to check if it is because the data are the same, but this sounds stupid to me.
Another way is to use the Active Record Class in code igniter, so the line will be something like:
$error_num = $this->db->update("users", array('firstName' => $newFirstName));
return $error_num;
which is a better solution (at least it works even if there is no update due to repeated data). However, I would like to use the database class, i.e. something like:
$this->db->query('update table set field = somedata where id=1');
It increases the readability of my code to coder who knows php + SQL but are not familiar with code igniter, but then this is why I am asking if anybody knows how do I get the error number if I query in this way?
i.e. Something like mysql_errno() when using mysql_query($query) in PHP.
Both will work like same only difference
if you using active record class all the input variables are escaped automatically
If you want security you better to go with active record class
If you use normal query execution you have to escape the input parameters manually using $this->db->escape_str()
$id = $this->db->escape_str($id)
You can check the query execution status.
$status = $this->db->update("users", array('firstName' => $newFirstName));
if($status)
{
//here you can check the number of affected rows if required
echo $this->db->affected_rows();
}else{
//here you can prcess for failure case
log_message('Error', $this->db->_error_message());
}
//return the status to required place
return $status
I have use this code for checking.
$status = $this->db->query('update table set field = somedata where id=1');
if($status)
return true;
else
return false;
Basically what I am trying to do is when I delete a client with an ID of lets say 6 and I have 50 clients, I then want to update the client with the ID of 50 to 6.
This is my code, in PHP, but it won't execute 2 mysql_query-s at the same time at least I think that's the problem. Otherwise the SQL syntax works fine.
public function delete () {
$last=$this->numrow; //contains last ID works fine
if (isset ($_GET['x'])) {
mysql_query('DELETE FROM proba WHERE ID ='.$_GET['x']);
mysql_query('UPDATE proba SET ID='.(int)$_GET['x'].'WHERE ID='.(int)$last);
}
}
The $_GET['x'] contains the ID on which it was clicked . But only the first mysql_query gets executed how do i make it so the second one gets executed also ?
And another question is is it possible to get <a href="munka/index.php?x=5" > [-] </a> the x=5 with a $_POST ?
You might save yourself a lot of trouble by using mysql's replace query:
see http://dev.mysql.com/doc/refman/5.6/en/replace.html
for details.
most probably you are facing a php error on the first query. Check the php error log.
for the second question $_GET is used to take parameters from the URL for example
munka/index.php?x=5
$_POST is used to get parameters posted on http post (usually on form submits).
just change the update query with a space before the where clause
mysql_query('UPDATE proba SET ID='.(int)$_GET['x'].' WHERE ID='.(int)$last);
Better to use transactions support by using InnoDB Mysql DB Engine, so both delete and update execute together wuth COMMIT without miss , and in case anything goes wrong your delete changes get ROLLBACK
if (isset($_GET['x'])) {
mysql_query('DELETE FROM proba WHERE ID =' . $_GET['x']);
mysql_query('ALTER TABLE `proba` DROP `ID`;');
mysql_query('ALTER TABLE `proba` ADD `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
}
Try in Phpmyadmin delete record no of 5 and drop id column and recreate id column.
It is work.
I'm having problems with a piece of code and wonder if someone can help.
I have a form that submits information to a MySQL database, I have the correct code for checking to see if the submitted product code already exists, and if so shows a warning message and the record is not added.
That code is:
$result = mysql_query("SELECT * FROM listing_1 WHERE product_code='$product_code'");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
adminwarnmessage("DUPLICATE REFERENCE CODE","FAILURE - <b>$product_name</b> has <b>NOT</b> been added because the reference number already exists.");
}
That works fine for Data Entry, however I have another form that allows users to edit the record, this is what is causing me a problem, as the above code only tells me that there is already a matching record in the database, Of course when I try to save (update) the record it now tells me I can't because it is a duplicate.
What I would like to happen is that it doesn't allow users to choose another productcode that already exists, but I want them to be able to update the record using the same product code the form fetched from the database.
Hope that makes sense, any help greatly appreciated.
If you have id (primary key) then You will have to compare with id of that product before updating the record. For example
$result = mysql_query("SELECT * FROM listing_1 WHERE product_code='$product_code' AND id!=$id");
$num_rows = mysql_num_rows($result);
if ($num_rows) {
echo "duplicate record";
}
Here $id is the id of the product that you should have while editing the record.
following is the step you need to follow when you managing the Database
First you need an primary key(auto_increment) in "ID" field
When you execute insert query that time first check where record is already available or not. if not available than only you should execute insert query.
use primary key filed for update, delete etc...
if you follow the above step than you never face this problem
Are you perhaps checking for duplicate occurrences in both of insert and update statement? If so, you shouldn't. Duplicate entry is relevant only when "inserting". You shouldn't use the same check for update. Hope that helps.
why the same code for update also? you can use another query for updating which is better for debugging if you have problems later. try this
$result = mysql_query("UPDATE listing_1 SET product_code='$new_product_code' WHERE product_code='$product_code' AND id='$id'");
if($result) {
echo "your product was updated.";
} else {
echo "your product is not in DB";
}
EDIT: be careful in updating or inserting things, take always id to check unless your product_code is unique
EDIT
I have resolved this issue by making $productcode field a unique Index.
Now when editing if there is a duplicate..
Mysql does not accept the update query, it returns an error code
I trap that error code and include it in an if statement...
if( mysql_errno() == '1062' )
adminwarnmessage("DUPLICATE REFERENCE CODE","FAILURE - $product_name has NOT been added because the reference number already exists");
}
adminmessage("Item Updated", Congratulations you updated $productname succesfully");
}
This now allows editing of $productcode but does not allow it to be changed to one already used in the database.
Thank you to everyone who took the time to offer help
I have a bit of an issue with my code.
I'm making an administrative panel for users to add things to the database. On occasion, they might try to save data without changing it (open a dialog, click save without changing anything). This, of course, will make mysql_affected_rows() return '0' when checking to see if the UPDATE query worked.
Is there another query to make that will always UPDATE regardless of whether the data is the same or not (or can I modify a simple UPDATE query to always update)?
EDIT
This is for users who don't have programming experience. Of course you wouldn't want to update if there's no reason to, but when a user tries to update and it doesn't happen I end up showing a failure message. Rather than there being something wrong, its just it doesn't need to be updated. I need a way to show the user that, instead of a generic 'failure' message. If it failed for another reason, I still need to know.
From the MySQL Documentation:
If you set a column to the value it currently has, MySQL notices this
and does not update it.
Instead of checking mysql_affected_rows, just check to see if the query was successful:
if(!mysql_query("UPDATE ..."))
{
//failure
}
else
{
$verification = mysql_query("SELECT ROW_COUNT() as rows_affected");
$row = mysql_fetch_row($verification);
$rows_affected = $row[0];
if ($rows_affected > 0)
{
//update was performed
}
else
{
//no update was needed
}
}
Here's a situation, i have a list of support tickets that when you click the title of the ticket takes you to a page that displays the ticket in more detail. If uses URL GET variables to query the database. I've taken SQL injection into account but what if someone modifies the url to an id that doesn't exist? whats the best way to deal with that?
Thanks,
Jonesy
If the ID does not exist, send a 404 - Not Found header along with a nice error page telling the user that it wasn't found.
You probably have to make a page handling unsuccessful searches anyway; just route it in there. Then you can help the user to find what (s)he searches in a consistent way, provide cues and "most-searched-after" and what not.
This may seem too simple, but you should always validate your GET (or POST) variable before doing anything with them. In your case, just verify that the ID exists in the database. If it doesn't, inform the user.
You should always check if your query returned anything. If it returned 0 rows, the ID doesn't exist.
<?php
$result = mysql_db_query("your query", $link);
$num_rows = mysql_num_rows($result);
if($num_rows < 1) {
// row with that id doesnt exist
// do whatever you want
} elseif($num_rows > 1) {
// you have problem with your ids in db
} else {
// everything went fine
// do your thing here
}
?>
Check if the ticket exists; if not, react accordingly. What "react accordingly" means is determined by your business logic: create a new ticket? raise an error? take the user to a list of available tickets?
An example using the old mysql extension for brevity:
$sanitized_numeric_id = (int) $_GET['ticket_id']; // assuming id is numeric
$query_resource = mysql_query('SELECT `somecolumn`, `column2`, `othercolumn`
FROM `tickets`
WHERE `id`= ' . $sanitized_numeric_id);
if (mysql_num_rows($query_resource) > 0) {
// the ticket exists, do something with it
} else {
// the ticket doesn't exist, react accordingly
}