MySQL Update Query - By Row Number - php

I'd like to update a row in a MySQL table when a specific row number is reached
This is a little confusing since , the real row number of the record isn't a column in the table.
And there's no question of iterating over rows , since we're not iterating over an array as in mysql_fetch_array()
So , if I'd like to update - say the 3rd row of the table , what would the query be like?
I'm a noob at MySQL
Thanks a ton for your help ! :D

$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
$query = "SELECT MyColoumn FROM Mytable";
$result = mysqli_query($link, $query);
$row_needed = 3; //Your needed row e.g: 3rd row
for ($i=1,$i=$row_needed,$i++) {
$row = mysqli_fetch_array($result);
}
// now we are in 3rd row
$query = "UPDATE MyColumn FROM MyTable SET MyColumn = '".$MyColumnUpdate."' WHERE MyColumn = '".$row['MyColumn']."' ";
$result = mysqli_query($link, $query);
...

Try this query
UPDATE
tbl a,
(Select
#rn:=#rn+1 as rowId,
tbl.*
from
tbl
join
(select #rn:=0) tmp) b
SET
a.columnName = <VALUE>
WHERE
b.rowId = <rowNumber> AND
a.id = b.id;
NOTE The id column must be a unique one, you can use the primary key of that table...
SQLFIDDLE

Related

get count of the ids in mysql

I want to count all the entries against id
i have used this query
select count(*) from table1 group by `id`
the problem is my table has 3 records
id A has 2 records
id B has 1 record
when i run this query using php it gives me 2 enteries
$mysqli = new mysqli("localhost","root", "", "db");
$query = $mysqli->prepare("SELECT COUNT(*) FROM `tble1` GROUP by `ID`");
$query->execute();
$query->store_result();
$rowsaff = $query->num_rows;
echo $rowsaff;
EDIT: misunderstand the question.
You have to SELECT the count of the distinct id:
$query = $mysqli->prepare("SELECT COUNT(distinct `ID`) FROM `tble1`");

Need to figure out total hours between check-in and check-out times

I am trying to create a check-in/check-out table in my database. My check-in form works without issue, inserting the time into my database. The problem occurs when I try to check out. Everything is good on the first entry...
But when I try to check in and check out again, this happens...
So far so good, but when I check out...
Currently, my code updates the out column and totalTime column of all matching child_id's.
Here is my code:
// Select the correct child from the database
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$var = $row['id'];
// Insert the check out time for the child
$query = "UPDATE checkinout
SET `out` = :nowTime
WHERE child_id = $var
AND `in` IS NOT NULL";
$statement = $pdo->prepare($query);
$statement->bindValue(':nowTime', date("YmjHis"));
$statement->execute();
// Select check in time for specified child
$sql_inTime = "SELECT `in` FROM checkinout
WHERE child_id = $var";
$inResult = $pdo->query($sql_inTime);
$inRow = $inResult->fetch();
$inTime = strtotime($inRow['in']);
// Select the check out time for specified child
$sql_outTime = "SELECT `out` FROM checkinout
WHERE child_id = $var";
$outResult = $pdo->query($sql_outTime);
$outRow = $outResult->fetch();
$outTime = strtotime($outRow['out']);
// Find total hours
$totalTime = abs($outTime - $inTime)/(60*60);
// Update totalHours column for specified child
$queryTotalTime = "UPDATE checkinout
SET totalTime = :totalTime
WHERE child_id = $var
AND 'out' IS NOT NULL";
$statement = $pdo->prepare($queryTotalTime);
$statement->bindValue(':totalTime', $totalTime);
$statement->execute();
I think you could do all of this in your first update statement using TIMESTAMPDIFF rather than figuring the total time with PHP:
UPDATE checkinout
SET
out = NOW(),
totalTime = TIMESTAMPDIFF(SECOND, `in`, NOW()) / 3600
WHERE
child_id = $var
AND out IS NULL
The criteria WHERE out IS NULL will only update rows that do not have a value in the out column yet.
IF you have MySQL Db THEN sql will be
SELECT TIMESTAMPDIFF(HOUR,in,out) from checkinout;

Updating the row with the biggest value

In the "user_id" column of my table, I'd like to insert the ID of the user who just registred from my page. The idea is to associate his recent generated income with the users id, just to spot an eventual double registration of the income.
In order to do this, I tought to update the user_id column, on the row where income_id has the biggest value, i.e. the last generated income, but something isn't working. My code is:
$query = "SELECT max( id_income ) FROM `affiliate_income`";
$last_income = mysql_query($query, $conn) or die(mysql_error());
$last = mysql_fetch_assoc($last_income);
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']."WHERE id_income =".$last;
$result = mysql_query($updtsql, $conn) or die(mysql_error());
any ideas?
Actually you can do it in one query,
UPDATE affiliate_income a
INNER JOIN (SELECT MAX(id_income) id_income FROM affiliate_income) b
ON a.id_income = b.id_income
SET a.id_user = 'valueHere'
You get the value of $last as array.So you have to giv the query like the following
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']."WHERE id_income =".$last['id_income'];
You try to get the max id_income but in the second query (updtsql) you try to find the id_income = array. Besides, you do not put a white space before WHERE clause.
$query = "SELECT max( id_income ) AS ii FROM `affiliate_income`";
$last_income = mysql_query($query, $conn) or die(mysql_error());
$last = mysql_fetch_assoc($last_income);
$updtsql = "UPDATE affiliate_income SET `id_user`=".$row_user_code['id_user']." WHERE id_income =".$last['ii'];
$result = mysql_query($updtsql, $conn) or die(mysql_error());

Pass column value from Select query to another query for insertion in PHP

I was thinking of accomplishing the following as a PHP multi_query. But I'm trying to figure out how to pass the column value from the select query to the insert and update queries.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$query .= "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query .= "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
Problem is, I'm not sure how to pass the link_id value to the other queries. So I'm thinking I might have to rearrange the queries into one, but again, I'm just not sure how to pull that off.
Anyone got any suggestions?
You need to execute select query 1st then use its output to execute 2nd & 3rd query.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$query2 = "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query3 = "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
mysql_query($query2);
mysql_query($query3);
}

MySQL MyISAM race condition

The function has next structure:
$q = 'LOCK TABLES table1 WRITE;';
mysql_query($q);
$q = 'select id from table1 where is_delete = 0 limit 1;';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
$q = 'UNLOCK TABLES;';
mysql_query($q);
I locking all tables, but queries run parallel.
How fix this?
Check whether you're getting any MySQL errors on the LOCK TABLES query:
$q = 'LOCK TABLES table1 WRITE';
$r = mysql_query($q) or die(mysql_error());
However, if this is all you are doing, you can also simply write:
UPDATE `table1 SET `is_delete` = 1 WHERE `is_delete` = 0 LIMIT 1
which does not require any locks at all. Of course, this will only work if the data from your first query is not being processed in any way, and if it doesn't really matter which row you are updating, as long as it's one in which is_delete is set to 0. This is what the code you posted does, too, but it's not immediately obvious to me what you would want to use this code for :)
More generally, if you are using the default InnoDB storage engine for your MySQL table, you may want to look into SELECT ... FOR UPDATE:
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
You could write:
$q = 'select id from table1 where is_delete = 0 limit 1 for update';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
See also: http://www.mysqlperformanceblog.com/2006/08/06/select-lock-in-share-mode-and-for-update/

Categories