Access form elements' properties in PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

first_blood
Forum Newbie
Posts: 5
Joined: Fri Aug 29, 2008 11:37 am

Access form elements' properties in PHP

Post by first_blood »

I am new to PHP so I need a lot of help with this.

I have a form with 2 text boxes (loginid/password) On submitting the form (action = same PHP page) I check (if(isset($_POST("submit"))) and validate the fields from the records in a database. If its wrong, i need to display a error message, if not I direct the user to another page. This is my scenario.

I have a problem displaying the error message. I have 2 <div> tags right next to the 2 text boxes showing the error message but its invisible on form load (style.display = 'none') Upon validation i need to make this div tags visible using (style.display = 'block'). How do i do that in PHP?

Here is part of my code..
<?
if(isset($_POST["submit"]))
{
require_once("config.php");
$userid = $_POST['userid'];
$password = $_POST['password'];


$query = "select * from login where userid = '$userid'";

$result = pg_query($connection, $query) or die("Error in query: $query." . pg_last_error($connection));
$rows = pg_num_rows($result);
if($rows != 1)
{
echo "<div name=\"div1\" id=\"div1\" style=\"display:block\">Invalid Username!!!</div>";
}
else
{

$row = pg_fetch_row($result);

if($password == $row[1])
{
$type = $row[2];
$company = $row[4];
echo "correct username and password";
}
else
{
echo "Invalid";
}
pg_free_result($result);
}
}
?>
Instead of echoing the error message to the browser, i need to make the div tag style.display = 'block'/'none' according to conditions.... Is there a way to access the div tag's properties in PHP????

In javascript I would write something like this document.getElementById('div1').style.display = 'none'; Is there a corresponding code in PHP for this?
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Access form elements' properties in PHP

Post by marcth »

Wouldn't this do it?

Code: Select all

 
print '<div name="div1" id="div1" style="display:none"></div>';
 
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Access form elements' properties in PHP

Post by RobertGonzalez »

No, you cannot access HTML elements attributes in PHP (well, not without a lot of work). But you can do something like this:

Code: Select all

<?php 
// Default form login value
$login = null;
// default error messages
$loginerror = null;
$passworderror = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // Try to not check against a submit button, it isn't always sent
  // handle validation, set error messages
  // ... oops, pretend there was an error in the login
  $loginerror = 'You had an error in your loging';
}
?>
<form>
  <input type="text" name="login" value="<?php echo $login; ?>" /> 
  <?php if ($loginerror): ?><div class="error"><?php echo $loginerror; ?></div><?php endif; ?>
</form>
No, this is not complete code. It is only out here as a guide to something you could do logically, so that you are not bound by what you are trying to do now.
first_blood
Forum Newbie
Posts: 5
Joined: Fri Aug 29, 2008 11:37 am

Re: Access form elements' properties in PHP

Post by first_blood »

marcth wrote:Wouldn't this do it?

Code: Select all

 
print '<div name="div1" id="div1" style="display:none"></div>';
 
yes that works (echo works too).. but I cannot use that every time i want to display/hide a div...also that places the div tag on the first line of the form. I need it immediately after the login text box.
Everah wrote:No, you cannot access HTML elements attributes in PHP (well, not without a lot of work). But you can do something like this:

Code: Select all

<?php 
// Default form login value
$login = null;
// default error messages
$loginerror = null;
$passworderror = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
&nbsp; // Try to not check against a submit button, it isn't always sent
&nbsp; // handle validation, set error messages
&nbsp; // ... oops, pretend there was an error in the login
&nbsp; $loginerror = 'You had an error in your loging';
}
?>
<form>
&nbsp; <input type="text" name="login" value="<?php echo $login; ?>" /> 
&nbsp; <?php if ($loginerror): ?><div class="error"><?php echo $loginerror; ?></div><?php endif; ?>
</form>
No, this is not complete code. It is only out here as a guide to something you could do logically, so that you are not bound by what you are trying to do now.
That sorta works!!! I'll work on it more.. Thank You.
Also, can u elaborate more on the "Try to not check against a submit button, it isn't always sent" part? I am not sure I understood it...
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Access form elements' properties in PHP

Post by RobertGonzalez »

Create a simple form with a text box and submit button. Then inside the text box hit the enter key on your keyboard and dump the POST array. Try this in all of your browser (not just one) and see if the results are different.

Then do the same thing with an image submit button.
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Access form elements' properties in PHP

Post by marcth »

If I recall correctly, some of the early Internet Explorer 5 browsers had trouble with this. Aside from that, I'm under the believe that all browsers on Windows, Linux and Macintosh submit the first submit input button when you press enter.

As for <input type="image" />, you are correct, it does not work, which is why I've never used it. Why not use <button><img src="" /></button> instead; it works wonderfully and is quite flexible.

The reason why I test for the existence of a submit button as opposed to testing to see if the request method is POST is because it allows me to handle multi-page form wizards.

Quite clearly, you know your stuff. Please tell me of a non-obsolete, W3C-compliant browser that fails to send the first submit button as a variable, and I promise to change my ways forever.

Your post says I'm wrong and in order to disprove this, I need to test every single browser under every operating system known to human kind--that's not very cool. My response is that is does work (except under obsolete IE 5) and if you want to disprove this, name one of the aforementioned browsers that fails.

I've attached a test script, which you can use.
Attachments
submit_test.php.zip
(681 Bytes) Downloaded 24 times
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Access form elements' properties in PHP

Post by RobertGonzalez »

I have tests at work. I will be mess with them tomorrow. I ran into this problem about 18 months ago specifically with IE6 on Windows and IE5.5 on Mac. When inside a text field when a user hit the enter key the form would post without the submit button. That is why I offer this advice.

As for multi form submits, there is not reason why you cannot check for request method type then handle the form based on a known element of the form other than the button. Is there?
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Access form elements' properties in PHP

Post by marcth »

Please let me know (especially with Mac on IE--never tested that). I do know it functions fine with IE6 on Windows though.
User avatar
starram
Forum Commoner
Posts: 58
Joined: Thu Apr 10, 2008 1:27 am
Location: India
Contact:

Re: Access form elements' properties in PHP

Post by starram »

Why you want to use such complicated script?
Have a look at this simple script.

Code: Select all

<?php
    if($_GET['login']=="yes")//Admin Validation Start
    {
        session_start();
        $user_name=addslashes(trim($_POST['username']));
        $password=addslashes(trim($_POST['password']));
        include("include/connection.php");//Database Connection
        $sql = "select * from table where username='".$user_name."' and binary password='".$password."'";
        $result=mysql_query($sql,$a);
        $count=mysql_num_rows($result);
        if($count>0)//Validated
        {
            $check=mysql_fetch_assoc($result);
            $_SESSION['admin_id_sess']=$check['id'];
            $_SESSION['admin_username_sess']=$user_name;
            header('location:'.YOURSITE_ADMIN_URL.'admin_home.php');
        }
        else//Not Validated
        {
            header('location:index.php?invalid=invalid');
        }
    }//Admin Validation End
    include("include/message.php");//language file
    $pagename=PAGETITLE_ADMINLOGIN;//page Title
    include("include/header.php");//Include page header
    include("include/left.php");//Include left menu
    
?>
 
 
<table border="0" width="100%" cellspacing="0" cellpadding="0">
    <tr>
        <td height="10" class="lorem" align="right"><?=MANDATORY_MESSAGE?></td>
    </tr>
    <tr>
        <td><form id="login" name="login" method="post" action="index.php?login=yes" onsubmit="return validate_admin()">
            <table border="0" align="left" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td align="left">
                        <table width="40%" border="0" cellspacing="0" cellpadding="0" align="center">
                            
                            <tr>
                                <td colspan="3" height="10" class="showerror" align="center"><? if($_GET['invalid']=="invalid") echo INVALID_USERNAME; else if($_GET['logout']=="yes") echo "<font color='green'>".SUCCESSFULL_LOGOUT."</font>"; else if(isset($_GET['noaccess'])) echo UNAUTHORIZED_ACCESS;?> </td>
                            </tr>
                            <tr>
                                <td width="200"></td>
                                <td></td>
                                <td  height="35" align="left" valign="middle" class="redHeadTitle">Login</td>
                            </tr>
                            <tr>
                                <td valign="middle" class="lorem"><span class="showerror"><?=ASTERIK_STAR?></span> Username</td>
                                <td class="lorem">:</td>
                                <td height="35" colspan="2" valign="middle"><input name="username" type="text" class="lorem" maxlength="<?=MAXLENGTH_FIFTY?>" /></td>
                            </tr>
                            <tr>
                                <td class="lorem"><span class="showerror"><?=ASTERIK_STAR?></span> Password</td>
                                <td class="lorem">:</td>
                                <td height="35" colspan="2"><input name="password" type="password" class="lorem" maxlength="<?=MAXLENGTH_FIFTY?>" /></td>
                            </tr>
                            <tr>
                                <td height="21" align="right">&nbsp;</td>
                                <td class="lorem"></td>
                                <td height="21"  align="left"><input type="submit" value="Submit" src="images/login.jpg" align="top" title="Submit" height="20" border="0" onClick="return validate_admin(); "/></td>                      
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
            </form>
        </td>
    </tr>
</table>
<?php
    require_once("include/footer.php");
?>    
 
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Access form elements' properties in PHP

Post by RobertGonzalez »

Load this script in IE (I used IE 7 just now, though I ran this originally in IE6). See what outputs in IE as compared to FF, Opera and Safari when you hit the enter button while in the text input box.

Code: Select all

<?php
$this_page = basename($_SERVER['SCRIPT_FILENAME']);
if (isset($_POST['sent']))
{
    if (isset($_POST['button1']))
    {
        echo 'This is the first button on the list of buttons to be pressed';
    }
    elseif (isset($_POST['submit1']))
    {
        echo 'This is the second button (the submit) on the list of buttons to be pressed';
    }
    elseif (isset($_POST['button2']))
    {
        echo 'This is the last button on the list of buttons to be pressed';
    }
    
        if (isset($_POST['check1']))
        {
                echo 'The checkbox is set!';
        }
 
    echo '<pre>';
    var_dump($_POST);
    echo '</pre>';
}
 
if (!empty($_REQUEST))
{
        echo '<pre>';
    var_dump($_REQUEST);
    echo '</pre>';
}
 
setcookie('text-field', 'Cookie Text', 0);
?>
<html>
<head><title>Form sending tests</title></head>
<body>
<form name="test-form" id="test-form" method="post" action="<?php echo $this_page; ?>?text-field=BlahBlah">
<input type="text" name="text-field" value="some text" /> 
<select name="select-item">
        <option value="1">First</option>
        <option value="2">Second</option>
        <option value="3">Third</option>
        <option value="4">Fourth</option>
        <option value="5">Fifth</option>
        <option value="6" selected="selected">Last</option>
</select>
<select name="select-multi[]" multiple="multiple" size="4">
        <option value="1">First</option>
        <option value="2">Second</option>
        <option value="3">Third</option>
        <option value="4">Fourth</option>
        <option value="5">Fifth</option>
        <option value="6" selected="selected">Last</option>
</select>
<input type="checkbox" name="check1" />
<p>
C1 <input type="radio" name="radio1" value="C1" />
C2 <input type="radio" name="radio1" value="C2" checked="checked" />
C3 <input type="radio" name="radio1" value="C3" />
C4 <input type="radio" name="radio1" value="C4" />
</p>
<p>
C1 <input type="checkbox" name="cb[]" value="CB1" />
C2 <input type="checkbox" name="cb[]" value="CB2" checked="checked" />
C3 <input type="checkbox" name="cb[]" value="CB3" />
C4 <input type="checkbox" name="cb[]" value="CB4" />
</p>
<input type="hidden" name="member_id" value="1" />
<input type="hidden" name="sent" value="true" />
<input type="submit" name="button1" value="Click Me" />
<input type="submit" name="submit1" value="Submit this form" />
<input type="submit" name="button2" value="Click Me too" />
</form>
</body>
</html>
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Access form elements' properties in PHP

Post by marcth »

Everah wrote:Load this script in IE (I used IE 7 just now, though I ran this originally in IE6). See what outputs in IE as compared to FF, Opera and Safari when you hit the enter button while in the text input box.

Code: Select all

<?php
$this_page = basename($_SERVER['SCRIPT_FILENAME']);
if (isset($_POST['sent']))
{
    if (isset($_POST['button1']))
    {
        echo 'This is the first button on the list of buttons to be pressed';
    }
    elseif (isset($_POST['submit1']))
    {
        echo 'This is the second button (the submit) on the list of buttons to be pressed';
    }
    elseif (isset($_POST['button2']))
    {
        echo 'This is the last button on the list of buttons to be pressed';
    }
    
        if (isset($_POST['check1']))
        {
                echo 'The checkbox is set!';
        }
 
    echo '<pre>';
    var_dump($_POST);
    echo '</pre>';
}
 
if (!empty($_REQUEST))
{
        echo '<pre>';
    var_dump($_REQUEST);
    echo '</pre>';
}
 
setcookie('text-field', 'Cookie Text', 0);
?>
<html>
<head><title>Form sending tests</title></head>
<body>
<form name="test-form" id="test-form" method="post" action="<?php echo $this_page; ?>?text-field=BlahBlah">
<input type="text" name="text-field" value="some text" /> 
<select name="select-item">
        <option value="1">First</option>
        <option value="2">Second</option>
        <option value="3">Third</option>
        <option value="4">Fourth</option>
        <option value="5">Fifth</option>
        <option value="6" selected="selected">Last</option>
</select>
<select name="select-multi[]" multiple="multiple" size="4">
        <option value="1">First</option>
        <option value="2">Second</option>
        <option value="3">Third</option>
        <option value="4">Fourth</option>
        <option value="5">Fifth</option>
        <option value="6" selected="selected">Last</option>
</select>
<input type="checkbox" name="check1" />
<p>
C1 <input type="radio" name="radio1" value="C1" />
C2 <input type="radio" name="radio1" value="C2" checked="checked" />
C3 <input type="radio" name="radio1" value="C3" />
C4 <input type="radio" name="radio1" value="C4" />
</p>
<p>
C1 <input type="checkbox" name="cb[]" value="CB1" />
C2 <input type="checkbox" name="cb[]" value="CB2" checked="checked" />
C3 <input type="checkbox" name="cb[]" value="CB3" />
C4 <input type="checkbox" name="cb[]" value="CB4" />
</p>
<input type="hidden" name="member_id" value="1" />
<input type="hidden" name="sent" value="true" />
<input type="submit" name="button1" value="Click Me" />
<input type="submit" name="submit1" value="Submit this form" />
<input type="submit" name="button2" value="Click Me too" />
</form>
</body>
</html>
You are right: it doensn't work in IE. I guess I'm going to have to start using a hidden variable called formAction--I really don't want to distinguish between get and post variables.
first_blood
Forum Newbie
Posts: 5
Joined: Fri Aug 29, 2008 11:37 am

Re: Access form elements' properties in PHP

Post by first_blood »

starram wrote:Why you want to use such complicated script?
Have a look at this simple script.

Code: Select all

<?php
    if($_GET['login']=="yes")//Admin Validation Start
    {
        session_start();
        $user_name=addslashes(trim($_POST['username']));
        $password=addslashes(trim($_POST['password']));
        include("include/connection.php");//Database Connection
        $sql = "select * from table where username='".$user_name."' and binary password='".$password."'";
        $result=mysql_query($sql,$a);
        $count=mysql_num_rows($result);
        if($count>0)//Validated
        {
            $check=mysql_fetch_assoc($result);
            $_SESSION['admin_id_sess']=$check['id'];
            $_SESSION['admin_username_sess']=$user_name;
            header('location:'.YOURSITE_ADMIN_URL.'admin_home.php');
        }
        else//Not Validated
        {
            header('location:index.php?invalid=invalid');
        }
    }//Admin Validation End
    include("include/message.php");//language file
    $pagename=PAGETITLE_ADMINLOGIN;//page Title
    include("include/header.php");//Include page header
    include("include/left.php");//Include left menu
    
?>
 
 
<table border="0" width="100%" cellspacing="0" cellpadding="0">
    <tr>
        <td height="10" class="lorem" align="right"><?=MANDATORY_MESSAGE?></td>
    </tr>
    <tr>
        <td><form id="login" name="login" method="post" action="index.php?login=yes" onsubmit="return validate_admin()">
            <table border="0" align="left" cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td align="left">
                        <table width="40%" border="0" cellspacing="0" cellpadding="0" align="center">
                            
                            <tr>
                                <td colspan="3" height="10" class="showerror" align="center"><? if($_GET['invalid']=="invalid") echo INVALID_USERNAME; else if($_GET['logout']=="yes") echo "<font color='green'>".SUCCESSFULL_LOGOUT."</font>"; else if(isset($_GET['noaccess'])) echo UNAUTHORIZED_ACCESS;?> </td>
                            </tr>
                            <tr>
                                <td width="200"></td>
                                <td></td>
                                <td  height="35" align="left" valign="middle" class="redHeadTitle">Login</td>
                            </tr>
                            <tr>
                                <td valign="middle" class="lorem"><span class="showerror"><?=ASTERIK_STAR?></span> Username</td>
                                <td class="lorem">:</td>
                                <td height="35" colspan="2" valign="middle"><input name="username" type="text" class="lorem" maxlength="<?=MAXLENGTH_FIFTY?>" /></td>
                            </tr>
                            <tr>
                                <td class="lorem"><span class="showerror"><?=ASTERIK_STAR?></span> Password</td>
                                <td class="lorem">:</td>
                                <td height="35" colspan="2"><input name="password" type="password" class="lorem" maxlength="<?=MAXLENGTH_FIFTY?>" /></td>
                            </tr>
                            <tr>
                                <td height="21" align="right">&nbsp;</td>
                                <td class="lorem"></td>
                                <td height="21"  align="left"><input type="submit" value="Submit" src="images/login.jpg" align="top" title="Submit" height="20" border="0" onClick="return validate_admin(); "/></td>                      
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
            </form>
        </td>
    </tr>
</table>
<?php
    require_once("include/footer.php");
?>    
 
That... pretty much solved my problem... i was a little uncomfortable with writing PHP code in between HTML Tags... but i guess I'll have to learn to work with that..

Thanks guys...

One last question. Just like PHP inside HTML, Is it possible to write Javascript (<script> tag) in between PHP? something like this

Code: Select all

<?php
 
if(condition)
{
?>
<script language.....>
</script>
<?
}
else
{
?>
<script language.....>
</script>
<?
}?>
User avatar
starram
Forum Commoner
Posts: 58
Joined: Thu Apr 10, 2008 1:27 am
Location: India
Contact:

Re: Access form elements' properties in PHP

Post by starram »

Yes, Buddy you can do that.
first_blood
Forum Newbie
Posts: 5
Joined: Fri Aug 29, 2008 11:37 am

Re: Access form elements' properties in PHP

Post by first_blood »

lol..... a simple....php (js) php (js) did the trick;

Code: Select all

else
        {
            
            echo '<script language = "JavaScript" type="text/javascript">';
            echo 'document.getElementById(\'div1\').style.display = \'none\';';
            echo 'document.getElementById(\'div2\').style.display = \'block\';';
            echo '</script>';   
        
        }
 
damn... i am so nooob..
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Access form elements' properties in PHP

Post by RobertGonzalez »

marcth wrote:I guess I'm going to have to start using a hidden variable called formAction--I really don't want to distinguish between get and post variables.
You should always distinguish between your superglobals. It makes for clean, maintainable, readable code later on. If you know it is coming from POST use POST, if it is coming from GET use that.

I would not use REQUEST (yes, that is a bit of a holy war around here... search and you will find all sorts of opinions about it) because PHP sets a precedent order on REQUEST, one that is tested in the code I posted above.
Post Reply