When we update a MySQL record with php, we can check if it has effect using:
$mysqli->affected_rows;
But how do I check which column has been modified?
Example, in my table have the columns: id / name / age
In a record we have the data: 1 / Woton / 18
If I send an: UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'
Only the age field has changed. How can I determine this?
You cannot directly get the updated columns from the query result.
It can be get from some php query. Firstly we will have to select the row from database which we are going to update in a array variable. Than run the update query for the same row.
Lastly get the same row from database from select query in the new array variable.
Finally we get two arrays.
We can get the updated column with the array_diff_assoc php function.
See the below code for the same.
$sql = "SELECT * from mytable where id=1 limit 1";
$prev = mysqli_fetch_assoc(mysqli_query($conn, $sql));
//Get the column data in the array. Before update.
$sql = "UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'";
$conn->query($sql);
// Update data
$sql = "SELECT * from mytable where id=1 limit 1";
$updated = mysqli_fetch_assoc(mysqli_query($conn, $sql));
// Again run the select command to get updated data.
$UpdatedColumns=array_diff_assoc($updated,$prev);
In a different note: If QueryLog has been enabled in the DB then you (or your script in PHP or Python or any) can easily see/read which part of the content has been updated and even you can monitor the DB.
The good news is, even you can target which table, which query etc.
Related
This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}
I want a Mysql query to update all users 'status' filed in 'user' table. I can update one user by running following query.
Table
What I tried
update user set status = 1 where id = 1 and type = 'viber'
Do I need to run the above query inside a loop to update all users data?
I want a query like following
update user set status = 1 where id = 1 and type = 'viber' and id = 2 and type = 'twitter' ..
your help is much appreciated.
Just
update user set status=1;
Updates your whole table.
If you want to just update the status for all records then below query is useful for that.
update user set status=1;
The WHEREclause is used to extract only those records that fulfill a specified criterion. but here you don't want that .so just use this query to update all the records
update user set status=1;
just use:
$update = mysqli_query("UPDATE user SET status = 1")or die(mysqli_error());
if this not works, you can select all data and then update each row by setting user id like this :
$select = mysqli_query("SELECT * FROM user")or die(mysqli_error());
while($row = mysqli_fetch_array($select)){
$id = $row['id'];
mysqli_query("UPDATE user SET status=1 WHERE id='$id' ");
}
Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`
I updated with success
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
but how can I get the "queue2" value without opening a new request to MySQL
I can simply get the new value with this command
$selresult = mysql_query("SELECT * FROM $table WHERE `id` = '$getid'") or die(mysql_error());
but I'm afraid that the database can get new update again and i will get higher number
Any idea how to do it ?
you can use query to update the value.
mysql_query("UPDATE user_profile SET userpoints = userpoints + 1 WHERE user_id = '".$user_id."'");
See URL:-
PHP + MySQL transactions examples
Try this:-
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
You will need to use a transaction between the queries to be certain.
The docs for transactions are here. A good SO question that covers it in detail: PHP + MySQL transactions examples
Edit:
Looking at it from a different angle, why don't you do it in reverse though? It might save the need for a transaction (thought it is possible that you get multiple reads before a write):
Get the value for your queue2 value to display in the page from this:
mysql_query("SELECT * FROM $table WHERE `id` = '$getid'");
You have the true value now, so you can run:
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
No transaction and you know the value of the data before the update.
If I perform the following MySQL query through PHP:
UPDATE pictures
SET category = '0'
WHERE category = '$categoryID'
AND username = '$username'";
$queryUncat = mysql_query($uncategorise) or die(mysql_error());
It works fine and any category that was equal to $categoryID gets changed to 0. However, if I perform the following:
UPDATE pictures
SET category = '0',
pictureorder = (SELECT COUNT(category) + 1 WHERE category='0' AND username='$username')
WHERE category = '$categoryID'
AND username = '$username'";
$queryUncat = mysql_query($uncategorise) or die(mysql_error());
Not only does pictureorder not equal to the count of the category row plus one, but the category no longer gets changed if equal to $categoryID. I'm not too good at figuring this out as I know only basic MySQL through PHP and am not familiar with it through its own console.
Thanks in advance for any suggestions.
This form of query is not valid. First, your subquery is missing a FROM clause. Second, you cannot select from the same table you are updating in the same query.
http://dev.mysql.com/doc/refman/5.1/en/update.html