How can I return the 1 or 0 as true and false for my select query? I've tried every combination of fetch_assoc, arrays, etc. It usually returns as null, which doesn't make sense.
$querydetails = "select exists (select * from customer_det where id = $uid)";
$resultdetails = mysql_query($querydetails) or die(mysql_error());
while ($row = mysql_fetch_assoc($resultdetails)) {
$resultdetails1 = $row[0];
}
That's the latest version of my query. I guess it's not an array, but I'm not sure how to pull the value if there's no row to be named?
This is a post question to my previous thread: MySQL Update WHERE
SELECT IF(EXISTS(...),1,0) AS result
simple use COUNT and IF
SELECT IF(COUNT(*) = 0, 0, 1)
FROM table1
WHERE s = 2
SQLFiddle Demo
SELECT count(*) FROM (
SELECT id FROM table WHERE condition LIMIT 1
) AS result;
i am using mysql version 8.0.23 on AMS
SELECT
column1,
column2,
IF (exists(select * from MeasurementItemNos measureItem where measureItem.itemNo = ib.itemNo and measureItem.IsActive = 1),1,0) as isUploadedSizeSpec
from table
I would do:
select * from customer_det where id = $uid LIMIT 1
You will get either 1 row or zero rows.
Related
Suppose I have a table TABLE:
NAME ID ...
m -1 ...
f -1 ...
g -1 ...
b -1 ...
z -1 ...
And I want to turn it into:
NAME ID ...
f 1 ...
g 2 ...
m 3 ...
b -1 ...
z -1 ...
You probably get the idea:
select the first 3 rows from the original table (preserving order)
order selected rows by the NAME column.
update selected rows' IDs with their position in the new table (keeping the remaining unselected rows in their original positions).
So (m, f, g) got sorted to (f, g, m) and (b, z) remained (b, z).
Here's how I am trying to do it in PHP:
$count = 0;
$query = "UPDATE TABLE SET ID = $count:= $count + 1 ORDER by NAME DESC LIMIT 3";
mysqli_query($con, $query);
But I don't think I can just go ahead and increment a counter and store its value like that. Any advice?
You can try this :
$limit = 3;
for($count = 0 ; $count < $limit;$count++ ){
$query = "UPDATE TABLE SET ID = $count + 1 WHERE ID = '-1' ORDER by NAME DESC";
mysqli_query($con, $query);
}
$query = "UPDATE TABLE SET ID = '-1' WHERE ID > $limit ORDER by NAME DESC";
mysqli_query($con, $query);
In the above logic :
In the final loop, all the IDs are set to $limit
However the update command outisde the loop will set back IDs to -1 again
First, you can quickly query for the first 3 rows in the table and get the name property only and assign the value in an array.
$sql = "select name from table order by name limit 3"
$query = $mysqli->query($sql);
Now let's construct a helper array:
while ($row = $mysqli->fetch_assoc()) {
$a[] = $row['name'];
}
Now just structure the queries:
foreach($a as $id => $name) {
$query = "update table set id={$id+1} where name='$name' limit 1";
// execute the query
}
Note that I assume that the name is unique so I added the limit 1 directive to tell it stop looking for rows to update once it has found a row.
Also, don't forget that array keys are counting starting from 0, hence we are adding 1 to the $id in the loop.
There may be more elegant solutions but this one is rather easy to understand and use.
In MySQL:
SET #row_number = 0;
update TABLE d
join
(
select
NAME,
#row_number:=#row_number+1 as ID,
from
(select NAME from TABLE limit 3) t
order by
NAME asc
) s on s.NAME = d.NAME
set d.ID = s.ID;
SQLFiddle: http://sqlfiddle.com/#!9/dffecf/1
This assumes NAME is your unique key, otherwise likely best to replace with an Identity column in your table and use that for the update.
This approach may require some syntax changes depending on your DB engine. By doing this in SQL, we only make one pass at the DB. Not a huge deal to iterate in multiple passes with PHP if you're only updating three records, but if it was a 1000, etc.
I have written a MySql query to get the columns related with minimum id . Looks something like this
SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed=21
The table has 4 rows looks like this
So according to the function that I have written
function setLC()
{
$sql = "
SELECT min(id) as ID
, feed
, idpropiedad
FROM `registrofeed`
WHERE feed=21
";
$result = $this->localDb->execute($sql);
$row=mysql_fetch_array($result);
echo $sql;
echo $row['idpropiedad'];
$this->lastCode = $row['idpropiedad'];
}
It returns empty string for idpropiedad
Can any one help me out where I am going wrong
Thanks in advance
I'd think the query you're actually looking for is this:
SELECT id, feed, idpropiedad
FROM registrofeed
WHERE feed = 21
ORDER BY id ASC
LIMIT 1
MIN() is giving you the generally lowest value in the column, it does not affect the rest of the columns. If you want the whole row with the lowest id it doesn't help.
To illustrate, if you really wanted to use MIN here, you'd have to do:
SELECT id, feed, idpropiedad
FROM registrofeed
WHERE id = (SELECT MIN(id) FROM registrofeed WHERE feed = 21)
You can do a better query like this:
$sql = "
SELECT id as ID
, feed
, idpropiedad
FROM `registrofeed`
WHERE feed=21
HAVING MIN(id)
";
This will return only one row with the minimum id number. It's more readable than using ORDERING AND LIMIT 1.
try your select query as
SELECT * FROM registrofeed WHERE feed='21' ORDER BY id ASC LIMIT 1
this fetches the row having minimum id.
Hope it helps
Try this
$sql = "SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed='21' order by id asc";
I'm trying to get rows from a table according to some basic where clauses, and now I want to include an "AND EXISTS" clause on the end. My code is the following:
$stmt = $mysqli->prepare("SELECT object_id FROM ".
$db_table_prefix."user_events
WHERE LPAD(start_timestamp,15,'0') < LPAD(?,15,'0')
AND event_id = ?
AND EXISTS (
SELECT * FROM ".$db_table_prefix."user_events
WHERE LPAD(start_timestamp,15,'0') > LPAD(?,15,'0')
AND event_id = ? )
");
The problem I'm having is that I don't know how to specify a column value from the main query within the AND EXISTS subquery.
I'm looking for a way to tack on this bit into the subquery:
AND object_id = **object_id from main query**
Any help appreciated
Also, added an alias to the subquery's table to avoid confusion
$stmt = $mysqli->prepare("SELECT object_id FROM ".
$db_table_prefix."user_events
WHERE LPAD(start_timestamp,15,'0') < LPAD(?,15,'0')
AND event_id = ?
AND EXISTS (
SELECT * FROM ".$db_table_prefix."user_events AS u
WHERE LPAD(u.start_timestamp,15,'0') > LPAD(?,15,'0')
AND u.object_id = " .$db_table_prefix.".object_id
AND u.event_id = ? )
");
Rather than EXISTS, you might find a self-join syntax is clearer here, I cannot deduce exactly what you want from your code, but to get object_id for an event that started before a specific time, and was also started again later:
SELECT ue1.object_id
FROM user_events ue1 join user_events ue2
WHERE ue1.event_id = ue2.event_id AND
ue1.object_id = ue2.object_id AND
ue1.event_id = ? AND
LPAD(ue1.start_timestamp, 15, '0') < LPAD(ue2.start_timestamp, 15, '0') AND
LPAD(ue1.start_timestamp, 15, '0') < LPAD(?, 15, '0')
and object_id in (select object_id from ...
i have a table in mysql and i am fetching the results from this table. but instead of fetching all the rows in this table i only want to fetch every other row. so first get row one then skip the second row, get row 3 and skip row 4 etc.
Is there a way of doing this and if so can someone please show me how.
I've tried this:
function:
function blocked_users_list() {
global $connection;
global $_SESSION;
global $profile_id;
$query = "SELECT
baseview.*
#odd:=1-#odd AS even
FROM
(
SELECT *
FROM ptb_block_user
WHERE
WHERE ptb_block_user.blocked = '1'
AND ptb_block_user.blocked_id = ".$_SESSION['user_id']."
) AS baseview,
(
SELECT #odd:=0
) AS filter
WHERE
even=1
";
$blocked_users_list = mysql_query($query, $connection);
confirm_query($query, $connection);
return $blocked_users_list;
}
php:
<?php
$blocked_users_list = blocked_users_list();
while ($block = mysql_fetch_array($blocked_users_list)) {
?>
but it gives this error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/ptb1/blocked_users.php on line 44
do it in the query:
SELECT *
FROM (
SELECT
#row := #row +1 AS rownum, [column name]
FROM (
SELECT #row :=0) r, [table name]
) ranked
WHERE rownum % [n] = 1
You can use modulus in mysql (one query)
select * from `table` where `id` % 2 = 1
Retrieves all odd IDs.
Assuming you have a query like
SELECT
col1 AS colA,
col2 AS colB
FROM
sometable
WHERE
something=17
that fetches all rows as a baseline. You can then filter every second row by using
SELECT
baseview.*
#odd:=1-#odd AS even
FROM
(
SELECT
col1 AS colA,
col2 AS colB
FROM
sometable
WHERE
something=17
) AS baseview,
(
SELECT #odd:=0
) AS filter
WHERE
even=1
Use a variable to record the index, then check with mod 2 ($ind % 2) - this will return either 0 or 1.
<?php
$users_list = users_list();
$ind = 0;
while ($user = mysql_fetch_array($users_list)) {
if(($ind++)%2) echo "something";
}
?>
I recently created a scoring system where the users are ordered by their points on descending basis. First I used to store ranks in a column of its own. I used to run this loop to update the rank:
$i = 1;
$numberOfRows = mysql_query('SELECT COUNT(`id`) FROM sector0_players');
$scoreboardquery = mysql_query("SELECT * FROM sector0_players ORDER BY points DESC");
while(($row = mysql_fetch_assoc($scoreboardquery)) || $i<=$numberOfRows){
$scoreid = $row['id'];
$mysql_qeury = mysql_query("UPDATE sector0_players SET scoreboard_rank = '$i' WHERE id = '$scoreid'");
$i++;
}
And it was really hard, not to mention slow to actually run this on a huge amount of users.
Instead, I tried to construct a query and ended up with this.
SET #rownum := 0;
SELECT scoreboard_rank, id, points
FROM (
SELECT #rownum := #rownum + 1 AS scoreboard_rank, id, points FROM sector0_players ORDER BY points DESC
)
as result WHERE id = '1';
But, this is just a select statement. Is there anyway I could get around it and change it so that it updates the table just as the loop does?
Please try using the following query :
set #rownum:=0;
update sector0_players set scoreboard_rank=#rownum:=#rownum+1 ORDER BY points DESC;
PHP code can be ,
mysql_query("set #rownum:=0;");
mysql_query("update sector0_players set scoreboard_rank=#rownum:=#rownum+1 ORDER BY points DESC;");
You can try using the RANK function .. I haven't actually executed the SQL, but it should work
UPDATE sector0_players
SET scoreboard_rank =
(
SELECT srank
FROM
(
SELECT id,points, RANK() OVER (ORDER BY points) AS srank
FROM sector0_players T
) D
WHERE D.id = sector0_players.id
AND D.points = sector0_players.points
)