Page 1 of 1

Storing an increment in a variable

Posted: Wed Aug 08, 2007 6:19 pm
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.

Posted: Wed Aug 08, 2007 8:09 pm
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]

Re: Storing an increment in a variable

Posted: Wed Aug 08, 2007 8:25 pm
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.