Jump to content

Help me understand this mysql connection.


MuphN
Go to solution Solved by Ch0cu3r,

Recommended Posts

Okey. So I read tutorial how to make log/reg sacure script. I did understand most of things. But now I need to add for exemple an option to it.

I have 

register page with containts:

        <form action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>" 
                method="post" 
                name="registration_form">
            Username: <input type='text' 
                name='username' 
                id='username' /><br>
            Email: <input type="text" name="email" id="email" /><br>
            Password: <input type="password"
                             name="password" 
                             id="password"/><br>
            Confirm password: <input type="password" 
                                     name="confirmpwd" 
                                     id="confirmpwd" /><br>
            <input type="button" 
                   value="Register" 
                   onclick="return regformhash(this.form,
                                   this.form.username,
                                   this.form.email,
                                   this.form.password,
                                   this.form.confirmpwd);" /> 
								   <select class="select">
									<option id="Archer" selected>Archer</option>
									<option id="Swordsman">SwordsMan</option>
									<option id="Assasin">Assasin</option>
									<option id="Dualist">Dualist</option>
									</select>
        </form>

and then there is my option:

in my functions.php

function dropdown( $name, array $options, $selected=null )
{
    /*** begin the select ***/
    $dropdown = '<select name="'.$name.'" id="'.$name.'">'."\n";

    $selected = $selected;
    /*** loop over the options ***/
    foreach( $options as $key=>$option )
    {
        /*** assign a selected value ***/
        $select = $selected==$key ? ' selected' : null;

        /*** add each option to the dropdown ***/
        $dropdown .= '<option value="'.$key.'"'.$select.'>'.$option.'</option>'."\n";
    }

    /*** close the select ***/
    $dropdown .= '</select>'."\n";

    /*** and return the completed dropdown ***/
    return $dropdown;
}
----- In reg.php. Functions are included.
		<?php
$name = 'my_dropdown';
$options = array( 'test', 'Dtrsdft', 'Asdfgn', 'Adfs' );
$selected = 0;

echo dropdown( $name, $options, $selected );
?>




and this is my whole rgister.inc.php file. Which adds contet to detabase

<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
 
$error_msg = "";
 
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
    // Sanitize and validate the data passed in
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Not a valid email
        $error_msg .= '<p class="error">The email address you entered is not valid</p>';
    }
 
    $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
    if (strlen($password) != 128) {
        // The hashed pwd should be 128 characters long.
        // If it's not, something really odd has happened
        $error_msg .= '<p class="error">Invalid password configuration.</p>';
    }
 
    // Username validity and password validity have been checked client side.
    // This should should be adequate as nobody gains any advantage from
    // breaking these rules.
    //
 
    $prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
 
    if ($stmt) {
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->store_result();
 
        if ($stmt->num_rows == 1) {
            // A user with this email address already exists
            $error_msg .= '<p class="error">A user with this email address already exists.</p>';
        }
    } else {
        $error_msg .= '<p class="error">Database error</p>';
    }
	
    // TODO: 
    // We'll also have to account for the situation where the user doesn't have
    // rights to do registration, by checking what type of user is attempting to
    // perform the operation.
 
    if (empty($error_msg)) {
        // Create a random salt
        $random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
 
        // Create salted password 
        $password = hash('sha512', $password . $random_salt);
 
        // Insert the new user into the database 
        if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
            $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
            // Execute the prepared query.
            if (! $insert_stmt->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
            }
        }
        header('Location: ./register_success.php');
    }
}?>

So, I need to understand how dose it work. I understand somethings. but not all of it. Talking about transfering username, password and so on.

 

So I need to transfare the Option aswell.

for exemple table name is members and add an option to "Things" on members table. 

 

Dont understand this part especealy prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)") - does the "?" gets the values from cookies or something?

 

Would be grateful for help. 

 

Link to comment
Share on other sites

  • Solution

 

Dont understand this part especealy prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)") - does the "?" gets the values from cookies or something?

This is a special query called a prepared statement. Prepared statements handles the input values separately from the actual query. This is to help prevent a vulnerability called SQL Injection. The values are coming from the bind_param() in the order they are listed.

$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt); 

--

 

 

So I need to transfare the Option aswell.

You have named the option as my_dropdown so you'll get it from $_POST['my_dropdown']. if you want to use the filter_input function it'll be

$my_dropdown = filter_input(INPUT_POST, 'my_dropdown', FILTER_SANITIZE_STRING);

$my_dropdown will contain the selected value.

Edited by Ch0cu3r
Link to comment
Share on other sites

So as I understood that, if I name my new dropdown .

$drop = filter_input(INPUT_POST, 'my_dropdown', FILTER_SANITIZE_STRING); and I place it somewhere near

$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);

if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}

$drop = filter_input(INPUT_POST, 'my_dropdown', FILTER_SANITIZE_STRING); and I place it somewhere near for exemple like that.

 

and place "<?php

$name = 'my_dropdown';
$options = array( 'test', 'Dtrsdft', 'Asdfgn', 'Adfs' );
$selected = 0;

echo dropdown( $name, $options, $selected );
?>" in register <form>

 

and then I place

prepare("INSERT INTO members (username, email, password, salt, Thing) VALUES (?, ?, ?, ?, $drop)") //is that correct? - I dont really understand the questionmarks, dose it include the posts in row, For exemple if option will be last one its the last ? or username will be after password so there will be like username on password?

Edited by MuphN
Link to comment
Share on other sites

 

So as I understood that, if I name my new dropdown .

 

....

 

and place

...

 

Yes that should be fine.

 

 

 

and then I place

No you'll add a ? (placeholder) and pass the value in the bind_param()

        if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt, Thing) VALUES (?, ?, ?, ?, ?)")) { // define query
            $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt, $drop); // add the values to query
Link to comment
Share on other sites

Oh, change   bind_param('ssss',  to  bind_param('sssss',

                                                   ^ add 5th s

 

I forgot to mention that earlier. The s stands for string it defines that data type for the input.

Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.