PHP variable assignment from javascript for MySQL query, not working

Happy New Year everyone.

I am a novice at both PHP and javascripts, so please bear with me a little and no flames.

In my website, I would like to run a DB query and display the results based on the client side time. So my PHP script would have to be modified to bring in the date and month values using a call to a javascript. Below are the portions of my code. Please tell me where I am going wrong.

The initial assignments in the PHP script (trying only with the month first):

[php]/* Init Block /
/
$todayMN = date(“m”); /
$todayDN = date(“d”);
/
Pradeep. Dec. 27, 2014: Getting the date and time from client side for DB query /
$todayMN = ‘’;
/
$todayDay = ‘’; */[/php]

The javascript:

currentTime = new Date()
month = currentTime.getMonth()
month = month + 1;
if (month < 10){
month = “0” + month;
}

document.write(month);

Later in the PHP script:

[php]//** Family Born this day.
function getBirthToday($targs) {
global $people_table, $sLstr, $bPlaceLen, $bDayHeader, $URLpath, $todayMN, $todayDN, $sPerson;
$cacheName = ‘tngBornToday.cache’;
/* Pradeep. Dec. 27, 2014: Getting the date and time from client side for DB query */
print $todayMN . " day " . $todayDN;

		//** Pradeep May 17, 2014
		//** Added "living" to the query below.
		$qry = "
           SELECT personID,firstname,lastname,birthdate,birthplace,gedcom,living,YEAR(birthdatetr) AS lYear 
			   FROM $people_table 
			   WHERE" . $treeInsert . "
			   month(birthdatetr) = $todayMN
			   AND dayofmonth(birthdatetr) = $todayDN $sLstr ORDER BY lYear
			   ";
			   
		$results = qryDB($qry);[/php]

The “qryDB” function is:

[php]//** Query Database
function qryDB($qry) {
global $link;
$result = mysql_query($qry) or die (“Query ERROR: $qry”);
return $result;
}[/php]

Issue:

When this code is run with the month determined by the PHP code, the results are just fine. However, when the assignment comes from the javascript, it returns an error from the “qryDB” function, thusly:

Query ERROR: SELECT personID,firstname,lastname,birthdate,birthplace,gedcom,living,YEAR(birthdatetr) AS lYear FROM tng_people WHERE month(birthdatetr) =01 AND dayofmonth(birthdatetr) = 01 ORDER BY lYear

The assignments for the month and the year are as expected, yet the DB query does not work.

Looking in the logs for the DB server, I see the following:

150101 14:15:45 12 Connect @on
12 Query SET NAMES utf8
12 Init DB
12 Query SELECT userID FROM tng_users
12 Quit
7 Init DB
7 Query SELECT * FROM tng_mediatypes ORDER BY ordernum, display
7 Query SELECT languageID, display, folder FROM tng_languages ORDER BY display
7 Query SELECT personID,firstname,lastname,birthdate,birthplace,gedcom,living,YEAR(birthdatetr) AS lYear
FROM tng_people
WHERE
month(birthdatetr) =
AND dayofmonth(birthdatetr) = 01 ORDER BY lYear

So, what goes into the DB for query is the call of the javascript. However, all the debug statements, and even the error message, says the assignment is correct.

What am I doing wrong? Thank you in advance.

You’re using obsolete php in mysql instead of msyqli or PDO (My recommendation), you might as use the current stuff instead of the obsolete just my opinion. Using way to many global variables, in fact you really shouldn’t be using any global variables.

However you major problem is JavaScript is a Client-side programming language (Think Client Browser) and PHP is a server-side language. So by the time JavaScript needs to access the variable done in PHP, the PHP code has already pass it by. So what you need is something that can handle the traffic, an Ajax is one of those languages (although I don’t think technically it is a stand-alone language, but I could be wrong). Anyways, my suggestion is to use a JavaScript library, my preference is JQuery. I know JavaScript purists scrounge when I suggest doing this, but I don’t care. ;D Anyways, there are other ways in getting a PHP variable into JavaScript, but for a novice I think it could get a little tricky or you’ll get it to work for this project not knowing how you got it to work.

Here is a simple little countdown clock that I did:
countDownClock.php file:
[php]<?php
session_start();
date_default_timezone_set(‘America/Detroit’); // Set the Default Time Zone:

if (isset($_POST[‘action’]) && $_POST[‘action’] == ‘enter’) {
$futureDate = date(‘Y-m-d H:i:s’,strtotime($_POST[‘futureDate’]));
$_SESSION[‘future’] = $futureDate;
}
?>

The Count Down Clock <?php echo (isset($futureDate)) ? '

' . $futureDate . '

' : '

Detroit Tigers Opening Day is 2015-04-06

'; ?> Enter Future Date:
[/php]

The JQuery:
web.countdown.ajax.02.js
[php]$(function() {
/* The Countdown Timer to call the Ajax Method */
var updateTime = setInterval(displayTime, 1000);

/* The Ajax Method of Getting Time */
function displayTime() {
	var $clock = $('.clock');
	
		$.ajax({ // Start of ajax:
			url: 'sendCountDown.02.php',   // Pulling time from the server:         
			dataType: "json", // Format type:
			success: function(info) { // Grab the data from php and then display it:
				
				// Variables * Self-Explanatory *
				var days       =  info.countDown.days, // Grab total days till expiration:
						hours      =  info.countDown.h, // Grab total hours till expiration:
				    minutes    =  info.countDown.i, // Grab total mins till expiration:
						seconds    =  info.countDown.s, // Grab total secs till expiration:
						$msg       =  ''; 
													
						if (hours < 10) {
							hours = '0' + hours;
						}
						
						if (minutes < 10) {
							minutes = '0' + minutes;
						}
						
						if (seconds < 10) {
							seconds = '0' + seconds;	
						}
						
						$msg =  days + ' Days '  + hours + ' Hours ' + 				
						 minutes + ' Minutes ' + seconds + ' Seconds';
						
						/* Display Time in Message */				 
						$clock.text($msg);										
						
					},
					error: function (response) {
						var r = jQuery.parseJSON(response.responseText);
							alert("Message: " + r.Message);
							alert("StackTrace: " + r.StackTrace);
							alert("ExceptionType: " + r.ExceptionType);
						}
					}); // End of ajax call:
					
} // End of Function:	

}); // END OF DOC READY:[/php]

sendCountDown.02.php
[php]<?php
date_default_timezone_set(‘America/Detroit’); // Set the Default Time Zone:

session_start();

$future = (isset($_SESSION[‘future’])) ? $_SESSION[‘future’] : ‘2015-04-06 13:08:00’;

$expired = new DateTime($future);
$now = new DateTime();

$e[‘countDown’] = $now->diff($expired, true);

print json_encode($e); // JSON

[/php]

This is just an example on how one would go about handshaking between JavaScript and PHP. HTH

Thank you Strider64 for responding. I am looking into your example and still trying to get my head around it. I admit, it is quite advanced for me. I am novice, remember, and this is a code that I adopted.

Secondly, I humbly beg to differ on the following statement made by you:

[center]So by the time JavaScript needs to access the variable done in PHP, the PHP code has already pass it by[/center].

In my code, I specifically, get a print statement to see what the variables got assigned prior to executing the DB query and it does clearly show the correct value for the month. This can only come from the javascript. Additionally, the error statement (out of the “qryDB” function) also prints the correct values.

Is there an easier way to achieve the objective?

It can not come from JS according to the code you have shown.

The execution of your code goes like this
User requests yoursite.com/page.php
Apache gets the request and according to config passes it on to the PHP engine
PHP code executes
Resulting output is sent back to the user
after this point you can not execute PHP unless reloading/changing page or doing Ajax requests
Browser reads response, parses html, css and js
Javascript is executed

[hr]

As you can see from your DB log you are trying to use the string you set as value to $todayMn ‘’. It does not try to use a valid date.

[hr]

In order to properly figure this out I’d need running code, with a print of the valid data where you find it. It might be a problem with using globals (not recommended), as you can not be sure where the values of those globals are set.

Jim,

the code is attached here (“today.php” in the zip file). There are no input data to this script. All values are computed and then a DB query executed to the display the results.

Take a look at http://famtree.subramaniam.com, on the right hand side for where the results should be displayed.

Thank you.

Pradeep.


today.zip (10.1 KB)

[php]month(birthdatetr) = $todayMN[/php]

Comes from,

[php]$todayMN = ‘’;[/php]

Which explains the strange SQL statement.

Sponsor our Newsletter | Privacy Policy | Terms of Service