phoxd
phoxd

Reputation: 1622

Get variable and save it inside the same php file?

I tried doing this

<h1>My Css Colors</h1>
<form action="" method="get">
    <input type="text" name="csscolor"/>
    <input type="submit" value="Save">
</form>

<div ID="csscolors">
</ul>
<?php
    $csscolor = $_GET['csscolor'];
    echo '<li>'. $csscolor .'</li>'; // I used `echo` b/c I don't know anything else
?>
</ul>
</div>

How do I save that <li>some csscolor</li> on that same php file and so that I could add as many li as I want?

Upvotes: 0

Views: 129

Answers (3)

hidemaru
hidemaru

Reputation: 51

You might want to use cookies or session to store all the CSS colors.

Below is sample code using $SESSION.

<?php 
   // this starts the session 
   session_start(); 

   // get all CSS colors in SESSION
   $allCssColors=$_SESSION['color'];
   if (!isset($allCssColors)) {
      $allCssColors=array();
   }
   $allCssColors[count($allCssColors)]=$_GET['csscolor']; // add the new one

   // now display all the CSS colors
   for ($i = 0; $i < count($allCssColors); ++$i) {
      print '<li>'.$allCssColors[$i].'</li>'
   } 
   $_SESSION['color'] = $allCssColors; // save all CSS colors in SESSION

?> 

Upvotes: 1

Rajan Rawal
Rajan Rawal

Reputation: 6317

See if you are having more than one css classes that you need to maintain between some pages and being used again and again then as @SomeKittens, mentioned you can store these values to the database but if your application does not have so many database tradeoffs than you can store it to the CONSTANT variable like

define('CSSCOLOR', '#EFEFEF'); \\ Or any color code you want to put in second parameter.

Then put this code in one global file and where you want to use this code at that include that file in where you want to use this constant you can use it like

echo '<li>'. CSSCOLOR .'</li>'; 

Another way you can store it to session or cookies as mentioned by hidemaru fist at time of login or some global include file say in global.php

session_start(); 
$_SESSION['color'] = "#DEFDEF"; // any of your color code here

and in file where you want to use say index.php

session_start(); 
echo '<li>'. $_SESSION['color'] .'</li>';

Hope you have got it.

Upvotes: 1

SomeKittens
SomeKittens

Reputation: 39512

If you're looking to save a value, your best bet is to put in in a database, rather than try and hardcode it into the PHP file (especially if you want to add more <li>. Use the PDO or MySQLi classes to communicate with your database. I'd recommend getting XAMPP/WAMP to experiment on your home machine.

Upvotes: 1

Related Questions