How to delete and update data in MySQL at the same time - php

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.

Related

How to make update query when user status changed to 1

i got issue while if statement running. i want to update query on those user_id's who status changed from 0 to 1. but this query run on all status userid who already 1. but i want run on those who changed to 0 to 1. and run only one time don't many time. please help me to solve this. Thanks
if($status==1)
{
$query22= "UPDATE `user` SET `global` =$row[user_id] WHERE
`user_id` = '".$_SESSION['userid']."' ";
$current_id = $db_handle->insertquery($query22);
}
Try with below condition:
if($status=1)
If I understand correctly you want to take some action when a status is changed by user, Ignore answer if thats not the case.
First you need to check the initial status. This you most probably need to fetch from database.
Lets call this variable $initialStatus
$initialStatus = fetchUserStatus($userId); // need to implement fetchUserStatus
then you can put your check something like this,
if($status==1 && $initialStatus==0){
// do some action
}

Codeigniter unknown column in where clause?

I am trying to create an update function in Codeigniter using a dropdown menu. Unfortunately, when I click submit I get an error that there is an "Unknown column 'stages.id' in my where clause. I've used the stages.id in other parts of my code to update other fields, and am not sure why this is happening here. Any assistance or thoughts on why this might be happening would be greatly appreciated!
function update_stage_name($id){
$stage_name=array(
'stage_name'=>$this->input->post('stage_name')
);
$this->db->where('stages.id', $id);
$this->db->update('stage_names', $stage_name);
}
This is what the database query looks like according to the error:
UPDATE `stage_names` SET `stage_name` = 'Holly' WHERE `stages`.`id` = '264'
I have several tables, and stages is sort of the main one. Stages each only have one stage_name but a stage_name can belong to multiple stages. Stage_name does not have a foreign key from stages, but stages has a stage_name_id.
EDIT: So it seems the issue was actually that I wanted to update the stages table, and not the stage_names table. But the problem is that the stages table has a stage_name_id but the input from my form is for stage_name. How do I get to the id in the same method? I'm still new to active record and codeigniter and i'm not sure how to proceed.
As the error says you dont have a column that can be referenced using stages.id. Mainly because its the wrong table..
Try..
UPDATE `stage_names` SET `stage_name` = 'Holly' WHERE `stage_names`.`id` = '264'
//Note changed the table name in the where
If you need to use the stages.id and (as you say in your comment) you dont have an FK then you will need to create one as the database isnt smart enough to guess it. So once you have a field in stages_names called stage_id (or similar) you can do..
UPDATE `stage_names` SET `stage_name` = 'Holly' WHERE `stage_id` = '264'
Try this:
function update_stage_name($id) {
$stage_name=array(
'stage_name'=> $this->input->post('stage_name')
);
$this->db->where('stage_names.id', (int)$id);
$this->db->update('stage_names', $stage_name);
}

Update ENUM field in MySQL

I have a strange and incomprehensible situation. I can't update an ENUM field with my query in my php script. Executed in Heidi, it works perfectly. Can somebody help me to understand why?
This is the query:
UPDATE ps_specific_price
SET reduction='0.5', reduction_type='percentage'
WHERE id_product='249' and id_group='3'
The enum field is reduction_type (amount, percentage)
Here is the code for the operation:
if($valori['perc_riv']==0){
$sql_perc_riv="update ps_specific_price set reduction='0', reduction_type='amount' where id_product='".$valori[id_product]."' and id_group='3'";
} else {
$riduzione=(float)$valori['perc_riv']/100;
$sql_perc_riv="update ps_specific_price set reduction_type='percentage' WHERE id_specific_price='2031'"; // where id_product='".$valori[id_product]."' and id_group='3'";
}
$sttpercriv = $conn->prepare($sql_perc_riv);
$sttpercriv->execute();
Ok, I read better the documentation: I have to make an Alter table. I dont' want. I'll make a select, then I'll delete the row and I'll make a new insert with the different values.

How to get the last ID with mysql using php

I have a form with two stages, the first is to put the information but the second is the UPDATE to add the photo. So what I want to do is retrieve the last auto incremented ID to update the data, I used LAST_INSERT_ID ()
but I realize it is the update everywhere. Do you have a suggestion for me to help me? Thank you and sorry sorry for my english.
You can see here what I did:
$sql = 'UPDATE 'jj_news' SET
cover_picture="'.$large_image_name.$_SESSION['user_file_ext'].'",
min_picture="'.$thumb_image_name.$_SESSION['user_file_ext'].'", statut="1",
edited="'.date('Y-m-d h:i:s').'" WHERE id_news= LAST_INSERT_ID(id_news)';
mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());
You cannot get your id in the "second stage". You have to get it immediately after running insert.
So, get it in the first stage, store it in a session and then use in the second one.
Bloody hell, why don't you just store the damn id, into a hidden post field and pass it to the second page on form submit?
mysql_query("INSERT INTO `xy` (`xy`) VALUES ('$_POST[xy]');");
$insertId = mysql_insert_id();
mysql_query("UPDATE xy SET xy='$xy' WHERE id='$insertId'");
only know from the mysql_* function...
use mysqli or PDO, but if this helps you i´m glad.....
You can try the following function.
function getLastId($tablename,$id_field){
$id=0;
$sql="select ".$id_field." from ".$tablename." order by ".$id_field." desc limit 1" ;
$res_obj=mysql_query($sql) or die(mysql_error);
if(mysql_num_rows($res_obj)>0){
$result=mysql_fetch_array($res_obj); //we have only on row and column.
$id=$result[$id_field]; //set the last greator Id value;
}
return $id;
}
$newid=getLastId("yourtable","id_field")+1;
//insert your data using $newid instead of autocomplete.
//use $newid during update if update is on new page make a session of $newid. like
$_SESSION['update_id']=$newid;
this function make manual increment of id column, instead of auto increment. I think it is ease to control your situation using this function.

How get value from POST

This piece of code has been tripping me out for the past four hours. It is deleting a row of photos by the primary ID.
I have var_dump($selectedPhoto) and it is the correct ID, a number. My code will run every time I press delete photo, get to the mysqli_stmt_store_result part and shoots out the $txtMessage, But the database does not update.
This is really weird because I have used the exact same code, with different variables on another page and it works perfectly fine.
Can you see any errors by looking at this? OR have a better way to writing the delete statement.
if (isset($_POST['btnDeletePhoto']))
{
$selectedPhoto = $_SESSION['selectedPhoto'];
$deleteString = "DELETE FROM Photos WHERE PhotoID = ?";
$preparedDeleteStmt = mysqli_prepare($link, $deleteString);
mysqli_stmt_bind_param($preparedDeleteStmt, 'i', $selectedPhoto);
if (!mysqli_stmt_execute($preparedDeleteStmt))
{
mysqli_close($link);
die("The system is not available, try again later");
}
if(mysqli_stmt_store_result($preparedDeleteStmt))
{
$txtMessage = "Delete successfull";
}
To add: $selectedPhoto is a value of a select, drop down list value.
If the photo comes from the value of a select, it is not going to be stored in a session variable, so you probably need to change:
$selectedPhoto = $_SESSION['selectedPhoto'];
to:
$selectedPhoto = $_POST['selectedPhoto'];
Apart from that you need to add error handling to all database operations.

Categories