MySQL select random records with limit - php

I have a query for selecting random records with a limit of 6.
$query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` ORDER BY rand() LIMIT " . $limit);
If I set the limit to 6, it will sometimes only show 4 records, sometimes 5.
How can I make it always show 6?
I have more than 6 records in the database.
I looked at some questions around this here but couldn't find a clear answer.

$query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` ORDER BY rand() LIMIT $limit " );

Try with :
SELECT RAND(6)
$query = $this->pdo->prepare("SELECT * FROM " . $this->table . " ORDER BY RAND(6) LIMIT " . $limit);

Related

CodeIgniter get table count rows

I am new in CodeIgniter, I want to count all rows from database table but i use limit in query and i want all count without use limit how can i do ?
my code is below :
$sql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC
LIMIT $start, $per_page ";
$query = $this->db->query($sql)
i use limit for pagination but i want to get all record from table.
You can add new column in both above and below UNION queries. It will be like below.
select (select count(*) from your_query), your_columns from query_above_union
UNION
select (select count(*) from your_query), your_columns from query_below_union
your_query = your full actual query your are using currently.
Although I am not sure about Codeigniter. But sure about SQl.
* If you count all records with all data including limit, than you can use this code. please check it. I hope it will works for you.*
$countsql = " SELECT intGlCode,fkCategoryGlCode,'C' as acctyp,varEmail,varContactNo as phone,CONCAT(varFirstName,' ',varLastName) as name,dtCreateDate,chrStatus,varMessage as message
FROM " . DB_PREFIX . "Customer WHERE varEmail='$userEmail'
UNION
SELECT intGlCode,'' as fkCategoryGlCode,'P' as acctyp,varEmail,varPhoneNo as phone,varName as name,dtCreateDate,chrStatus,txtDescription as message FROM
" . DB_PREFIX . "Power WHERE varEmail='$userEmail' ORDER BY intGlCode DESC";
$sql = $countsql. " LIMIT $start, $per_page";
$totalRecords = $this->db->query($countsql);
$result["total_rows"] = $totalRecords->num_rows();
$query = $this->db->query($sql);
$result["list"] = $query->result_array();

Selecting data of a 'person'' using LIMIT from table

I was wondering how to fetch data of a person from a table. I found the query to LIMIT data fetch from table. Here is what I got so far:
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
It returns data when LIMIT is available but if the LIMIT exceed the entire data returns null. So how can I know if ROW is available or not in table?
use mysql Count
SELECT count(username) FROM users WHERE username ='xyz'
And your $last_limt is not grater than total count-1
You have to check number of rows of the result from that query before proceeding
$result = mysql_query("SELECT * FROM users WHERE username = '" . $username[$x] . "' LIMIT " . $last_limt . " , " . $nxt_limt . "");
$rowcount=mysql_num_rows($result);
if($rowcount > 0)
{
//next operations
}
else
{
//No more data
}

Why is this PHP / mySQL query giving me an error?

I am generating the first part of the query like this:
while ($all_products = $db->fetch_array($all_prods))
{
$filter_string .= 'AND product_id !=';
$filter_string .= $all_products['item_id'];
$filter_string .= ' ';
}
and then the second part like this:
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
However it's giving me a mySQL syntax error and the $filter_string part strangely adds ' twice before and after the string, so it runs like this:
WHERE user_id='12345' AND active=1 'AND product_id !=0001 AND product_id !=0002 ' ORDER BY RAND ...
What am I doing wrong?
$filter_string adds ' because you put it there. :P
Try with just the double quotes around $filter_string:
$sql_more_items = $db->query("SELECT * FROM db_products WHERE owner_id='" . $user_id . "' AND active=1 " . $filter_string . "ORDER BY RAND() LIMIT 10");
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
Check the way you're performing a string concatenation (putting together strings). It seems like there's a copy/paste error as you're using '" instead of just a "
I would use whitespace (and a good code editor) to your advantage by reformatting your code to look like this:
$queryString = "SELECT * FROM db_products WHERE owner_id='$user_id'"
." AND active=1 " //Note these
. $filter_string //are separated
. "ORDER BY RAND() LIMIT 10 "; //into individual lines
$sql_more_items = $db->query($queryString);
This style helps you keep track of whether you're using " or ' for your strings and also helps you debug things more easily than putting it into one giant hard to read string.
That's probably because of the part
`"' AND active=1 '"`
^.... This ' here

Can a variable be used in Mysql query after WHERE

the below query works and returns results
$query = "SELECT * FROM table WHERE District = '" . $var . "' ORDER BY Form_Date DESC";
where as if I substitute the word "District" with a variable, it doesn't work
$query = "SELECT * FROM table WHERE '" . $distvar . "' = '" . $var . "' ORDER BY Form_Date DESC";
what is wrong with this one and how can I make it work?
Remove the quotes surrounding the field you are testing for, or replace them with backticks to save you from the mysql parser mistaking it for a potentially reserved word:
$query = "SELECT * FROM `table` WHERE `" . $distvar . "` = '" . $var . "' ORDER BY Form_Date DESC";
try this :
$query = "SELECT * FROM table WHERE `" . $distvar . "` = '" . $var . "' ORDER BY Form_Date DESC";
or
$query = "SELECT * FROM table WHERE " . $distvar . " = '" . $var . "' ORDER BY Form_Date DESC";

MySQL - Select differently

I have this query, which selects a distinct value for a column, but I need something else in that query too. I need it to fetch a different row associated with the main select.
Let me illustrate...
This is my query:
$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
mysql_free_result($result);
return $rows;
As you see it returns this query returns the DISTINCT of user_id.
If I use a function like this in a double foreach loop created using the return of the query above:
public function get_donor_status($user_id)
{
global $db;
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$payment_status = $row['payment_status'];
$db->sql_freeresult($result);
return $payment_status;
}
This function would return Completed for user_id 2, but I want it to say Pending instead. How would I change my query so it returns the last value for the corresponding user_id?
If I'm not clear enough, please let me know so I can reexplain.
Just select the last row for the user:
"SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"
How about this?
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";
You can actually get everything in one SQL statement, no need for a double loop:
SELECT
user_id, payment_status
FROM
DONATION_SECURITY_TABLE t1
WHERE
donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
ORDER BY
user_id

Categories