I am trying to register two different userinfo with dropdown but getting some error when i click on submit butto. I am newbie in php.Please help me solving this error...

My database is:

id      int(2)  Primary Key     
type    char(2)         
cname   varchar(55)             
uname   varchar(55)             
mail    varchar(55)         
pswd    varchar(55)         
address varchar(255)        
zip     int(6)          
regtime datetime

conn.php file

<?php

$host   = 'localhost';
$user   = 'root';
$pass   = '';
$dbname = 'star';

$con = mysql_connect( $host,$user,$pass ) or die('Unable to connect');
mysql_select_db( $dbname ) or die('Unable to select database');

?>

register.php

<?php 
require('include/conn.php'); //include db connection

$error = array(); //define $error to prevent error later in script
$message = '';
if ( isset( $_POST['submit'] ) ) {
    $error = array();
    array_map( 'stripslashes',$_POST ); //Strips slashes
    array_map( 'mysql_real_escape_string',$_POST ); //Escapes data to protect against sql injection
    $type = $_POST['utype'];
    $company = $_POST['cname'];
    $user = $_POST['uname'];
    $email = $_POST['mail'];
    $pass = $_POST['pswd'];
    $address = $_POST['address'];
    $zip = $_['zip'];
    //usertype
    if ( empty( $type ) ) { //check if type is selected on not
        $error[] = 'Type not selected';
    }
    //company name
    if ( empty( $company ) ) { //check if company name is blank
        $error[] = 'Company not entered';
    }
    //username
    if ( empty( $user ) ) { //check if username is blank
        $error[] = 'Username is blank';
    }
    elseif ( strlen( $user ) > 30 ) { //make sure the username is not longer than 30 chars
        $error[] = 'Username is longer than 30 characters';
    }
    else { //if there aren't any errors with $user at this point, check to make sure no one else has the same username
        $query = mysql_query( "SELECT * FROM `users` WHERE `user` = '{$uname}'",$con );
        if ( mysql_num_rows( $query ) > 0 ) {
            $error[] = 'Username already exists';
        }
    }
    //email
    if ( empty( $email ) ) { //check if email is blank
        $error[] = 'EMail not entered';
    }
    //password
    if ( empty( $pass ) ) { //check if password is blank
        $error[] = 'Password is blank';
    }
    elseif ( strlen( $pass ) < 9 ) { //make sure password is longer than 8 characters
        $error[] = 'Password must be longer than 8 characters';
    }
    elseif ( !preg_match( "/^.*(?=.{3,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/",$pass ) ) { //check to see if its a valid password
        $error[] = 'Password invalid - it must contain at least 1 number, 1 uppercase letter, 1 lowercase letter';
    }
    //address
    if ( empty( $address ) ) { //check if address is blank
        $error[] = 'Address not entered';
    }
    //zipcode
    if ( empty( $zip ) ) { //check if username is blank
        $error[] = 'Pincode not entered';
    }
    if ( count( $error ) == 0 ) { //if there are no errors, then insert into database
        $pass = encryptPassword( $pass ); //hash password before inserting into database
        $query = mysql_query( "INSERT INTO `users` (`type`,`cname`,`uname`,`mail`,`pswd`,`address`,`zip`) VALUES ('{$type}','{$company}','{$user}','{$email}','{$pass}','{$address}','{$zip}')",$con );
        $message = 'User registration successful!';
    }
}

$errmsg = '';
if ( count( $error ) > 0 ) { //if there are errors, build the error list to be displayed.
    $errmsg = '<div>Errors:<br /><ul>';
    foreach( $error as $err ) { //loop through errors and put then in the list
        $errmsg .= "<li>{$err}</li>";
    }
    $errmsg .= '</ul></div>';
}
<html>
<head>
<title>Register</title>
</head>
<body>
          <form action="{$_SERVER['PHP_SELF']}" class="form-horizontal" method="post">
            <fieldset>
              <legend>Sign Up | Basic Information </legend>
                <label >Listing Type</label>
                <div>
                  <select data-rel="chosen">
                    <option>Productin Unit</option>
                    <option>Vendor</option>
                  </select>
                </div>
              </div>
                <label>Company Name</label>
                <div >
                  <input type="text" name="cname" required="">
                  </div>
              <div>
                <label>Owner</label>
                <div>
                  <input type="text" name="uname" required="">
                  </div>
              </div>
                <label >Email</label>
                <div >
                  <input type="text" name="mail" required="">
              </div>
              <div>
                <label >Choose Password</label>
                <div >
                  <input type="password" name="pswd" required="">
                  </div>
              </div>
              <div>
                <label>Confirm Password</label>
                <div>
                  <input type="password" name="pswd" required="">
                  </div>
              </div>
              <div>
                <label>Address</label>
                <div>
                  <textarea name="address" rows="4"></textarea>
                </div>
              </div>
              <div>
                <label>Zip Code</label>
                <div>
                  <input type="text" name="zip" required="">
                  </div>
              </div>
              <div >
                <button type="submit" name="submit" >Next</button>
                <button>Cancel</button>
              </div>
            </fieldset>
          </form>
          </body>
          </html>
          ?>

Hi, this:

$zip = $_['zip'];

Must be:

$zip = $_POST['zip'];

Then, if you still get an error, post the details of the error, otherwise it becomes difficult to help.

Helo there,
I m getting, 'The requested URL /webfoldername/{$_SERVER['PHP_SELF']} was not found on this server error.' It looks like error related with form.

It happens because you have to use the php tags:

<form action="<?php echo $_SERVER['PHP_SELF']"; ?> class="form-horizontal" method="post">

Also 74 of the same file you have to use the closing PHP tag, so this:

}
<html>

Becomes:

}
?>
<html>

And you have to remove the one at the end of the file:

</html>
?>

For more information check these links:

Above error solved. but now i am getting following error.
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in register.php file. Please help me...

The error happens because of:

$query = mysql_query( "SELECT * FROM `users` WHERE `user` = '{$uname}'",$con );

You're using $uname instead of $user and for this reason mysql_query() returns boolean FALSE. When in doubt, you should use mysql_error() right after the query:

$q = mysql_query("...") or die(mysql_error());

Consider also that the mysql_* API functions are going to be deprecated and removed soon from PHP, you should use MySQLi or PDO:

But I want to point you to another problem, this:

array_map( 'stripslashes',$_POST );
array_map( 'mysql_real_escape_string',$_POST );

It must be:

$_POST = array_map( 'stripslashes',$_POST );
$_POST = array_map( 'mysql_real_escape_string',$_POST );

Because the array_map will not overwrite the original array, example:

$a = array("hello", "wor\ld");
array_map('stripslashes', $a);

print_r($a);

# output:
Array
(
    [0] => hello
    [1] => wor\ld
)

$b = array_map('stripslashes', $a);
print_r($b);

# output:
Array
(
    [0] => hello
    [1] => world
)

I dont know how to store dropdown list value in database. Can you please help me how to store value of selected dropdown in the mysql table ?
Thanks.

No problem. Assign the name attribute to the select tag, for example:

<select name="fruits">

So, when the form is submitted you can check the value of $_POST['fruits']. Now, if you submit something like this:

<select name="fruits">
    <option>---</option>
    <option>Apples</option>
    <option>Oranges</option>
    <option>Cherries</option>
</select>

the value of $_POST['fruits'] will be chosen from the content of the option tag, if you select the second option, the value will be Apples. If, instead, you add the value attribute, then this will be considered instead of the text, for example:

<select name="fruits">
    <option value="">---</option>
    <option value="fujiapple">Apples</option>
    <option value="vanillaorange">Oranges</option>
    <option value="pandoracherry">Cherries</option>
</select>

So, in this case, if we choose the first valid option, the value of $_POST['fruits'] will not be Apples but fujiapple.

Multiple Options

If you want to enable multiple choices, then there are few a small changes to apply: add two square bracktes [] to the value of the name attribute, the meaning is that we are going to collect an array of values and not a single string. Then add the multiple attribute. So:

<select name="fruits[]" multiple>

When you receive the POST request, the values will be served as an array:

[fruits] => Array
    (
        [0] => fujiapple
        [1] => pandoracherry
    )

Instead of the traditional:

[fruits] => orange

Note: when submitting a multiple select, the user can deselect all the options, in this case the fruits index will be missing from the $_POST array, as the checkboxes. When using the single select, instead, an option of the select group is always submitted. But you should never be confident with that, because a form can be refactored from remote and submitted without some input fields, leading the script to unexpected results.

Prepare for the Database

Now, if you want to save the value to the database table you have different solutions. In case of single option then just verify if the index key exists in the $_POST array and check that the value is not empty:

# initialize the variable
$fruits = '';

# check if the index exists
if(array_key_exists('fruits', $_POST))
{
    $fruits = ! empty($_POST['fruits']) ? $_POST['fruits'] : '';
}

In case of multiple options then check if you have really got an array, check if the values are unique, are not null and then you can choose if you want to store them separately or into a single string. In the first case you will need separated columns, or a separated table referenced by a foreign key, in the second case you can use a single column, for example:

# initialize the variable
$fruits = '';

# check if the index exists
if(array_key_exists('fruits', $_POST))
{
    $fruits = is_array($_POST['fruits']) ? implode(',', array_filter( array_unique( $_POST['fruits']))) : '';
}

The output of $fruits will be a column separated list: vanillaorange,pandoracherry. Which can be stored into a varchar or text column.

Note: to avoid unexpected behavious it is important to initialize the variables that should be filled by the $_POST array.

At this point you can filter and validate the data before saving it to the database table.

Examples

Full example with single option:

<?php

    if($_POST)
    {
        # show the contents of the $_POST array
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";

        # initialize the variable
        $fruits = '';

        # check if the index exists
        if(array_key_exists('fruits', $_POST))
        {
            $fruits = ! empty($_POST['fruits']) ? $_POST['fruits'] : '';
        }

        echo "<p><strong>Result:</strong> $fruits</p>";
    }

?>

<form method="post" action="">

    <select name="fruits">
        <option value="">---</option>
        <option value="fujiapple">Apples</option>
        <option value="vanillaorange">Oranges</option>
        <option value="pandoracherry">Cherries</option>
    </select>

    <input type="submit" name="submit" value="submit" />

</form>

Generated output (result 1):

Array
(
    [fruits] => fujiapple
    [submit] => submit
)

Result: fujiapple

Full example with multiple options:

<?php

    if($_POST)
    {
        # show the contents of the $_POST array
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";

        # initialize the variable
        $fruits = '';

        # check if the index exists
        if(array_key_exists('fruits', $_POST))
        {
            $fruits = is_array($_POST['fruits']) ? implode(',', array_filter( array_unique( $_POST['fruits']))) : '';
        }

        echo "<p><strong>Result:</strong> $fruits</p>";
    }

?>

<form method="post" action="">

    <select name="fruits[]" multiple>
        <option value="">---</option>
        <option value="fujiapple">Apples</option>
        <option value="vanillaorange">Oranges</option>
        <option value="pandoracherry">Cherries</option>
    </select>

    <input type="submit" name="submit" value="submit" />

</form>

Generated output (result 2):

Array
(
    [fruits] => Array
        (
            [0] => fujiapple
            [1] => vanillaorange
        )

    [submit] => submit
)

Result: fujiapple,vanillaorange

Do you note the differences between the results while printing the $_POST arrays?

Your Code

So, in case you want only one single option choosen, then, change your code:

<select data-rel="chosen">
    <option>Productin Unit</option>
    <option>Vendor</option>
</select>

With:

<select data-rel="chosen" name="ListingType">
    <option value="ProductinUnit">Productin Unit</option>
    <option value="Vendor">Vendor</option>
</select>

And check for the $_POST['ListingType'] index key. Hope it helps you to understand how the form works. If you still have doubts, let us know.

Some documentation:

commented: For going the extra mile :) +14

Thans a lot. It really helped me a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.