I have this query in laravel
$listings = DB::select('select auction.*, product.* from auction as auction inner join
product as product on auction.productID=product.id where auction.sold=0 and auction.endDate != NOW() order by auction.created_at desc limit 10');
Now I want to get the id on the last row or the 10th row of the result set $listings. How could I do that?
I couldn't use this kind of code $lastID = Auction::orderby('created_at','desc')->first() because it fetches the last row from the table and not from the result set.
You may try this to get the last record from the result set:
$listings = DB::select('select auction.*, ... limit 10');
$last = end($listings);
Now get the id:
$id = $last->id;
Related
I use this code to show category from database
$select_newscats = $mysqli->query("SELECT * FROM news_cats order by ord_show asc");
while ($rows_newscats = $select_newscats->fetch_array(MYSQL_ASSOC)){
$id_newscats = $rows_newscats ['id'];
$title_newscats = $rows_newscats ['title'];
$ord_show_newscats = $rows_newscats ['ord_show'];
$icon_newscats = $rows_newscats ['icon'];
$kind_newscats = $rows_newscats ['kind'];
$description_newscats = $rows_newscats ['description'];
//here is my data
}
i have in news table row for categoies it's name is cats and i insert data inside it like that 1,5,6,8
and i use this code to count news inside each cat
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
it gets only first value for example if i have this values 1,5,6,8 it gets only 1 the first value
I would do the counting in a single sql call, not with php logic and separate sql calls. For this I would join the 2 tables using left join and use a join condition instead of an in clause:
SELECT nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description, count(n.id) as newsnum
FROM news_cats nc
LEFT JOIN news n ON nc.id=n.cats
GROUP BY nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description
ORDER BY nc.ord_show asc
Obviously, make sure that the join condition is the right one. When you loop through the resultset, the number of news per category will be in the newsnum field.
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
Here $rows_newsnum will only return the first row in the database.
Fetch Array only returns one row at a time, and then moves the row pointer forward. For example the following code on the dataset you provided (1, 5, 6, 8).
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 1
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 5
What you need to do is move it into a while loop (like your first example) to get to access each row, like below:
while($row = $select_newsnum->fetch_array(MYSQL_ASSOC)) {
echo $rows_newsnum["id"] . ", ";
}
// Will produce:
// 1, 5, 6, 8,
If you just want to get a count
Your existing code should work fine. And you can omit the call to fetch_array.
$num_newsnum = $select_newsnum->num_rows;
echo $num_newsnum; // Will display 4
Read more about fetch_array on the PHP documentation:
http://php.net/manual/en/mysqli-result.fetch-array.php
Hope this helps.
I thought this would be simple but I'm having a tough time figuring out why this won't populate the the data array.
This simple query works fine:
$queryPrice = "SELECT price FROM price_chart ORDER BY id ASC LIMIT 50";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
But instead I want it to choose the last 10 results in Ascending order. I found on other SO questions to use a subquery but every example I try gives no output and no error ??
Tried the below, DOESN'T WORK:
$queryPrice = "SELECT * FROM (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
I also tried specifying the table name again and using the IN, also doesn't work:
$queryPrice = "SELECT price FROM price_chart IN (SELECT price FROM price_chart ORDER BY id DESC LIMIT 10) ORDER BY id";
$resultPrice = mysqli_query($conn, $queryPrice);
$data = array();
while ($row = mysqli_fetch_array($resultPrice)) {
$data[] = $row[0];
}
In both examples my array is blank instead of returning the last 10 results and there are no errors, so I must be doing the subquery wrong and it is returning 0 rows.
The subquery doesn't select the id column, so you can't order by it in the outer query. Also, MySQL requires that you assign an alias when you use a subquery in a FROM or JOIN clause.
$queryPrice = "SELECT *
FROM (SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) x ORDER BY id ASC";
$resultPrice = mysqli_query($conn, $queryPrice) or die (mysqli_error($conn));
$data = array();
while ($row = mysqli_fetch_assoc($resultPrice)) {
$data[] = $row['price'];
}
You would have been notified of these errors if you called mysqli_error() when the query fails.
Your second query is the closest. However you need a table alias. (You would have seen this if you were kicking out errors in your sql. Note you will need to add any field that you wish to order by in your subquery. In this case it is id.
Try this:
SELECT * FROM (SELECT price, id
FROM price_chart ORDER BY id DESC LIMIT 10) as prices
ORDER BY id ASC
You must have errors, because your SQL queries are in fact incorrect.
First, how to tell you have errors:
$resultPrice = mysqli_query (whatever);
if ( !$resultprice ) echo mysqli_error($conn);
Second: subqueries in MySQL need aliases. So you need this:
SELECT * FROM (
SELECT id, price
FROM price_chart
ORDER BY id DESC LIMIT 10
) AS a
ORDER BY id ASC";
See the ) AS a? That's the table alias.
Thanks for helping, first I will show code:
$dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESSION['user_id']."' and contracts.customer_contract = ".$_SESSION['user_id']." order by COUNT(contracts.customer_contract) DESC limit $limit, $pocetZaznamu ";
I need to get the lists of users (customers table) ordered by count of contracts(contracts table)
I tried to solve this by searching over there, but I can't... if you help me please and explain how it works, thank you! :) $pocetZanamu is Number of records.
I need get users (name, surname etc...) from table customers, ordered by number of contracts in contracts table, where is contract_id, customer_contract (user id)..
This should do it where is the column name you are counting.
$id = $_SESSION['user_id'] ;
$dotaz = "Select COUNT(`customer_contract`) AS CNT, `customer_contract` FROM `contracts` WHERE `user_id`=$id GROUP BY `customer_contract` ORDER BY `CNT` DESC";
Depending on what you are doing you may want to store the results in an array, then process each element in the array separately.
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
$contracts[$row[1]] = $row[0];
}
foreach ($contracts AS $customer_contract => $count){
Process each user id code here
}
Not sure what you are counting. The above counts the customer_contract for a table with multiple records containing the same value in the customer_contract column.
If you just want the total number of records with the same user_id then you'd use:
$dotaz = "Select 1 FROM `contracts` WHERE `user_id`=$id";
$results = $mysqli->query($dotaz);
$count = mysql_num_rows($results);
I am trying to get the first id with a specific date.
So this is my code:
$checkm = "SELECT FIRST(id) FROM times WHERE date='2014-03-07'";
$resultm = mysqli_query($con,$checkm);
I have a table called times and there are some columns. Two of them are date and id.
I am trying to get the first row's id with the date 2014-03-07.
EDIT: Fixed!
$checkm = "SELECT id FROM times WHERE date='2014-03-06' ORDER BY id ASC LIMIT 1";
$resultm = mysqli_query($con,$checkm);
while($row = mysqli_fetch_array($resultm)) {
$resultm1 = $row['id'];
}
You probably want the minimum id.
SELECT min(id)
FROM times
WHERE date = '2014-03-07'
pretty straightforward...
SELECT id FROM times WHERE date='2014-03-07' ORDER BY id ASC LIMIT 1
I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT