0

I have a datepicker with the format d/m/Y:

<input type="text" name="date" id="single_cal4" class="form-control has-feedback-left" aria-describedby="inputSuccess2Status4">

If the date is changed I want to run an SQL statement that needs to select the id from the database WHERE the year is the same year as the selected year in the datepicker.

Does someone know how I can run an SQL statement that runs an WHERE with the selected year from the datepicker?

Here is my SQL statement:

$sql = SELECT id FROM `trans` WHERE user_id='". $_SESSION['user_id'] ."' AND year(date) = ";
John
  • 856
  • 5
  • 19
  • 44
  • You will probably need ajax/jquery for this. Basically `onchange` of the datepicker, perform an ajax post/get to another page that will return the results of the query, and then use use javascript/jquery to update the page you are on with the data you just received. – GrumpyCrouton Jul 06 '17 at 20:55
  • You may be able to find more information about this at [jQuery AJAX submit form](https://stackoverflow.com/questions/1960240/jquery-ajax-submit-form) – GrumpyCrouton Jul 06 '17 at 20:58
  • Your question is not clear! if you want to write a sql statement you just did it in your example above. However if your want to send the request immediately after the input is changed so you can use Ajax... – Tohid Dadashnezhad Jul 06 '17 at 21:02
  • Ok, I understand. But with: `#single_cal4` I can select the full date. The sql statement will look like year(date) = `6/7/2017`. But to run the statement I only need the year. How can I only select the year of `#single_cal4` – John Jul 06 '17 at 21:06

1 Answers1

0

Since your supplied date is not the right format for SQL's YEAR() function, I would just use substr on the input as below:

$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$date = mysqli_real_escape_string($link, $_GET['date'];);
$year = substr($date, -4);
$sql = "SELECT id FROM `trans` WHERE user_id=". $_SESSION['user_id'] ." AND YEAR(date)=".$year;

Dont forget to sanitize the input.

Wesley Smith
  • 17,890
  • 15
  • 70
  • 121