let say i have a table named banners. the columns are:
+---+-------------------------------+
|ID | link | image | active |
+---+-------+-------------+---------+
|1 |#link1 | image1 | 0 |
|2 |#link2 | image2 | 1 |
|3 |#link3 | image3 | 0 |
+---+-------+-------------+---------+
there you can see row #2 is active. how can i update next row based on latest active row? also if active row is the last row, then set first row as active row.
PS: I will do the query using cron, update every 2 hours for example. no problem about the cron, I did it.
use this stored procedure :
DELIMITER //
CREATE PROCEDURE updateActiveRow()
BEGIN
SELECT MAX(ID) INTO #activeID FROM banners WHERE active;
UPDATE banners SET active=1 WHERE ID > #activeID LIMIT 1;
IF ROW_COUNT() = 0 THEN
UPDATE banners SET active=1 ORDER BY ID LIMIT 1;
END IF;
UPDATE banners SET active=0 WHERE ID = #activeID;/*do this only if you want to deactivate current active row*/
END //
Thanks to all,
I solved it myself. here is the code
class Job{
private $con;
function __construct(){
$this->con = mysqli_connect('localhost', 'root', '', 'egoji');
}
function getCurrentActiveID(){
$q = "SELECT id FROM banners WHERE active='1'";
$result = $this->con->query($q);
$row = mysqli_fetch_assoc($result);
return $row['id'];
}
function getNextID($id){
$q = "SELECT MIN(id) AS id FROM banners WHERE id > '{$id}'";
$result = $this->con->query($q);
$row = mysqli_fetch_assoc($result);
return $row['id'];
}
function isLastRow(){
$currentActiveId = $this->getCurrentActiveID();
$q = "SELECT id FROM banners ORDER BY id DESC LIMIT 1";
$result = $this->con->query($q);
$row = mysqli_fetch_assoc($result);
return $row['id'] == $currentActiveId ? true:false;
}
function updateFirstRow(){
$q = "SELECT MIN(id) AS id FROM banners";
$result = $this->con->query($q);
$row = mysqli_fetch_assoc($result);
$this->deactivateAll();
$update_q = "UPDATE banners SET active='1' WHERE id='{$row['id']}'";
$this->con->query($update_q);
}
function updateNextRow(){
$currentActiveId = $this->getCurrentActiveID();
$nextID = $this->getNextID($currentActiveId);
$this->deactivateAll();
$update_q = "UPDATE banners SET active='1' WHERE id='{$nextID}'";
$this->con->query($update_q);
}
function deactivateAll(){
$update_q = "UPDATE banners SET active='0'";
$this->con->query($update_q);
}
function doit(){
if($this->isLastRow()){
$this->updateFirstRow();
}else{
$this->updateNextRow();
}
}
}
$job = new Job;
$job->doit();
I am open to any suggestions or correction.
Tested SQL Fiddle
SET #activeID = (SELECT ID FROM Banners WHERE active = 1);
SET #isLast = (SELECT COUNT(*) FROM Banners) LIKE #activeID;
UPDATE Banners
SET active = IF(ID = #activeID, 0, IF(ID = #activeID+1, 1, active));
UPDATE Banners
SET active = IF(#isLast AND ID = 1, 1, active);
Related
i am trying to update a table column which same column from same table select.
Here is the code (updated)
public function UpdateStockIn($id, $subUnitValue) {
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = (SELECT CURRENT_STOCK_BOTTLE FROM BRAND_LIST WHERE ID = ?) + '.$subUnitValue.' WHERE ID = ? ";
$success = 0;
try {
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $id);
$stmt->execute();
$success = 1;
} catch (PDOException $ex) {
echo $ex->getMessage();
}
return $success;
}
it Show error like this
You can't specify target table 'BRAND_LIST' for update in FROM clause
Try run these 2 sqls, The first one will store a value into mysql local variable then use into 2nd sql.
SELECT #old_subUnitValue := GROUP_CONCAT(table1.CURRENT_STOCK_BOTTLE) FROM BRAND_LIST AS table1 WHERE table1.ID=2;
UPDATE BRAND_LIST AS table2 SET table2.CURRENT_STOCK_BOTTLE = #old_subUnitValue + '.$subUnitValue.' WHERE table2.ID=2;
Use the below query
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = CURRENT_STOCK_BOTTLE + ".$subUnitValue." WHERE ID = ?";
How can I perform the following two updates in only one MySQL query?
$query = "UPDATE news SET main = 1 WHERE id = '$id'";
mysqli_query($this->db_conn, $query);
$query = "UPDATE news SET main = 0 WHERE id <> '$id'";
mysqli_query($this->db_conn, $query);
Only one row should be set to 1 while the rest of them should be set to 0.
Give this a try:
UPDATE news SET main = CASE
WHEN id = '$id' THEN 1
ELSE 0
END
create table quiz(E_Id INT NOT NULL AUTO_INCREMENT PRIMAR KEY, E_name VARCHAR(255), E_Salary INT)
now whenever i insert data intop table, auto increment works as expected.
Now when i delete the record the sequence of number doesnot get decrement.
Suppose I have a records with Id 1, 2, 3, 4, 5. When i delete the 2 and 3 rd records, the sequence continues from the number 6. I want that if a records is deleted it numbering should get decrement automatically
There is no way for auto-decrementing. But you can use other simple methods.
DROP the field you are auto_incrementing.
ALTER the table to ADD the field again with the same attributes.
Then the list of auto-incrementing will reset.
NOTE: Take care when you are DROPing the table. It may drop your entire data.
Update all ids that are above the one been deleted by decrementing by 1 (-1) (if there are 3 id's in auto_increment column and you delete id 2, id 3 will be set to be id = 2) and then "alter table set auto_increment = 1 to update auto_increment counter.
code(including deletion of image file from website folder:
$allGood = false;
if(isset($_GET['id']) != ""){
$item = $_GET['id'];
$query = "SELECT * FROM products WHERE id = ?";
if($getImgPath = $sqlConnection->prepare($query)){
$getImgPath->bind_param("i",$item);
$getImgPath->execute();
$result = $getImgPath->get_result();
$row = $result->fetch_array();
$deletedItemId = $row['id'];
if(isset($row['image']) != ""){
$imgPath = "../../../../".$row['image'];
if(unlink($imgPath)){
$query = "DELETE FROM products WHERE id = ?";
if($delete = $sqlConnection->prepare($query)){
$delete->bind_param("i",$item);
if($delete->execute()){
$query = "SELECT * FROM products";
if($getIds = $sqlConnection->query($query)){
while($row = $getIds->fetch_array()){
if($row['id']>$deletedItemId){
$newId = $row['id']-1;
$query = "UPDATE products SET id=? WHERE id=?";
if($updateIds = $sqlConnection->prepare($query)){
$updateIds->bind_param("ii",$newId,$row['id']);
if($updateIds->execute()){
$allGood = true;
}
}
} else {$allGood = true;}
}
}
}
}
}
}
}
}
if($allGood == true){
$query = "ALTER TABLE products AUTO_INCREMENT = 1";
if($sqlConnection->query($query)){
echo "success!";
}else{echo "error.";}
}
I have a Table structure as
id, trackid, table_name, operation,
oldvalue, newvalue, field,
changedonetime
Now if I have 3 rows for the same "trackid" same "field", then how can i select the latest out of the three?
i.e. for e.g.:
id = 100 trackid = 152 table_name
= jos_menu operation= UPDATE oldvalue = IPL newvalue = IPLcccc
field = name live = 0 changedonetime =
2010-04-30 17:54:39
and
id = 101 trackid = 152 table_name =
jos_menu operation= UPDATE oldvalue
= IPLcccc newvalue = IPL2222 field = name live = 0 changedonetime =
2010-04-30 18:54:39
As u can see above the secind entry is the latest change,
Now what query I should use to get the only one and Latest row out of many such rows...
$distupdqry = "select DISTINCT trackid,table_name from jos_audittrail where live = 0 AND operation = 'UPDATE'";
$disupdsel = mysql_query($distupdqry);
$t_ids = array();
$t_table = array();
while($row3 = mysql_fetch_array($disupdsel))
{
$t_ids[] = $row3['trackid'];
$t_table[] = $row3['table_name'];
//$t_table[] = $row3['table_name'];
}
//echo "<pre>";print_r($t_table);echo "<pre>";
//exit;
for($n=0;$n<count($t_ids);$n++)
{
$qupd = "SELECT * FROM jos_audittrail WHERE operation = 'UPDATE' AND trackid=$t_ids[$n] order by changedone DESC ";
$seletupdaudit = mysql_query($qupd);
$row4 = array();
$audit3 = array();
while($row4 = mysql_fetch_array($seletupdaudit))
{
$audit3[] = $row4;
}
$updatefield = '';
for($j=0;$j<count($audit3);$j++)
{
if($j == 0)
{
if($audit3[$j]['operation'] == "UPDATE")
{
//$insqry .= $audit2[$i]['operation']." ";
//echo "<br>";
$updatefield .= "UPDATE `".$audit3[$j]['table_name']."` SET ";
}
}
if($audit3[$j]['operation'] == "UPDATE")
{
$updatefield .= $audit3[$j]['field']." = '".$audit3[$j]['newvalue']."', ";
}
}
/*echo "<pre>";
print_r($audit3);
exit;*/
$primarykey = "SHOW INDEXES FROM `".$t_table[$n]."` WHERE Key_name = 'PRIMARY'";
$prime = mysql_query($primarykey);
$pkey = mysql_fetch_array($prime);
$updatefield .= "]";
echo $updatefield = str_replace(", ]"," WHERE ".$pkey['Column_name']." = '".$t_ids[$n]."'",$updatefield);
}
In the above code I am fetching ou the distinct IDs in which update operation has been done, and then accordingly query is fired to get all the changes done on different fields of the selected distinct ids...
Here I am creating the Update query by fetching the records from the initially described table which is here mentioned as audittrail table...
Therefore I need the last made change in the field so that only latest change can be selected in the select queries i have used...
please go through the code.. and see how can i make the required change i need finally..
This is another question of the greatest-n-per-group category, which comes up several times per week on Stack Overflow.
Here's how I'd solve it in your case:
SELECT j1.*
FROM jos_audittrail j1 LEFT OUTER JOIN jos_audittrail j2
ON (j1.trackid = j2.trackid AND j1.field = j2.field
AND j1.changedonetime < j2.changedonetime)
WHERE j2.id IS NULL;
I have a Table structure as
id, trackid, table_name, operation, oldvalue, newvalue, field, changedonetime
Now if I have 3 rows for the same "trackid" same "field", then how can i select the latest out of the three?
i.e. for e.g.:
id = 100 trackid = 152 table_name
= jos_menu operation= UPDATE oldvalue = IPL newvalue = IPLcccc
field = name live = 0 changedonetime =
2010-04-30 17:54:39
and
id = 101 trackid = 152 table_name =
jos_menu operation= UPDATE oldvalue
= IPLcccc newvalue = IPL2222 field = name live = 0 changedonetime =
2010-04-30 18:54:39
As u can see above the secind entry is the latest change,
Now what query I shoud use to get the only one and Latest row out of many such rows...
UPDATED
$distupdqry = "select DISTINCT trackid,table_name from jos_audittrail where live = 0 AND operation = 'UPDATE'";
$disupdsel = mysql_query($distupdqry);
$t_ids = array();
$t_table = array();
while($row3 = mysql_fetch_array($disupdsel))
{
$t_ids[] = $row3['trackid'];
$t_table[] = $row3['table_name'];
//$t_table[] = $row3['table_name'];
}
//echo "<pre>";print_r($t_table);echo "<pre>";
//exit;
for($n=0;$n<count($t_ids);$n++)
{
$qupd = "SELECT * FROM jos_audittrail WHERE operation = 'UPDATE' AND trackid=$t_ids[$n] order by changedone DESC ";
$seletupdaudit = mysql_query($qupd);
$row4 = array();
$audit3 = array();
while($row4 = mysql_fetch_array($seletupdaudit))
{
$audit3[] = $row4;
}
$updatefield = '';
for($j=0;$j<count($audit3);$j++)
{
if($j == 0)
{
if($audit3[$j]['operation'] == "UPDATE")
{
//$insqry .= $audit2[$i]['operation']." ";
//echo "<br>";
$updatefield .= "UPDATE `".$audit3[$j]['table_name']."` SET ";
}
}
if($audit3[$j]['operation'] == "UPDATE")
{
$updatefield .= $audit3[$j]['field']." = '".$audit3[$j]['newvalue']."', ";
}
}
/*echo "<pre>";
print_r($audit3);
exit;*/
$primarykey = "SHOW INDEXES FROM `".$t_table[$n]."` WHERE Key_name = 'PRIMARY'";
$prime = mysql_query($primarykey);
$pkey = mysql_fetch_array($prime);
$updatefield .= "]";
echo $updatefield = str_replace(", ]"," WHERE ".$pkey['Column_name']." = '".$t_ids[$n]."'",$updatefield);
}
Here I am creating the Update query by fetching the records from the initially described table which is here mentioned as audittrail table... please go throught the code.. and see how can i make the required change i need finally..
select * from TableName order by id DESC LIMIT 1
EDITED. YEs you can if you want to order by "changedonetime" USE.
select * from TableName order by changedonetime DESC LIMIT 1