Heres the problem...
I have a loop looking like this selecting stuff from my database.
$query = "SELECT * FROM table WHERE publish <= CURDATE() AND active = 'Yes' AND (YEAR(begin) = YEAR(CURDATE()) OR YEAR(begin) = YEAR(CURDATE()) + 1) ORDER BY begin ASC";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet))
{
$newsArray = array();
while ($newsResult = mysql_fetch_array($resultSet))
{
$newDate = $newsResult['begin'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',strtotime($timePeriod));
$timePeriodM = date('F',strtotime($timePeriod));
if (!isset($newsArray[$timePeriod]))
{
$newsArray[$timePeriod] = array();
}
$newsArray[$timePeriod][] = $newsResult;
}
foreach ($newsArray as $timePeriod => $newsItems)
{
$timePeriodY = date('Y',strtotime($timePeriod));
if ($timePeriodY == $thisYear){
}
else if ($timePeriodY == $nextYear){
}
echo '<h2 class="year>'.$timePeriodY.'</h2>';
echo '<ul class="column">';
foreach ($newsArray as $timePeriod => $newsItems)
{
$timePeriodMonth = date('Y',strtotime($timePeriod));
if ($timePeriodY == $timePeriodMonth) {
$moSe = strftime('%B',strtotime($timePeriod));
$MonthSe = ucfirst($moSe);
$seMonth = str_replace($dateSearch,$dateReplace,date('F',strtotime($timePeriod)));
echo $seMonth;
foreach ($newsItems as $item)
{
$ad_event = date("Y-m-d",strtotime($item['event_end']));
$today = date("Y-m-d");
$dayMod = strftime('%e',strtotime($item['event_begin']));
$seDay = str_replace($dateSearch,$dateReplace,date('D',strtotime($item['event_begin'])));
echo ''.$seDay.' '.$dayMod.' - '.$item['event_title'].'';
echo '</div>';
}
}
}
}
}
else
{
echo '';
}
This code outputs the data for each row and separates it for year month day etc. However some of the data is on the same day. Thats fine BUT when data is on the same day i want a variable that holds only the last of the items on that same day.
EX.
DB
PUBLISH ID NAME
2011-05-05 1 test 1
2011-05-05 2 test 2
2011-05-06 3 test 3
The result I would like from this is something like this
RESULT
test 1 ID 1 PUBLISH 2011-05-05 VARIABLE 2 <<-- see the variable that comes from test 2 row
test 2 ID 2 PUBLISH 2011-05-05 VARIABLE 2
test 3 ID 3 PUBLISH 2011-05-06 VARIABLE 3
Meaning test 1 in this case holds information about test 2 since test 2 is after test 1 and they both have the same date. If there is only one on the specific date as test 2 and 3 just echo the same id as the variable.
Any ideas? PLease tell me if i need to explain this even more :)
Thanks a lot for any help!
Group by date(begin)as you want only 1 record on the same date(begin) and since you want the latest order by dsc on column 'begin' (I believe the 'begin' is stored as datetime else you need to have dsc on table.ID)
$query = "SELECT *
FROM table
WHERE publish <= CURDATE()
AND active = 'Yes'
AND (YEAR(begin) = YEAR(CURDATE())
OR YEAR(begin) = YEAR(CURDATE()) + 1)
GROUP BY begin
ORDER BY begin DSC";
Related
I have all records in sequence from 1 onwards for each record displayed but wish to update each one with that sequence in a field within the table.
Any help?
if(isset($_POST['setorder']))
{
$i = 1;
//$today = date('Y-m-d', strtotime('-1 day'));
$routesql = $mysqli->query("SELECT * FROM routes WHERE status = 1");
while ($routerows = $routesql->fetch_array())
{
$rname = $routerows['routename'];
$routejobs = $mysqli->query("select tracking.*, district.* from tracking left join district on tracking.street = district.street
where tracking.date = '$today' AND tracking.status = 2 and route = '$rname' order by district.sortorder asc");
while ($routejrows = $routejobs->fetch_array())
{
echo $i.' - '.$routejrows['joborder'].' - '.$routejrows['addressto'];
echo '<br/>';
$i++;
}
}
}
I have the issue with LIMIT with foreach using PHP.
Basics: I have 50 different tables and in every table I have 2 rows.
When I try to add LIMIT 1 to $$modules_for_all, then I see 50 rows, but I want to see only 1. If I add LIMIT 2, then I see 100 rows.
How I can connect all these tables as a one LIMIT 1 to get 1 row in foreach?
<?php
for ($i = 1; $i <= 50; $i++) {
// $array_table_name contains names with tables
$table_names = $array_table_name[$i];
$modules_for_all = 'g_module_for_all_'.$i;
$$modules_for_all = $db->QueryFetchArrayAll("SELECT * FROM $table_names WHERE user='1' LIMIT 1");
}
for ($i = 1; $i <= 50; $i++) {
$modules_for_from = ${"g_module_for_all_$i"};
foreach ($modules_for_from as $m_foreach_as) {
echo $m_foreach_as['id'];
}
}
Example tables:
table_1
id date_added
1 2018-12-01 00:00:00
2 2018-12-02 00:00:00
table_2
id date_added
1 2018-12-03 00:00:00
2 2018-12-04 00:00:00
table_3
id date_added
1 2018-12-05 00:00:00
2 2018-12-06 00:00:00
Example foreach:
<?php
$array_table_name_1 = 'table_1';
$array_table_name_2 = 'table_2';
$array_table_name_3 = 'table_3';
$for_table_1 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_1 WHERE id='1' LIMIT 1 ORDER BY date_added");
$for_table_2 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_2 WHERE id='1' LIMIT 1 ORDER BY date_added");
$for_table_3 = $db->QueryFetchArrayAll("SELECT * FROM $array_table_name_3 WHERE id='1' LIMIT 1 ORDER BY date_added");
foreach ($for_table_1 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
foreach ($for_table_2 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
foreach ($for_table_3 as $m_foreach_as) {
echo $m_foreach_as['id'];
}
// Now result is '111' but I want only '1' (realted to make LIMIT 1 to all foreach)
The only way to connect the tables is by using a UNION. So you will need to build one large UNION query and then perform the select after the loop:
$tables = array();
for ($i = 1; $i <= 50; $i++) {
// $array_table_name contains names with tables
$table_names = $array_table_name[$i];
$tables[] = "(SELECT * FROM $table_names WHERE user='1')";
}
$query = implode(" UNION ", $tables) . " ORDER BY date_added LIMIT 1";
$result = $db->QueryFetchArrayAll($query);
foreach ($result as $row) {
echo $row;
}
You are gonna have to use UNION ALL for summing this rows together before ordering and limiting the results.
But keep in mind that a query like this will only work if all the tables in your array have the same structure. If they do not, then you will have to be specific in the query to make them have the same fields.
$array_table_name = [
'table_1',
'table_2',
'table_3',
];
$search_id = 1;
$selectsArray = [];
foreach ($array_table_name as $table_name) {
$selectsArray[] = "SELECT * FROM $table_name WHERE id='$search_id'\n";
}
As you see, I am using foreach() and not for() so you won't update the for by decreasing/increasing the number of tables in the array. So to finally have:
$selectsUnion = implode("UNION ALL\n", $selectsArray) . "ORDER BY date_added \nLIMIT 1";
You can see the code tested and query mounted here: https://3v4l.org/HXH2K
I solved my problem using this: foreach ($modules_for_from as $m_foreach_as) if ($tmp++ < 1) {
I have a table with a status column and date column. I need to add 3 days to my date from the DB expecting weekends if status is 2 or 6. Here is my code:
$selectall = sqlsrv_query($conn, "select * from Table where and Status = 2 or status = 6", $params, $options);
while($fetchall = sqlsrv_fetch_array($selectall))
{
$id = $fetchall['DATAID'];
$dates = $fetchall['DATE'];
if( 3 DAYS PAST )
{
sqlsrv_query($conn, "UPDATE TABLE SET STATUS=5 WHERE DATAID=$ID")
}
}
I don't see how is this a JS question, but anyhow, you need to calculate date range in your php code and put that date range into your SQL query. AKA you take the start date, check which weekday it currently is and do respective mathematical calculations to add additional days.
I would use something like this around my date variable
select
DATEADD(d,
case when datepart(dw,'2017-05-17')=6 then 6
when datepart(dw,'2017-05-17')=7 then 5
when datepart(dw,'2017-05-17')=1 then 4
when datepart(dw,dateadd(d,3,'2017-05-17'))=7 then 5
when datepart(dw,dateadd(d,3,'2017-05-17'))=1 then 4
else 3
end
,'2017-05-17')
$selectall = sqlsrv_query($conn, "select * from Table where and Status = 2 or status = 6", $params, $options);
while($fetchall = sqlsrv_fetch_array($selectall))
{
$DATAID= $fetchall['DATAID'];
$dates = $fetchall['DATE'];
$p = date("l");
switch ($p)
{
case "Wednesday" || "Thursday" || "Friday":
$day = '-5 days';
break;
default:
$day = '-3 days';
}
$s = date($dates);
$today = date('Y-m-d');
$totalday = date('Y-m-d', strtotime($day));
if($totalday <= $s)
{
sqlsrv_query($conn, "UPDATE table SET STATUS = 5 WHERE DATAID=$dataid");
}
}
i'm not that good with php, but I did the code below and hope for some little help:
<?php
$next = '';
$result = mysql_query("SELECT ID FROM table WHERE x_column < '$x_column_variable' AND Column = '$column_variable' ORDER BY x_column DESC LIMIT 1");
while($row=mysql_fetch_array($result)) {
$next_id = $row['ID'];
if ($next_id != '') {
$next = '<img src="img/next.jpg"/>';
}
}
?>
The code works but when i have multiple ids with the same x_column value, it gives me only the first one and jump to the next x_column value.
Ex: if i have
12 78 2 2 1
i get only
78 12 2 1
I have a problem realizing some output to echo a list of results that comes from an Array.
I would like to create a Live search engine that runs a query by the help of keyup-function by using AJAX.
Everything works fine when the output will be echoed for every match that is listed in the table.
Now I would like to to combine all entries that are duplicates.
The code is like:
$search_term = $_POST['search_term'];
$where = "";
$search_term = preg_split('/[\s]+/', $search_term, -1, PREG_SPLIT_NO_EMPTY);
$total_search_terms = count($search_term);
$total_search_term = 0;
foreach ($search_term as $key=>$value) {
$total_search_term = $total_search_term + 1;
if ($total_search_term === 1){
if (is_numeric($value) ){
$where .= "(`a` LIKE '%$value%')";
} else {
$where .= "(`b` LIKE '%$value%')";
}
}else if ($total_search_term > 1){
$where .= " AND ";
if (is_numeric($value) ){
$where .= "(`a` LIKE '%$value%')";
} else {
$where .= "(`b` LIKE '%$value%')";
}
}
}
$duplicate = $db->query("SELECT a, b, COUNT(*) counter
FROM `table`
GROUP BY a, b
HAVING COUNT(*) > 1
");
$check = $duplicate->fetch_assoc();
$query = $db->query("SELECT a, b FROM table WHERE $where");
$result = $query->num_rows;
if ($result !== 0 ){
echo '<li id="hit">There are $result results!</li>';
while ($row = $query->fetch_assoc() ) {
echo '<li>',
$row["a"],
' ',
$row["b"],
'</li>';
}
} else {
echo '<li id="hit">no result!</li>';
}
To give an example of the output:
There are 3 results!
12345 New
12345 New
56789 Chicago
And thats how it should be:
There are 3 results!
12345 New (2x)
56789 Chicago
So the table is:
a | b
12345 New
12345 New
56789 Chicago
Thanks alot.
I thought of something like this:
$query = $db->query("SELECT a, b, COUNT(*) counter FROM `table` WHERE ".$where." GROUP BY a, b");
$result = $query->num_rows;
if ($result !== 0 ){
$resultSizeQuery = $db->query("SELECT COUNT(*) counter FROM `table` WHERE ".$where);
$resultSize = $resultSizeQuery->fetch_assoc();
echo '<li id="hit">There are '.$resultSize["counter"].' results!</li>';
while ($row = $query->fetch_assoc() ) {
echo '<li>'.$row["a"].' '.$row["b"];
echo ($row["counter"] > 1 ? " (".$row["counter"]."x)" : "");
echo '</li>';
}
} else {
echo '<li id="hit">no result!</li>';
}
Replacing all lines from "$duplicates = ..." to the end it should do it's work. Just give it a try because sometimes the step before the problem should be thought over.
Regards
parascus
first of all, your statement will return just 1 line with New York and the column counter will have 2. Chicago is missing because counter is just 1.
So I think your result looks like:
Ther are 1 results!
12345 New York
If you want to have "3 results" jsut do 2 queries, one for the number of rows (just leave out the group and having clause, also don't ask for a and b).
So you get the output:
There are 3 results!
Next you have to omit the having clause for getting all rows (also those without duplicates). You could write something like:
echo ($row["a"].' '.$row["b"].($row["counter"] > 1 ? " (".$row["counter"]."x)" : "")
I hope this helps.
Regards
Parascus