Two updates in one MySQL query - mysql

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

Related

Updating Multiple Column on MySQL

I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle

SQL UPDATE Not Updating

After uploading a csv file, I am trying to insert its contents into my database table. I have this query:
$connect = mysql_connect("localhost","root","");
mysql_select_db("dbtest",$connect);
//get the file
$handle = fopen($filename,"r");
do {
if (isset($data[0])) {
$data0 = mysql_real_escape_string($data[0]); //rcode
$data1 = mysql_real_escape_string($data[1]); //pcode
$data2 = mysql_real_escape_string($data[2]); //mcode
$data3 = mysql_real_escape_string($data[3]); //bcode
$data4 = mysql_real_escape_string($data[4]); //ecode
$data5 = mysql_real_escape_string($data[5]); //filetype
$data6 = mysql_real_escape_string($data[6]); //rec_count
$data7 = mysql_real_escape_string($data[7]); //gen_count
$data8 = mysql_real_escape_string($data[8]); //qc_count
$data9 = mysql_real_escape_string($data[9]); //be_count
$data10 = mysql_real_escape_string($data[10]); //trn_count
$query = "INSERT INTO tbltest(rcode,pcode,mcode,bcode,ecode,filetype,rec_count,
gen_count,qc_count,be_count,trn_count) VALUES ('$data0','$data1','$data2',
'$data3', '$data4', '$data5', '$data6', '$data7', '$data8', '$data9', '$data10')
ON DUPLICATE KEY UPDATE rec_count=values(rec_count),gen_count=values(gen_count),
qc_count=values(qc_count), be_count=values(be_count), trn_count=values(trn_count)";
mysql_query ($query,$connect) ;
}
} while ($data = fgetcsv($handle,1000,"|"));
And it's working neatly but then as the database was re-structured, I just then need to update the database table as rcode to filetype has values already and I just need to insert values of rec_count to trn_count. So my first query INSERT INTO ... ON DUPLICATE KEY UPDATE has been change to UPDATE only. And so I did this:
$query = "UPDATE tbltest SET (rec_count='$data6', gen_count = '$data7',
qc_count = '$data8', be_count = '$data9', trn_count= '$data10') WHERE
(rcode = '$data0', pcode = '$data1', mcode = '$data2', bcode = '$data3',
ecode = '$data4', filetype = '$data5')";
My problem now is that, my UPDATE seems to be not working as it doesn't update the database table. Bu when I did this;
$query = "UPDATE tbltest SET rcode = '5'";
The database is being updated. When I tried echo $query;, the echo responds the correct data (from the csv). I just cannot figure why it doesn't insert these data into the database. Kindly help. Thanks
Your SQL syntax is incorrect. The statement should read something like
UPDATE tbltest
SET rec_count='...', gen_count = '...', ...
WHERE rcode = '...' AND pcode = '...' AND ...
See MySQL UPDATE syntax.

update next row based on previous ID

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);

Insert new column, increment all rows

Is this possible using only mysql:
Insert a new column and example - "pos".
Every row in the table has to have unique,incresing value of "pos" like - 1,2,3,4,5.
In php this would be an easy job:
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$counter = 0;
while($row = mysql_fetch_array($result)){
mysql_query( "UPDATE example SET pos = ".++$counter." WHERE id = ".$row['id']." );
}
As already suggested, the most efficient solution is to use auto incremental on pos.
Alternatively if your use case do not permit you, then try similar:
"UPDATE example SET pos = ((select max(pos) from example) +1) WHERE id
= ".$row['id']."
yes you can do it like that
UPDATE example SET pos = pos+1 WHERE id = ".$row['id']."
Give your pos mysql field the auto_increment attribute - this will index it, make it unique, and increment by 1 on each insert

Insert on first request; update on all subsequent requests

I'm inserting a row into a MySQL database table. On the first insertion I want a new row to be added, but after that I just want that row to be updated. Here's how I'm doing it. An Ajax request calls the following php file:
<?php
include "base.php";
$bookID = $_POST['bookID'];
$shelfID = $_POST['shelfID'];
$userID = $_SESSION['user_id'];
$query = mysql_query("SELECT shelfID FROM shelves WHERE userID = '$userID' AND shelfID = '$shelfID' AND bookID = '$bookID'");
if (mysql_num_rows($query) == 0) {
$insert = "INSERT INTO shelves (bookID,shelfID,userID) VALUES ('$bookID','$shelfID','$userID')";
mysql_query($insert) or die(mysql_error());
} elseif (mysql_num_rows($query) == 1) { //ie row already exists
$update = "UPDATE shelves SET shelfID = '$shelfID' WHERE userID = '$userID' AND bookID = '$bookID'";
mysql_query($update) or die(mysql_error());
}
?>
As it stands it adds a new row every time.
You should consider using PDO for data access. There is a discussion on what you need to do here: PDO Insert on Duplicate Key Update
I'd flag this as duplicate, but that question is specifically discussing PDO.
You can use the INSERT ... ON DUPLICATE KEY UPDATE syntax. As long as you have a unique index on the data set (i.e. userid + shelfid + bookid) you are inserting, it will do an update instead.
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html