I'm trying to attribute a value to a var depending of its text value. I can't just attribute the numerical value directly (via my form) because i'm also saving in my database the text value.
$section = $_POST['section']; // required
$page = $_POST['page']; // required
if ($_POST['page'] == 'Template') { $Code == '00'; }
elseif ($_POST['page'] == 'Menu') { $Code == '01'; }
elseif ($_POST['page'] == 'Home Page') { $Code == '02'; }
elseif ($_POST['page'] == 'About Us') { $Code == '03'; }
elseif ($_POST['page'] == 'Contact Us') { $Code == '04'; }
$Code_Page = $Code.''.$section;
Exemple, the code for the section 18 of the Home Page is 0218.
I don't understand why it doesn't work ? Only the second part is saved ($section), not the first 2 numbers.
Thanks in advance
EDIT: Author has clarified what he is after now. I've kept the original answer in as I feel it is a better solution.
To define a variable in PHP, you use a single equals sign (=). You've used two equals signs (==) when defining $Code , which is a comparison operator .
Original answer:
I'm assuming that you wish to optimize this code. If so, I feel the best way to do so is to either create an array, or pull from the database you mentioned from. Once you have the dataset in an array, you can do some simple checking:
Static array method:
$pages = array('Template' => '00', 'Menu' => '01', 'Home Page' => '02', 'About Us' => '03', 'Contact' => '04');
if (in_array($_POST['Page'], $pages))
{
//We have a match, deal with output here
$Code_Page = $pages[$_POST['Page']].$section
}
else
{
//Output an error message here, the page isn't in the array
}
add $Code
declaration first
$section = $_POST['section']; // required
$page = $_POST['page']; // required
$Code = ''; // This was missing
if ($_POST['page'] == 'Template') { $Code == '00'; }
elseif ($_POST['page'] == 'Menu') { $Code == '01'; }
elseif ($_POST['page'] == 'Home Page') { $Code == '02'; }
elseif ($_POST['page'] == 'About Us') { $Code == '03'; }
elseif ($_POST['page'] == 'Contact Us') { $Code == '04'; }
$Code_Page = $Code.''.$section;
It seems like the code you have provided gives you the code you are looking for the homepage of 0218. The only error I see is you are not assigning the $Code
. Your $Code == '02'
should be $Code = '02'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.