can here is any reset query which reset the table after update.
I update a colum and then I want to reset it.
id name
1 azeem
2 arfan
update the table.
update table set name = 'abc' where id = 1;
update table set name = 'xyz' where id = 2;
id name
1 abc
2 xyz
Update:
$sql = mysql_query("select * from table");
while($row = mysql_fetch_array($sql)){
echo $row['name'];
}
After that I want to reset it. How can I do that.?
2 Ways.
If you're running a test server and want to restore back all of the info that you're changing, then you can make a backup and restore the table values after the update.
otherwise if you're talking about at the transaction level you can make a transaction and instead of committing, roll it back.
<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");
/* Recognize mistake and roll back changes */
$dbh->rollBack();
/* Database connection is now back in autocommit mode */
?>
Yes you can, as sgeddes said, you need to use a transaction. When you use a transaction which is not committed you can rollback to the state before the query executed.
Try this:
//Start the transaction
mysql_query("START TRANSACTION");
//An update query
$yourUpdateQuery = mysql_query("UPDATE YOUR_TBL SET COLUMN = 'COLUMN_VALUE' WHERE COLUMN_ID = ID_VALUE");
//Some SQL select queries (note, that this do not have effect on your data, so this don't need to be in your transaction
$sql = mysql_query("select * from table");
while($row = mysql_fetch_array($sql))
{
echo $row['name'];
}
//Some check here
if (1==1) {
//Ok, let's finish it
mysql_query("COMMIT");
} else {
//Not ok, rollback to the state before the transaction started.
mysql_query("ROLLBACK");
}
Note that you and the above example are using mysql_* functions which are deprecated. You should use PDO instead of mysql_*.
Here is a PDO example:
<?php
//PDO Database connection (if you haven't done this)
$db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME', "USERNAME", "PASSWORD");
//Start the transaction
$db->beginTransaction();
//An update query
$db = $db->exec("UPDATE YOUR_TBL SET COLUMN = 'COLUMN_VALUE' WHERE COLUMN_ID = ID_VALUE");
//Some SQL select queries (note, that this do not have effect on your data, so this don't need to be in your transaction
$sql = 'select * from table';
foreach($db->query($sql) as $row)
{
echo $row['name'];
}
//Some check here
if (1==1) {
//Ok, let's finish it
$db->commit();
} else {
//Not ok, rollback to the state before the transaction started.
$db->rollBack();
}
?>
Related
I'm trying to populate a column in a mysql database with a unique identifier using a while loop, but uniqid is repeating the same output over and over again.
this is my code:
$dblink = mysqli_connect($host,$dbu,$dbp);
$dblink->set_charset("utf8");
$seldb = mysqli_select_db($dblink, $db);
$dblink = new mysqli($host, $dbu, $dbp, $db);
$result = $dblink->query(" SELECT * FROM `mytable` ");
while ($row = $result->fetch_assoc()) {
$uniquecode = uniqid();
$sql = mysqli_query($dblink,"UPDATE `mytable` SET `code`='$uniquecode' ");
}
What am I doing wrong?
You're updating every record in each iteration because your UPDATE is lacking a WHERE clause.
Normally you'd key this like:
UPDATE ... SET code=? WHERE id=?
Where that locks it to just the row matching id or whatever your ID column is called.
Note: You should avoid SELECT * unless you actually need all those columns. Here you don't, you just need ID, so just select that.
This code is working fine for updating the row , but I want to RETURN the updated Row ID. Please let me know how I can do that.
static function editProject($arr)
{
foreach ($arr as $key => $value) {
$$key = $value;
}
$db = new DatabaseConnection();
$dbh = $db->getDBH();
$sql = "UPDATE Project SET Job_Name='$JobName',Job_Number='$JobNumber',Location='$Location',
Project_SupervisorID='$ProjectSupervisorID',Project_ManagerID='$ProjectManagerID',Notes='$Notes',Category='$Category'
WHERE ID='$ID'";
$pdo = $dbh->query($sql);
$db->disconnect();
return $pdo->rowCount(); // INSTEAD of ROW COUNT RETURN I WANT TO RETURN ID here
}
Unlike an insert with an update you already know the id of the row you're updating. In your code it is $ID so just do
return $ID;
If you were doing an insert the pdo function would be http://php.net/manual/en/pdo.lastinsertid.php.
You also should use parameterized queries and prepared statements when using PDO. http://php.net/manual/en/pdo.prepared-statements.php
Rough parameterized version:
$sql = "UPDATE Project
SET Job_Name=?,
Job_Number=?,
Location=?,
Project_SupervisorID=?,
Project_ManagerID=?,
Notes=?,
Category=?
WHERE ID=?";
$pdo = $dbh->prepare($sql);
$pdo->execute(array($JobName, $JobNumber, $Location, $ProjectSupervisorID, $ProjectManagerID, $Notes, $Category, $ID));
In Update Query, you already have ID so you don't need to know last updated Id.
$ID is the updated ID that you are looking for in your case. So you need to return $ID only.
return $ID;
Otherwise you can use below PDO Query for getting last updated Id.
$pdo = $dbh->lastInsertId();
// If the row exists AND a value is updated, with lastInsertId() you will get the ID of the updated row.
That worked for me Edit table so that it will automatically keep track of whenever a row is modified.
ALTER TABLE Project
ADD lastmodified TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
Then, to find out the last updated row.
SELECT ID FROM Project ORDER BY lastmodified DESC LIMIT 1;
static function editProject($arr)
{
foreach ($arr as $key => $value) {
$$key = $value;
}
$db = new DatabaseConnection();
$dbh = $db->getDBH();
$sql = "UPDATE Project SET Job_Name='$JobName',Job_Number='$JobNumber',Location='$Location',
Project_SupervisorID='$ProjectSupervisorID',Project_ManagerID='$ProjectManagerID',Notes='$Notes',Category='$Category'
WHERE ID='$ID'";
$pdo = $dbh->query($sql);
$sql = "SELECT ID FROM Project ORDER BY lastmodified DESC LIMIT 1;";
$pdo = $dbh->query($sql);
$n = $pdo->fetch(PDO::FETCH_ASSOC);
$db->disconnect();
return $n['ID'];
}
You can use this mysql_insert_id()
Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement. Use this function after you have performed an INSERT statement into a table that contains an AUTO_INCREMENT field, or have used INSERT or UPDATE to set a column value with LAST_INSERT_ID(expr).
Futhur you can read from above mentioned link
Here is my script:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
All I want to know, can I use an if statement in the codes which are between beginTransaction() and commit() ? Something like this:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
if (/* a condition here */){
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
}
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
Can I ?
Actually I asked that because here is a sentence which says you can't and doing that is dangerous:
Won't work and is dangerous since you could close your transaction too early with the nested commit().
There is no problem with your transaction structure. The comment on php.net only means, that MySQL does not support nested transactions. In order to your further question, you can query any data (SQL), manipulate data (DML), but not modify any database structures (DDL - data definition language).
/*won't work*/
START TRANSACTION;
/*statement*/
START TRANSACTION; /*nested not supported, auto commit*/
/*statement*/
COMMIT;
/*statement dependend on 1st transaction won't work*/
COMMIT;
See also MySQL ref
Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.
You can do everything within a transaction, the only thing you cannot do is nest transactions.
Not the if clause itself is the problem in your linked comment, but the fact there is another beginTransaction / commit pair inside.
I have a script which is containing some queries:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
As you see there is two statements (insert and update). All I'm trying to do is making sure both of them work or none of them.
I mean I want to implement a dependency between those two statements. If updating fails, then inserting shouldn't work and vice versa. How can I do that?
You could use sql transactions
http://www.sqlteam.com/article/introduction-to-transactions
You can use transactions and PDO has an api for this (http://php.net/manual/en/pdo.begintransaction.php),
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
As others said, you could use 'transactions'.
Or
you could mannualy check whether the data is right in the database. Just 'select' what you have inserted.
The 'execute' function return 'true' on success or 'false' on failure. You can do something like:
$isDone=$stm1->execute(array($value));
if(!$isDone){
echo 'Operation fails, I will stop.';
return false;
}
I'm currently creating some sort of inventory system.
I have master_tbl where in I save the items. In master_tbl, I have column qty_left or the available stock left.
I also have the table issuance_tbl where in I save all the transaction in issuing items.
In this table there is issued_qty.
My problem is how can I INSERT a row into issuance_tbl at the same time UPDATE the master_tbl.qty_left. (master_tbl.qty_left - issuance_tbl.issued_qty).
Is it possible?
I think the best way is using Stored Procedure. You can have bunch of SQL statements with error handling and ACID transactions in one place. This is because if your first query executes and the second fails, you may need to rollback transactions. Stored procedures allow all this fancy but reliable stuff.
You can start here: http://forums.mysql.com/read.php?98,358569
I'm not completely confident that 'If there's any way to do such thing':
You need to do it in steps, LIKE THIS:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
Hope this might help
here is the example:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);