The idea of the following script is to add or remove a date to / from a datebase based on the user clicking on a date in the jQuery UI datepicker calendar which I have set up to pick up the date clicked.
I am sending a jQuery.post() to a php page that contains the following code.
The issue is that the value I pick up in the $_POST[] variable will not bind to the PDO->prepare statement and I end up just adding 0000-00-00 to my database!
if (isset($_POST['edit_date'])) {
$edit_date = htmlspecialchars(trim($_POST['edit_date']), ENT_QUOTES);
require_once '../includes/db_cnx.include.php';
// Check if already exists
$query = $db->prepare("SELECT * FROM `dates` WHERE `date` = :date");
$query->bindValue(':date', $edit_date);
print_r($query);
$query->execute();
$num_rows = $query->rowCount();
echo '(num rows: ' . $num_rows . ')';
if ($num_rows === 0 ) {
// INSERT NEW
$query = $db->prepare("INSERT INTO `dates` (`date`) VALUES (:insert_date)");
$query->bindValue(':insert_date', $edit_date, PDO::PARAM_STR);
print_r($query);
$query->execute();
if ($query->rowCount() === 1) {
$return_msg = 'Date added to database';
} else {
$return_msg = 'Could not add date to database';
}
} else if ($num_rows === 1) {
// DELETE EXISTING
$query = $db->prepare("DELETE FROM `dates` WHERE `date` = :delete_date");
$query->bindValue(':delete_date', $edit_date, PDO::PARAM_STR);
print_r($query);
$query->execute();
if ($query->rowCount() === 1) {
$return_msg = 'Date removed from database';
} else {
$return_msg = 'Date could not be removed from database';
}
} else {
// error??
$return_msg = 'More than one entry for this date. Please contact the administrator';
}
echo $return_msg . '- ' . $edit_date;
}
If I output the received $_POST['edit_date'] I see the correct value (e.g. 2013-03-01).
If I output the SELECT statement after binding I see:
PDOStatement Object
(
[queryString] => SELECT * FROM `dates` WHERE `date` = :date
)
Does this mean it has not bound the actual value to :date ?
Even seeing the above showing :date it does seem to be doing its job as I get the correct number of rows back based on whether it found the date or not.
Based on the number of returned rows it then drops into the correct if / else block. But will then show me for example:
(
[queryString] => INSERT INTO `dates` (`date`) VALUES (:insert_date)
)
And I input the 0000-00-00 date as mentioned above.
It's begining to drive me round the bend !
Is it binding even though it's not showing me in the output? And if it is why is it using 000-00-00 rather than my actual values?
Thank you!
EDIT... In case it is helpful the jquery post from the other page looks like this:
onSelect: function(){
var day = $("#datepicker").datepicker('getDate').getDate();
var month = $("#datepicker").datepicker('getDate').getMonth() + 1;
var year = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year + " - " + month + " - " + day;
$.post('admin_functions.php', {"edit_date" : fullDate}, function (data) {
alert(data);
});
}