Question

I was hoping someone could help me with a small script I am writing, my main goal is to just make a registration page as secure as possible and thought the best place to start would be using mysql_real_escape_string however it wont keep I just keep getting error at line 1 so here's my code:

<?php
if(isset($_POST['submit'])){
    if($_POST['username'] == "" || $_POST['password'] == ""){
        header("Location: tryagain.php");
        exit; 
    }else{
        mysql_connect("localhost", "root", "Root") or die(mysql_error());
        mysql_select_db("test") or die(mysql_error());
        $username = $_POST['username'];
        $password  = $_POST['password'];
        $sql = sprintf("INSERT into login(id,username,password) values('','%s','%s'", mysql_real_escape_string($username), mysql_real_escape_string($password));
        $result = mysql_query($sql) or die(mysql_error()) ;
        echo "Congratulations it worked woooo";
    }
}
?>

and heres the html

<form method="post" action="sql.php">
    <table>
        <tr>
            <td>
                <input type="text" name="username"/>
            </td>
            <td>
                <input type="text" name="password"/>
            </td>
            <td>
                <input type="submit" name="submit" value="submit">
            </td>
        </tr>
    </table>
</form>

If i change the $sql statment to this the code works fine

$sql = "INSERT into login(id,username,password) values('','$username','$password')";

Can anyone see what I've done wrong :S it works perfectly fine when I adjust it to log in using real escape.

Also what other methods can I use to validate data? I plan on making the if statements check for only number and letters, and just prevent any special characters all together. Thanks.

On a side note, yes I know mysqli and pdo should be used not mysql sadly were I'm at they don't use them.

Was it helpful?

Solution

Your SQL statement is broken:

INSERT into login(id,username,password) values('','%s','%s'

Should be

INSERT into login(id,username,password) values('','%s','%s')

OTHER TIPS

Not sure what is your issue, I'm thinking sprintf. Maybe try this :

    $username = mysql_real_escape_string($_POST['username']);
    $password  = mysql_real_escape_string($_POST['password']);
    $sql = sprintf("INSERT into login(id,username,password) values('','%s','%s', $username, $password)");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top