Page 1 of 1

Saving Variables in PHP

Posted: Sun Jul 10, 2011 7:08 am
by ANN-Tech Team.
Hi again guys. you have helped me out a lot last time.
Thank for that.

can you advise how to save variables in PHP file?

lets say i have a function that i pass a value to,

Code: Select all

<?php
  
  $num = 1;

  $qbClientString = isset($_GET['ClientString']) ? $_GET['ClientString'] : '';
    
 
  $num++;
  writeName($num);

      
   function writeName($String) {
      print($String);
    }
?>
When i run this in browser, it returns 2, as it should.
But how do i go about saving this 2, so next time i run it it will return 3, 4, 5...
so it saves the variable.

I just want to be able to save a simple variable in my PHP file.
Then retrieve it.

Re: Saving Variables in PHP

Posted: Sun Jul 10, 2011 8:46 am
by AbraCadaver
Use sessions and save it as a session variable.

Re: Saving Variables in PHP

Posted: Sun Jul 10, 2011 9:02 am
by ANN-Tech Team.
Ok, what if i need to save it permanently, not for a session?

I am making Hi-Scores list. Just want to save Names + Score
every time player submits it.

Re: Saving Variables in PHP

Posted: Sun Jul 10, 2011 9:28 am
by AbraCadaver
To keep it easy you'll need a database. MySQL or SQLite is a simple file based one.

Re: Saving Variables in PHP

Posted: Sun Jul 10, 2011 12:00 pm
by gbit
No need to use database this problem can be solved using filesystem.

Create a file name val.txt in the directory where you have this php file and check if it has proper read/write permissions.
Use this file to store the $num data and obtain it later.

Code: Select all

<?php

$fp = fopen("val.txt","r+");
if(!fp){ 
            echo "<b>sorry there was a problem</b>";
          }
$num = fread($fp,1024);

  $qbClientString = isset($_GET['ClientString']) ? $_GET['ClientString'] : '';
   
 
  $num++;
  writeName($num);

     
   function writeName($String) {
      print($String);
    }

fwrite($fp,$num);
fclose($fp);

?>

Re: Saving Variables in PHP

Posted: Sun Jul 10, 2011 4:48 pm
by AbraCadaver
Yeah, so latter, let's query the file for username and display their points. It can be done of course, but this is not a simple store a value issue, it's a job for a database.

And why everyone with fopen, fwrite, flose? file_put_contents() is not a new function.

Re: Saving Variables in PHP

Posted: Tue Jul 12, 2011 1:13 pm
by Squegg
As long as you have the correct permission to write to files that might be the best option for something as small as you are trying to achieve. For more complex scripts, use a database.