Show option value

Hi!

So I got a small problem with probably an easy fix but I haven’t been able to work it out and I’m starting to lose my calm. What I want to do is basically to get a form to show the right option value in a form. I got a value of Yes that I turn into a “1” in the DB and the value No = “0”. Now in a different page, edit.php, I want the form to show all my options in the form and give a chanse to switch yes to no. But I can’t figure out when I gather my DB value how to make the 0 = ‘No’ and show the option value as no. Here’s my code to make sense of my jibber jabber.

<?php
if (isset($con, $_POST['pagetitle'])){
	
	$mid = mysqli_real_escape_string($con, $_POST['thisID']);
	$showmenu= mysqli_real_escape_string($con, $_POST['showmenu']);
	
	// Showmenu 1 = yes, 0 = No
	if(isset($_POST['showmenu']) && 
	   $_POST['showmenu'] == 'Yes') {
		$showmenu = "1";
	} else {
		$showmenu = "0";
	}    
	
	$sql = mysqli_query($con, "UPDATE pages SET showmenu='$showmenu'' WHERE id='$mid'");
	
	header("location: page_list.php");
	exit();
}
?>
<?php

if(isset($_GET['mid'])){
	$targetID = $_GET['mid'];
	$sql = mysqli_query ($con, "SELECT * FROM pages WHERE id='$targetID' LIMIT 1");
	$pageCount = mysqli_num_rows($sql); // Count number of rows to outpout.
	if($pageCount > 0){
		while($row = mysqli_fetch_array($sql)){
			$showmenu = $row["showmenu"];
			// Showmenu 1 = yes, 0 = No
			if($showmenu == 1) {
				$row['showmenu'] = 'Yes';
			} else {
				$row['showmenu'] = 'No';
			} 
			
	}
} else {
	echo "Denna sida finns inte.";
	exit();
	}
}
?>
<body>
    <form action="page_edit.php" enctype="multipart/form-data" name="add_page_form" id="add_page_form" method="post">
                
        <!-- Show Menu -->
         <div class="add_page_info">
            <p>show in menu?</p>
            <label>
                <select name="showmenu" id="add_showmenu">
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                </select>
            </label>

</body>

Notice I have striped the document a whole lot to save you from reading unnecessary code.
Thank you in advance!

Why not just save Yes and No into the database as it will make everything simpler?

Two points, to start with:

  • <option> elements don’t require a value attribute. If you omit the value attribute, the contents of the element will be it’s value. So if you do: <option value="Yes">Yes</option>, you can reduce that to just: <option>Yes</option>.

  • As such, you must also realize that the option value can be a value other than the contents. So if your “Yes” option represents the number 1, and “No” represents 0, you could write that up directly in the HTML as:

     <option value="1">Yes</option>
     <option value="0">No</option>
    

    The PHP code receiving these values would then get the values directly, and you wouldn’t have to convert them. That, at least, should remove the need for those condition blocks in your code.

To have a form set the correct option when generated, you just need to add the selected attribute to the correct option. In it’s simplest form:

<select name="showmenu">
    <option value="1"<?= $row["showmenu"] == 1 ? " selected" : "" ?>>Yes</option>
    <option value="0"<?= $row["showmenu"] == 0 ? " selected" : "" ?>>No</option>
</select>

Although, if yo have more options you’d probably do better to make it more dynamic than that. Something like this, perhaps:

<?php
$optionItems = array(
    1 => "Yes",
    0 => "No"
);

$optionsHtml = "";
foreach ($optionItems as $value => $name) {
    $selected = $row["showmenu"] == $value ? " selected" : "";
    $optionsHtml .= "<option value=\"{$value}\"{$selected}>{$name}</option>";
}
?>

<select name="showmenu">
    <?= $optionsHtml; ?>
</select>
1 Like

For one, it’s a boolean value, and can be saved as such requiring only 1 byte of storage space. If you save it as a string, you will require at the very least 3 bytes (for “No”) or 4 bytes (for “Yes”).

That’s not to mention that you have little control over what the value actually is. Another part of the code could, by mistake (or even on purpose), save “Bob” as a value, and your code would then fail to work. Unless you wrote in safeguards against that, in which case the added complexity would pretty much negate the purpose of doing it this way.

Also, It doesn’t really make any of this any simpler, just very slightly different.

This is not a good practice

Hi,

First of all thank you for your help!
I added your code to mine and it seem to display correctly the only thing is it doesn’t work with my form.
I can’t edit the value from Yes to No.

How do you think I can solve this?

Thanks again!

I’ve never hear any solid logic backing that opinion up. Every HTML spec down to HTML 3 has clearly defined the value attribute as being optional, and the browsers have all been pretty good at following that.

A lot of people - notably those who preferred the stricter rules of XHTML to HTML - like to be overly explicit when writing markup, but that’s merely a matter of personal style preference. In truth there is no real upside to including the value attribute in situations like these.

Can you show us the current state of your code?

My argument is that into a big HTML page, into a large project, some may be mislead of this feature. It’s the same reason I don’t use short tags and always add brackets to my conditions, to make everything as visible as possible.

I see. To be perfectly honest, I can’t help thinking that’s a pretty thin argument. It is fairly obvious what will happen if the value attribute is left out, even if you’ve never actually learned the difference. I seriously doubt any web developer wouldn’t get that automatically when seeing it.

I kinda use a similar thing in my site but I use a option to send value to the data base but I save it as yes and no then retrieve them from the base I don’t know if it’s good or bad but it works.

<?php

$uName = $_REQUEST["uname"];
$pWord = $_REQUEST["pword"];

$getUser = "SELECT * FROM users WHERE uName = '".$uName."' AND pass = '".$pWord."'";
$trigerQuery = mysql_query($getUser);


$num = mysql_num_rows($trigerQuery);
$row = mysql_fetch_array($trigerQuery);

if($num > 0){
    //creating session
    $_SESSION["iD"] = $row["uId"];
    $_SESSION["uType"] = $row["admin"];

    if($row["admin"] == "Yes"){

        header("location:admin.php");
        exit();
    }else{
        header("location:user.php");
        exit();
    }
}else{//if the user details don't match up
    header("location:index.php?login=Login Failed! Please Try Again.");
    exit();
}

?>

What I say in post #4 applies to your situation as well.

In your case, if you were to use 0 and 1 as boolean values, as @gastooon does, all you’d have to change in the code you posted would be to replace this: if($row["admin"] == "Yes") with this: if($row["admin"]).

PHP’s internal type-conversion reads 1 as TRUE in conditions, so by saving 1 for “Yes” in the database, PHP would automatically evaluate that condition as true.

P.S.
Your code is wide open to SQL Injection, one of the most common web-based security vulnerabilities out there. Anybody with even the most basic knowledge of these things could log into your site as any user, without even having to guess the password.

P.P.S.
You also seem to be storing your passwords in plain-text form. That’s generally a very insecure thing to do, especially when your system is insecure in other ways. You should look up password hashing. Passwords should always be hashed when stored.

Thank you for the reply m8 yes I know about the security issue I will be doing the whole thing again after I get it working I’m thinking of using mysqli I kinda can’t get my head around the PDO thing. And I’m not storing the password in plain text I just removed it before posting it here. I tried the 1 - 0 thing with a boolean for some reason it didn’t work but this did so I stuck with it.

    <?php
if (isset($con, $_POST['pagetitle'])){
	
	$mid = mysqli_real_escape_string($con, $_POST['thisID']);
	$showmenu= mysqli_real_escape_string($con, $_POST['showmenu']);
	
	// Showmenu 1 = yes, 0 = No
	if(isset($_POST['showmenu']) && 
	   $_POST['showmenu'] == 'Yes') {
		$showmenu = "1";
	} else {
		$showmenu = "0";
	}    
	
	$sql = mysqli_query($con, "UPDATE pages SET showmenu='$showmenu'' WHERE id='$mid'");
	
	header("location: page_list.php");
	exit();
}
?>
<?php

if(isset($_GET['mid'])){
	$targetID = $_GET['mid'];
	$sql = mysqli_query ($con, "SELECT * FROM pages WHERE id='$targetID' LIMIT 1");
	$pageCount = mysqli_num_rows($sql); // Count number of rows to outpout.
	if($pageCount > 0){
		while($row = mysqli_fetch_array($sql)){
			$showmenu = $row["showmenu"];
			// Showmenu 1 = yes, 0 = No
			$optionItems = array(
				1 => "Yes",
				0 => "No"
			);
			
			$optionsHtml = "";
			foreach ($optionItems as $value => $name) {
				$selected = $row["showmenu"] == $value ? " selected" : "";
				$optionsHtml .= "<option value=\"{$value}\"{$selected}>{$name}</option>";
			}
			
	}
} else {
	echo "Denna sida finns inte.";
	exit();
	}
}
?>
<body>
    <form action="page_edit.php" enctype="multipart/form-data" name="add_page_form" id="add_page_form" method="post">
                
        <!-- Show Menu -->
         <div class="add_page_info">
            <p>show in menu?</p>
            <label>
                <select name="showmenu" id="add_showmenu">
                    <?= $optionsHtml; ?>
                </select>
            </label>
            
    	<label>
            <input type="hidden" name="thisID" value="<?php echo $targetID; ?>" />
            <input type="submit" name="button" id="add_page_button" value="Redigera Sida" />
        </label>
    </form>
            
            

</body>

This is what I got at the moment and it displays the value Yes and No correctly with the bool number in my db.
But I can’t change the bool value with my form from 1 to 0.

that’s because $_POST['showmenu'] is either 0 or 1, not “Yes” or “No” (which is what you test for).

note:
‘1’ == ‘Yes’ == ‘No’ == true // these are type-less comparisons

Changes the Yes to a 1 and No to a 0. Works when I create it in my create.php page

I don’t know what your created.php script looks like, or how it’s different from what you’re doing here, but if you’ve changed the options as I suggested, to:

<select name="showmenu">
    <option value="1">Yes</option>
    <option value="0">No</option>
</select>

Then the $_POST['showmenu'] will already be either “0” or “1”. You don’t need to do anything to change it. The entire IF clause you posted is unnecessary.