Get the highest id from a specific where clause - php

I have 4 records on my guests database.
I'm trying to query to the guest that has note_display = 1 and have the highest id.
I've tried
$last_note = DB::table('guests')->where('note_display','=',1)->where('id', DB::raw("(select max(`id`) from guests)"))->first();
I got
Trying to get property of non-object
I'm a lil stuck now, any hints will be a huge helps ?

There is no need to use raw in this query. You can run a simple query like
Guest::where('note_display', 1)->orderBy('id', 'desc')->first();
And it will return the Guest with the highest ID and having note_display = 1.

The raw sql string should be something like SELECT * FROM guests WHERE note_display = 1 ORDER BY id DESC LIMIT 1 it looks you are getting only rows with note_display = 1 inside a sub-query WHERE id={the maximum id present in the table}

It select the maximum of id where the the note_display is = 0, so the try to get non-object error happened.
If you're insisting to go with raw try this!
$last_note = DB::table('guests')->where('id', DB::raw("(select max(`id`) from guests where note_display = '1')"))->first();

Related

Selecting data from 2 tables where columns are the same, query not quite right?

I'm trying to fetch data from 2 tables where the prop_slug and prop_gallery_id match. I've written the following statement only I cant seem to get it to work and keep getting an error with my syntax - can anybody see if there's a glaring mistake in my query?...
$listings = $db->query('
SELECT *
FROM listing_details
JOIN prop_gallery
ON prop_gallery.prop_gallery_id = listing_details.prop_slug
WHERE (listing_details.prop_slug LIKE \'prop_gallery_id\' OR prop_gallery.prop_gallery_id LIKE \'prop_slug\')
AND
WHERE listing_details.prop_mandate = 1
LIMIT 3')->fetchAll();
You don't need the second WHERE
$listings = $db->query('
SELECT *
FROM listing_details
JOIN prop_gallery
ON prop_gallery.prop_gallery_id = listing_details.prop_slug
WHERE (listing_details.prop_slug LIKE \'prop_gallery_id\' OR prop_gallery.prop_gallery_id LIKE \'prop_slug\')
AND listing_details.prop_mandate = 1
LIMIT 3')->fetchAll();

Laravel : Select and GroupBy SQL Query Error. Multiple Selects with groupBy? Is it Possible?

I have an 2 tables Ratings and Attributes , i pass the month and get all record of both users and count this , i have already count this record , and divided into groups by user_id , But in my attribute table i have a user name , and join this table to get attribute name , My query is that
$months = \Request::get('month');
$records = DB::table("ratings")
->select(DB::raw("SUM(ratings.attribute_score) as score"))
->whereRaw('MONTH(ratings.created_at) = '.$months)
->join('users','ratings.user_id','=','users.id')
->groupBy('ratings.user_id')
->get();
dd($records);
And get json like that
But i want to get name of the specific user with score but here multiple selects not working in this query how to use multiple select to get attributes table records? if i am using this query. Thanks Developers in advance
->select(DB::raw("SUM(ratings.attribute_score) as score , ratings.user_id , attributes.attributes_name"))
Using this the select not working here it always return the score Jason like show in the Sceenshot. How can i do to selects multiples using groupBy??
USE THIS TO GET USERNAME WITH SCORE COUNTS. Try This
$months = \Request::get('month');
$records = DB::table("ratings")
->select(DB::raw('SUM(ratings.attribute_score) as score, users.name as
user_name'))
->whereRaw('MONTH(ratings.created_at) = '.$months)
->join('users','ratings.user_id','=','users.id')
->groupBy('users.name')
->get();
return view('attribute.show' , compact('records'));

How to get Distinct rows in Laravel

I have 6 Records in following Table
I Need to get Unique Leads id Columns Order by id DESC.
Following is my Query
Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC')->count();
Its Return Number of Records is : 1
Just Add distinct
Telecallerfirststep::WhereDate('created_at',date('Y-m-d'))-
>groupBy('leadsid')->OrderBy('id','DESC')->distinct()->count();
You should try this:
Telecallerfirststep::whereDate('created_at','=',date('Y-m-d'))->groupBy('leadsid')->count();
Use php count after fetching result
$reault = Telecallerfirststep::whereDate('created_at',date('Y-m-d'))->groupBy('leadsid')->OrderBy('id','DESC');
echo $count = count($reault);
I found similar issue MySql and SO

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

Did I mess up my where clause? Getting unexpected results

$active_sth = $dbh->prepare("SELECT * FROM user_campaign
WHERE status='blasting'
OR status='ready'
OR status='followup_hold'
OR status='initial_hold'
AND uid=:uid
ORDER BY status ASC");
$active_sth->bindParam(':uid', $_SESSION['uid']['id']);
$active_sth->execute();
I am positive $_SESSION['uid']['id'] = 7
but it will also pull results of id 10 or any other number.
Is my AND/OR clause written wrong?
Yes, query is wrong
SELECT * FROM user_campaign
WHERE (
status='blasting'
OR status='ready'
OR status='followup_hold'
OR status='initial_hold'
)
AND uid=:uid
ORDER BY status ASC
You have to group all ORs to make sure that row got one of this values, and separately check if it have given uid.
The proper way to write that is:
SELECT * FROM user_campaign
WHERE status IN ('blasting', 'ready', 'followup_hold', 'initial_hold')
AND uid =: uid
ORDER BY status ASC
You should use IN instead of that huge amount of ORs :)

Categories