开发者

PHP, help rewriting code to use prepared statements

Please could I get some help 开发者_JAVA技巧rewriting the following code, using prepared statements (mysqli), it's new to me and trying to get to grips with it:

        $sql = sprintf("SELECT `user`.`firstname`, `user`.`lastname` from `user` where `user`.email='%s' and `user`.password='%s'",
                mysql_escape($_POST['username']), 
                mysql_escape($_POST['password'])
            );
        $name = mysql_query($sql);
        if(mysql_num_rows($name)==1){
            $_SESSION['name'] = mysql_fetch_assoc($name);
            header("Location: /in.php");
            exit();
        }else{
            echo "here";
        }

-------------------------UPDATE-----------------

mysql_escape the following function:

            function mysql_escape($data){return(mysql_real_escape_string((get_magic_quotes_gpc())?stripslashes($data):$data));}

-------------------UPDATE2--------------------------

I can write the select statement as:

            $stmt = $db->prepare("SELECT `user`.`firstname`, `user`.`lastname` from `user` where `user`.email=? and `user`.password=?");
            $stmt->bind_param("ss", $_POST['username'], $_POST['password']);
            $stmt->execute();
            $stmt->close();

but I am struggling with this part:

            $name = mysql_query($sql);
            if(mysql_num_rows($name)==1){
                $_SESSION['name'] = mysql_fetch_assoc($name);
                header("Location: /in.php");
                exit();
            }else{
                echo "here";
            }


This is the general syntax.

    $dbconn = mysql_connect(...);
    $query  = $dbconn->prepare( "SELECT `user`.`name` from `user` where `user`.email=? and `user`.password=?" );

    $query->bind_param( "ss", $_POST['username'], $_POST['password'] );

    if ( $query->execute( ) == true ){
         $row = $query->fetch()) 
        $_SESSION['name'] = $row;
        header("Location: /in.php");
        exit();
    }else{
        echo "here";
    }

note the question mark placeholders without quotes/delimiters, when I'm binding the params, I'm specifying SS because the two params are both strings

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜