PHP,帮助重写代码以使用准备好的语句


PHP, help rewriting code to use prepared statements

我可以得到一些帮助重写以下代码,使用准备好的语句(mysqli),这对我来说是新的,并试图掌握它:

        $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";
        }

------------------------- 更新 -----------------

mysql_escape以下函数:

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

------------------- 更新2 --------------------------

我可以把select语句写成:

            $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();

但我正在努力与这部分:

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

这是通用语法。

    $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";
    }

注意没有引号/分隔符的问号占位符,绑定参数时,指定的是SS因为这两个参数都是字符串