Get multiple SQL rows with similar column value - php

I'm making a cron job where it publishes (inserting new into the database) an article. I was able to pull it through but there is one query I can't get to work. I'd like to print certain rows from another table that can be inserted to the article being published. Supposed I have this another table like this:
+----------+-------------+
| filename | released |
+----------+-------------+
| tigers | 2020-05-27 |
| wolves | 2020-05-27 |
| earth | 2020-05-27 |
| bamboo | 2020-05-27 |
| glaciers | 2020-05-02 |
+----------+-------------+
How can I print the result of the filenames as:
bamboo, earth, tigers, wolves
so that the cron can insert it to the article table's specified column with the same format? I've tried using this query below but it only returns one result, which is the tigers filename.
SELECT filename,
GROUP_CONCAT(filename ORDER BY filename ASC SEPARATOR ', ')
FROM table
WHERE released='2020-05-27'
GROUP BY released
Many thanks for the help in advance!

Using TheImpaler's query, I managed to solve what I'm trying to get with the following code:
$get = $database->query("SELECT released,
GROUP_CONCAT(filename ORDER BY filename ASC SEPARATOR ', ')
FROM another
WHERE released='2020-05-27'
GROUP BY released");
$row = mysqli_fetch_array($get);
echo $row['1']; // Prints the comma-separated result of the filenames
echo print_r($row); // Prints the entire row
Many thanks for the comments, it gave me an idea and had my query validated!

Related

How to user order by clause to get records correctly with data in shape of 01/2020

Hi I have some file's records with the number like 01/2020, 02/2020 up to so on and I have used order by clause to get the records in order by these numbers but it return correctly from 01/2020 to 10/2020 then it show me 100/2020 is there a solution? kindly share with me.
If my assumption is correct whereby the format of this record is running_no/year then you need to extract the year to include in order by. Consider example below.
If data is like this:
+----------+
| Value |
+----------+
| 01/2020 |
| 02/2020 |
| 10/2020 |
| 100/2020 |
| 01/2021 |
| 10/2021 |
+----------+
Whereby the 4 digits at the back represent running year, then you can extract the year from if in a few ways. Here I'm showing two example using RIGHT() and SUBSTRING_INDEX().
example 1:
SELECT * FROM table ORDER BY RIGHT(Value,4) ASC, ABS(Value) ASC;
example 2:
SELECT * FROM table ORDER BY SUBSTRING_INDEX(Value,'/',-1) ASC, SUBSTRING_INDEX(Value,'/',1) ASC;
There are more ways to achieve this as long as you can be certain it will return the result the way you want.
My problem has been solved by using ORDER BY ABS(MyField)

Splitting the result in while loop

Here i use a query for getting last two collision occurring dates of a licence number as follows:
<?php
$licence=$_POST['licence'];
$sel=mysqli_query($con,"select cdate from tblcollision where licence_number='$licence'");
while($s=mysqli_fetch_row($sel))
{
echo $s[2];
}
?>
I wish to split the result in to separate fields. That means date1 in a text field and date2 in another text field. Actually i didn't get any idea. Please help me.
My db design is
+--------------------------------------------------+
| CID | ID | LICENCE_NUMBER | CDATE |
+--------------------------------------------------+
| 1 | 1 | 3/4858/2012 | 2018-02-06 |
| 2 | 1 | 3/4858/2012 | 2018-03-20 |
+--------------------------------------------------+
As stated by mickmackusa, if the query is filtered for a single licence number, there is no point to group result in the SQL statement and then explode the result in PHP. Just read the rows and make the calculation on the resulting dates.
However, in a more general way, if dealing with several licences, grouping can be done within the SQL statement. Despite the added cost of exploding the result, it will simplify the grouping process.
You need to use GROUP_CONCAT in your query:
SELECT licence_number, GROUP_CONCAT(cdate) AS Events_dates
FROM tblcollision
WHERE licence_number='$licence'
GROUP BY licence_number;
This will return:
3/4858/2012 | 2018-02-06, 2018-03-20

how to use codeigniter where in on comma seperated row values

I am using codeigniter for my project and implementing search. I want to filter users from users table with cars they own. Structure of this table is shown below
+-----+----------+---------------------+---------------+
| #id | username | cars | other_details |
+-----+----------+---------------------+---------------+
| 1 | MAC | Jaguar,Porche | -- |
| 2 | DEV | Porche,Ferrari,Ford | -- |
| 3 | MONICA | Ford,Audi | -- |
+-----+----------+---------------------+---------------+
On front end, I am selecting cars from checkboxes which are returning car array for find users who have these cars like ["Porche","Ferrari"]. I am not able to find solution for how to get users using codeigniter active records in model. Please help me find out how to get users/rows having cars available in array.
Thanks in advance.
Finally, I find answer.First I had implode array with comma(,) and then use sql query and regular expression for getting an answer like this;
$this->db->sql("select * from users where `cars` NOT REGEXP '$cars'");
This query give data according to my requirement.

How to remove duplicate row considering the Arabic Phonetics

I have a table of Arabic text. I want to remove duplicate rows. In view of the symbols in Arabic language: َ ِ ُ
My table: vocabulary
+----+----------+--------------------------------+
| id | word | mean |
--------------------------------------------------
| 1 | سِلام | xxx |
--------------------------------------------------
| 2 | سَلام | xxx |
--------------------------------------------------
| 3 | سلام | xxx |
--------------------------------------------------
| 4 | سلام | xxx |
+------------------------------------------------+
Now i want this table:
+----+----------+--------------------------------+
| id | word | mean |
--------------------------------------------------
| 1 | سِلام | xxx |
--------------------------------------------------
| 2 | سَلام | xxx |
--------------------------------------------------
| 3 | سلام | xxx |
+------------------------------------------------+
How can i do that ?!
My Try:
$result = mysql_query( "SELECT * FROM vocabulary where");
while($end = mysql_fetch_assoc($result)){
$word = $end["word"];
$mean = $end["mean"];
$id = $end["id"];
$result2 = mysql_query( "SELECT * FROM vocabulary where word='$word' AND mean='$mean'");
$TotalResults = mysql_num_rows($result2);
if($TotalResults>1){
mysql_query( "DELETE FROM vocabulary WHERE id='$id'");
}
Summary: How can I sensitive MySQL to the Arabic symbols ?
There are multiple ways to achieve this.
1- You can either select your rows from the database, loop through them and save the 'word' title in an array, and in each iteration in the loop, you can check if a similar value is in_array(). If the value exists, then you can save the id in another array and then use these ids to delete from the database.
2- Another way to extract the ids is to use a query similar to the below:
select count(*), id from table group by title
You can then loop through the results and delete the row (using the ids) where count is greater than 1.
The basic concept in both (and other methods) is that you just have to match the strings. Phonetics on letters change the actual string so "سَلام" is not equal to "سلام".
On a side note, there is a great Arabic PHP library you can use for various Arabic related string manipulation: PHP and Arabic Language.
This way will only remove one duplicate.
There are several other ways to do it, and it all depends on the size of the data set you have and if deleting these duplicates is a one time thing or a frequent thing because you will have to keep performance in mind.
I haven't tested it, but this should work:
CREATE TEMPORARY TABLE tmp_keeps
SELECT title, MIN(id) AS keepID
FROM theTable
GROUP BY title
;
DELETE FROM theTable
WHERE (title, id) NOT IN (
SELECT title, keepID
FROM tmp_keeps
)
;
DROP TEMPORARY TABLE tmp_keeps;
It (in the subquery) gets the first id for each title, and then deletes rows that don't meet that condition.
Edit: Revised to avoid SQL error pointed out in comments.
If it is a large table, something along the lines of Adon's answer might be faster.

PHP/MySQL - If no rows of a certain type available, load a place holder

So I have this query:
SELECT * FROM cars {$statement} AND deleted = 'no' AND carID NOT IN (SELECT carID FROM reservations WHERE startDate = '".$sqlcoldate."') GROUP BY model
It basically checks the reservations table and then if there are reservations, it gets those carIDs and excludes them from the loop.
This is cool, so as there may be three dodge vipers and 2 are booked out it will only display the last one, and it will only display one at a time anyway because I group the results by model.
All that is good, however when it runs out of entries, so all the cars are booked out, the car does not appear in the list of cars. (As i clear from the query).
I would like a way to say if no rows of a certain car model are in the results, to display a placeholder, that says something like 'UNAVAILABLE'.
Is this possible at all? Its mainly so users can see the company owns that car, but knows its not available on that date.
You should probably handle this in the PHP, checking the number of rows returned and replacing the 0 with "UNAVAILABLE".
Based on TO comment:
In this case you want to look at
http://dev.mysql.com/doc/refman/5.1/en/case.html
This would need to go into the SELECT list like
SELECT
CASE car_count WHEN 0 THEN 'UNAVAILABLE'
WHERE ...
Without seen some of your data, its hard to give you a query, but if you move your subquery to your select expression, you could return the count available (which would be 0 when they are all reserved). Then when you display your data, you could then check if the count is 0, and display your unavailable message.
Edit:
Given the table cars:
+----+----------+
| id | model |
+----+----------+
| 1 | viper |
| 2 | explorer |
| 3 | viper |
| 4 | explorer |
+----+----------+
and the table reservations:
+-------+------------+
| carid | date |
+-------+------------+
| 1 | 2013-03-07 |
| 3 | 2013-03-07 |
+-------+------------+
A query similar to yours above will return:
+----+----------+
| id | model |
+----+----------+
| 2 | explorer |
+----+----------+
If you change it to something like:
SELECT
`outer`.`model`,
(
SELECT COUNT(*)
FROM
`cars` AS `inner`
WHERE
`inner`.`model` = `outer`.`model` AND
`inner`.`id` NOT IN(
SELECT `carid`
FROM `reservations`
WHERE `date` = '2013-03-07'
)
GROUP BY `inner`.`model`
) AS `count`
FROM cars AS `outer`
GROUP BY `outer`.`model`;
then you would get results like:
+----------+-------+
| model | count |
+----------+-------+
| explorer | 2 |
| viper | NULL |
+----------+-------+
If you then needed the NULL value to come back as a 0, you could use COALESCE, as Liv mentioned previously.
It's not pretty, and I'm sure it could be done a much cleaner way, but it does work.
There was a similar question asked here that might get you headed in the right direction. Check out the COALESCE() function.
The built-in function COALESCE() returns the first not-null value in its arguments. This lets you structure queries like SELECT COALSECE(foo, 'bar') [...] such that the result will be the value in column 'foo' if it is not null, or the value 'bar' if it is.

Categories