Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Sending data to the database using PHP question

Is this the right code i need to be using to send the inserted data?

 $sql = mysqli_query($con,"INSERT INTO Persons (username, userpass, email)
        VALUES(     '" . mysqli_real_escape_string($_POST['username']) . "', 
                    '" . sha1($_POST['userpass']) . "', 
                    '" . mysqli_real_escape_string($_POST['email']) . "'");

Depends on the purpose. What are you trying to do?

I'm trying to make a sign up form, and send the data from the sign up form to the database. But it keeps giving me an error.

Here's the full code if this helps

<?php  
$pageTitle = "Sign Up";

$pageCategory = "Sign Up";
$pageCategoryurl = "/signup.php";


//signup.php   
include($_SERVER["DOCUMENT_ROOT"] . "/inc/database3.php");
include($_SERVER["DOCUMENT_ROOT"] . "/inc/header.php"); 
include($_SERVER["DOCUMENT_ROOT"] . "/inc/search.php");

echo '<div class="ccontent">';

echo '<h3>Sign up</h3>'; 

if($_SERVER['REQUEST_METHOD'] != 'POST')  
{  
    /*the form hasn't been posted yet, display it 
      note that the action="" will cause the form to post to the same page it is on */  
    echo '<form method="post" action="">  
        Username: <input type="text" name="username" /><br>  
        Password: <input type="password" name="userpass"><br>  
        Password again: <input type="password" name="user_pass_check"><br>  
        E-mail: <input type="email" name="email"><br>  
        <input type="submit" value="Add category" />  
     </form>'; 
} 
else 
{ 
    /* so, the form has been posted, we'll process the data in three steps:  
        1.  Check the data  
        2.  Let the user refill the wrong fields (if necessary)  
        3.  Save the data   
    */  
    $errors = array(); /* declare the array for later use */  


    if(isset($_POST['username']) && !empty($_POST['username']))
    {  
        //the user name exists  
        if(!ctype_alnum($_POST['username']))  
        {  
            $errors[] = 'The username can only contain letters and digits.';  
        }  
        if(strlen($_POST['username']) > 70)  
        {  
            $errors[] = 'The username cannot be longer than 70 characters.';  
        }  
        if(strlen($_POST['username']) < 5)  
        {  
            $errors[] = 'The username cannot be shorter than 5 characters.';  
        }  

    }  
    else  
    {  
        $errors[] = 'The username field must not be empty.';  
    }  


    if(isset($_POST['userpass']) && !empty($_POST['userpass']))  
    {  
        if(!ctype_alnum($_POST['userpass']))  
        {  
            $errors[] = 'The password can only contain letters and digits.';  
        }  
        if(strlen($_POST['userpass']) > 20)  
        {  
            $errors[] = 'The password cannot be longer than 20 characters.';  
        }  
        if(strlen($_POST['userpass']) < 6)  
        {  
            $errors[] = 'The password cannot be shorter than 6 characters.';  
        }
        if($_POST['userpass'] != $_POST['user_pass_check'])  
        {  
            $errors[] = 'The two passwords did not match.';  
        }  
    }  
    else  
    {  
        $errors[] = 'The password field cannot be empty.';  
    }  

    if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/  
    {  
        echo 'Uh-oh.. a couple of fields are not filled in correctly..'; 
        echo '<ul>'; 
        foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */ 
        { 
            echo '<li>' . $value . '</li>'; /* this generates a nice error list */ 
        } 
        echo '</ul>'; 
    } 
    else 
    { 
        //the form has been posted without, so save it 
        //notice the use of mysql_real_escape_string, keep everything safe! 
        //also notice the sha1 function which hashes the password 

        $sql = mysqli_query($con,"INSERT INTO Persons (username, userpass, email)
        VALUES(     '" . mysqli_real_escape_string($_POST['username']) . "', 
                    '" . sha1($_POST['userpass']) . "', 
                    '" . mysqli_real_escape_string($_POST['useremail']) . "'");

        $result = mysql_query($sql);  
        if(!$result)  
        {  
            //something went wrong, display the error  
            echo 'Something went wrong while registering. Please try again later.'; 
            //echo mysql_error(); //debugging purposes, uncomment when needed 
        } 
        else 
        { 
            echo 'Successfully registered. You can now <a href="/signin.php">sign in</a> and start posting! :-)'; 
        } 
    } 
} 




echo '</div>';  
include($_SERVER["DOCUMENT_ROOT"] . "/inc/footer.php");
?> 

4 Answers

You're not closing the parentheses for VALUES( ). That's my next guess, and something I should have caught before but wasn't looking for it. I have to assume that $con is a valid connection.

Dang. I'm horrible at making sure I add on as a comment.

Yep, that was it. It sent the data. However, is it normal to not be able to see the username and email in SQL workbench? There is a row that was created but it shows nothing is in it.

I'm not really sure. I'm not very familiar with SQL workbench, but I know in phpmysql, I end up in the wrong view all the time.

As a side note, it's good practice to append a unique salt to passwords before hashing and storing them. This makes the hashed value more secure as it doesn't directly correlate to a user's password. Read more about using salts for password hashing.

That was supposed to be a comment. Oh well.

I see two issues in your full code.

  1. Running $sql = mysqli_query(...); executes a query against the database and returns a boolean for an INSERT query, so running $result = mysql_query($sql) tries to query a php boolean to the database, which will always return an error.
  2. The mysql_query function is deprecated, so I'd stick the the mysqli_query.

Essentially the fix is just to drop that line, and change $sql = ... to $result = .... It would look like this:

<?php
$result = mysqli_query($con,"INSERT INTO Persons (username, userpass, email)
VALUES(     '" . mysqli_real_escape_string($_POST['username']) . "', 
                    '" . sha1($_POST['userpass']) . "', 
                    '" . mysqli_real_escape_string($_POST['useremail']) . "'");

if(!$result)  
{  
    //something went wrong, display the error  
    echo 'Something went wrong while registering. Please try again later.'; 
    //echo mysql_error(); //debugging purposes, uncomment when needed 
} 
else 
{ 
    echo 'Successfully registered. You can now <a href="/signin.php">sign in</a> and start posting! :-)'; 
}

hmm, I changed it to that but it still isn't sending the information to the database.

Hi Trevor,

I also need to create a registration form and transfer the data into a php my-admin database, would it be possible to send me your code source to my inbox. If thats OK, I will forward you my email address

Thanks Martin