Storing an increment in a variable

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
cturner
Forum Contributor
Posts: 153
Joined: Sun Jul 16, 2006 3:03 am
Location: My computer

Storing an increment in a variable

Post by cturner »

I am wondering if someone could please tell me how I could store an increment in a variable for each page that is in the database? I need to be able to display that variable later on in my code. Thanks in advance.

This is as far as I have got:

Code: Select all

// php code is here
require "config.php";
$query = mysql_query("SELECT COUNT(page_title) FROM pages") or die ("Could not query because: ".mysql_error());
//$num_rows = mysql_num_rows($query);
// count how many pages (page_title) there are
while($row = mysql_fetch_array($query)){
	$count = $row['COUNT(page_title)'];
}

Code: Select all

// javascript code is here
var num = <?php echo $count; ?>;
for (var i=0707185109; i<num; i++) {
	document.write(i);
}
The above code doesn't work for me. It is not printing the increment.
AlExThEkAt
Forum Newbie
Posts: 1
Joined: Wed Aug 08, 2007 7:55 pm

Post by AlExThEkAt »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have always found it quite tricky to parse variables generated by php to javascript, seeing as javascript works on the client side and php works on the server side. However you can achieve what you want by writing the javascript in a function as follows.

Code: Select all

<?
$count=707185112; # example value
$html ='
	<script type="text/javascript">
	function inc(count){
	var num = count
	for (i=707185109; i<num; i++) {
			document.write(i);
	}
	} 
	var count = "'.$count.'"
	inc(count); // call the function
	</script>';

echo $html;
?>

Please not the use of both single and double quotes in the solution above. The double quotes are recognised by the javascript engine, and the single quotes by the php engine. This is very important. I hope that helps


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Storing an increment in a variable

Post by superdezign »

cturner wrote:The above code doesn't work for me. It is not printing the increment.
It should. Have you tried simply echoing $count to see what it is? Also, since your query should only return one result, you don't need to use a while loop.
Post Reply