Iggy's Pop
Iggy's Pop

Reputation: 599

How to pass month and year in url

I am displaying a list of months and years from the database like this into a drop-down menu:

$stmt = $link->prepare("SELECT `b_date` FROM `summary` GROUP BY YEAR(`b_date`), MONTH(`b_date`)");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
    while($row = $result->fetch_assoc()) {
        $month = date('F Y', strtotime($row['b_date']));
        echo "<option value='{$month}'>{$month}</option>";
    }
}

When the user clicks on a choice, it redirects to another page like:

mypage.com/results.php?date=

The problem is that I don't know what to set the value as. In the current code the url produced looks like:

php?date=April%202017

That obviously isn't ideal. And the point is that on the results page I need to show results for the month that was selected. So, I need that query string to query the database.

Upvotes: 1

Views: 1083

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Change like this (use urlencode()):-

$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='".urlencode($month)."'>{$month}</option>";

Now on next page check $_GET['date'] and see it's coming proper or not?

if it come proper in format like m-Y then split it with - and now you get month and year separately. Use them in your query or wherever you want.

Query need to be like something:-

$_GET['date'] = '04-2017';

$date_array = explode('-',$_GET['date']);

$month = $date_array[0];
$year  = $date_array[1];

"SELECT * FROM summary WHERE MONTH(<you date column name>) = $month";

Upvotes: 0

TheMY3
TheMY3

Reputation: 353

You can put to select value something like 05-2017:

while($row = $result->fetch_assoc()) {
    $month = date('m-Y', strtotime($row['b_date']));
    echo "<option value='{$month}'>{$month}</option>";
}

And then get it with DateTime object:

$date = DateTime::createFromFormat('m-Y', $_GET['date']);

And then you can format this object to any format you want:

$formated_date = $date->format('Y-m-d');

You can chose another format, but I think you understand my idea.

UPD. To execute all record on this month try to use this code:

$date = DateTime::createFromFormat('m-Y', $_GET['date']);
$stmt = $link->prepare("SELECT * FROM `summary` WHERE YEAR(`b_date`) = :year AND MONTH(`b_date`) = :month");
$stmt->bindParam(':month', $date->format('m'));
$stmt->bindParam(':year', $date->format('Y'));
$stmt->execute();
$result = $stmt->get_result();

I think its working but maybe need to fix.

Upvotes: 1

sentadoensilla
sentadoensilla

Reputation: 1

U can format data in select (postgres, mysql...)

SELECT TO_CHAR('MM-YYYY', b_date) AS formated_date FROM summary GROUP BY TO_CHAR('MM-YYYY', b_date

Upvotes: 0

Related Questions