Ignore param, if not present, in Mysql query - php

In PHP, I wrote a php function in controller getItems, to get all the items when I call through ajax using javascript/jquery. I am passing a param limit to limit the items to get from server.
This works fine but how to use the same method to get all the items? Currently, the below query is working if and only if I provide limit param value.
"SELECT DISTINCT name, id from TABLE_NAME
ORDER BY shared_date DESC
LIMIT #~~limit~~#";
How to get all the items by modifying the same query?
Currently, I am solving this by having two different queries, one with limit and other without limit. (which I feel messy)

One way would be to set the limit as an optional argument in getItems.
For example something like this:
function getItems($limit=false){
$sql = "SELECT DISTINCT name, id from TABLE_NAME
ORDER BY shared_date DESC "
if($limit){
$sql .= "LIMIT $limit";
}
...
}
I don't know if you were going to submit the query in a prepared statement or not, so I left it like this (sql-injectable)

$limit = '';
if ($paramLimit != NULL && is_int($paramLimit)) {
$limit = " LIMIT $paramLimit ";
}
"SELECT DISTINCT name, id from TABLE_NAME
ORDER BY shared_date DESC
$limit";

Related

PDO query appears to be returning DESC order. Ignoring ASC hardcode

Im new to PDO so maybe some subtle nuance that I am not aware of. But I have a query that is supposed to list the drivers by date ASC. The code works the right way, ASC when I test in workbench, so I know the test table data is solid; but when I run the below code in PDO, it does not show any error and returns the record but im seeing the results for DESC order by not ASC like expected. Here's the code:
$selectsql = "SELECT driverid, busid, firstname
FROM drivers
WHERE active= 1
AND day= 1
ORDER BY ? ASC
LIMIT ? ";
$results = $pdo->prepare($selectsql);
$results->execute([$list_date,$count]);
$row = $results->fetchAll();
I get no error and data is returned. Just not in order expected.
I did check and the 2 variables $list_date and $count are set properly.
Does anyone see what it possibly could be?
UPDATE
Im finding that it is sorting by the primary index driversid. I have no idea why.
I think you cannot use a field name as parameter for a prepared statement. You can change your code to something like this:
$selectsql = "SELECT driverid, busid, firstname
FROM drivers
WHERE active= 1
AND day= 1
ORDER BY " . $list_date . " ASC
LIMIT ? ";
$results = $pdo->prepare($selectsql);
$results->execute([$count]);
$row = $results->fetchAll();
You are sorting by a constant expression, not a column, so the sort order will basically be arbitrary (not even random).
If you want to inject code into a SQL statement (such as a column name) you need to use good old string manipulation functions. Prepared statements are specifically designed to avoid that:
$selectsql = "SELECT driverid, busid, firstname
FROM drivers
WHERE active= 1
AND day= 1
ORDER BY $list_date ASC
LIMIT ? ";
$results = $pdo->prepare($selectsql);
$results->execute([$count]);
$row = $results->fetchAll();
Make sure that $list_date is valid SQL you have full control on and not external input.

How to select the top third row in mysql

Guys am trying to select the top/recently third row, i tried this one but it doesn't work, where do i make mistake ?
<?php
$sql = "SELECT * FROM songs ORDER BY id ASC LIMIT 1,2;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['artist'];
}
}
?>
Use OFFSET:
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The shorthand (which you are using) is reversed, so OFFSET is first then LIMIT:
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1;
Use OFFSET
Here the limit 1 It simply means and you need one record
and the offset means skip the first 2
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The parameters you use after limit should be reversed.
The first parameter is offset, and the second parameter is number of record you want.
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1
This is just my opinion--
Sorting like this should always be done in client software.
Extract the data - remove the ORDER BY for your SQL...
Sort it in your client, and select and return the third line to the caller.
You will get better scalability and maintainability than driving all of this through an SQL query.
This is my go-to approach when solving these types of problems through custom software and it has been proven out over time.
Think about this:
Select ID from songs
get the id's into your code, and sort them there. Then chose the third one in the list. Then:
select title, author, artist, ... from songs where ID = VALUE FROM ID ABOVE
Yes, you are hitting the database twice, but these are two very efficient queries and that will perform better as your database scales, than the fancy order by you propose.

Mysql select list after a specific id

I'm trying to find a solution to select a list of rows coming after a certain Id from an ordered list.
For example, first I select 1000 rows. Then, on a subsequent request, i want to fetch another 1000 rows coming from after the last id of the first request. I know i can do it with limit, but suppose there has been 100 rows added between the first and second request, there will be 100 rows that will be from the first request.
Both queries will be ordered by the date of the entries.
Here's an example of the query I thought of:
$query = "SELECT * FROM table WHERE id AFTER $id ORDER BY date DESC";
$query = "SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT 1000";
Two ways to do this:
WHERE
"SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT $length"
LIMIT
"SELECT * FROM `table` LIMIT $start, $length"
$query = "SELECT * FROM table WHERE id > $id ORDER BY date LIMIT 1000";
You're asking about logic, not code so here it is.
The first request selects the first 1000.
$query = "SELECT * FROM the_table ORDER BY `date` DESC LIMIT 0,1000";
NB date is a reserved word so needs escaping if you've called a column "date" which you shouldn't.
$rs=$db->selectMany($query); // replace this with however you select the rows. $rs is results set
Do stuff with PHP and save the maximum id. They may not be in order.
$maxid=0;
foreach ($rs as $r){
// whatever you need to do with your results
$maxid=max($maxid, $r->id);
}
Your subsequent select uses the last id
$query = "SELECT * FROM the_table WHERE id > $maxid ORDER BY date DESC LIMIT 0,1000";
BUT you need to take note that you're ordering by date and using id to find a breakpoint which sounds like it would cause data to be missed.
Perhaps you mean to use WHERE`date`> $maxdate? If so you can figure that out from the code given.

PHP & MySQL - Limiting an array

I'm trying to limit the array mysql_fetch_assoc($query), and am unsure on how I would go about it.
$query = mysql_query('SELECT * FROM table ORDER BY id DESC');
while($output = mysql_fetch_assoc($query))
{
//do something
}
Do you add a counter or something? How do you add this counter?
I'm really confused about mysql_query and mysql_fetch_assoc. Please Help!
After your ORDER BY id DESC, add LIMIT 100 (or whatever number you want). For the next 100 rows, use LIMIT 100,100, then LIMIT 200,100 and so on.
You can limit the results directly in the SQL query. To get the top 100 records do
SELECT * FROM table
ORDER BY id DESC
LIMIT 100
Use LIMIT
SELECT * FROM table ORDER BY `id` DESC LIMIT 10;
Haven't you seen phpMyAdmin always limiting to 30?

Select a Random Database Row WHERE ID=a random value created by PHP function

If I have a PHP function that generates a random number, is it possible to pass that variable into the sql statement in the WHERE clause? I'm using CodeIgniter, so this is my code using its syntax.
$random = rand(1, 572);
$result = $this->db->query( ' SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ');
Is this even possible to do?
EDIT: The reason I want the php to execute the random number is because I need to call it multiple times throughout my pages, and it needs to do another call to another database using a sql query
Yes it is possible if you concatenate the variable with the string:
$query = "SELECT
part1,
part2,
_id
FROM
questions
WHERE _id >= " . $random . " LIMIT 0,1";
$result = $this->db->query($query);
But if what you want is to select a random row, then you might want this query
SELECT part1, part2, _id FROM questions ORDER BY RAND() LIMIT 1
EDIT
I understand that _id will be random, but you are specifying the min and max for rand(), right? So you'd have to change it whenever you insert a new row, or you'd have to use two queries if you want to make sure rand() does not return a value too high. By using ORDER BY RAND() you are free from both problems. You simply have to get the value of _id that was returned from the query.
This might just be a mater of using double quotes instead of single quotes on the outside of your string.
$result = $this->db->query("SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ");
Try this:
$result = $this->db->query("SELECT part1, part2, _id FROM questions WHERE _id >= '".$random."' LIMIT 0,1 ");

Categories