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

请使用准备好的语句(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";
        }

————————- UPDATE —————–

mysql_escape的以下功能:

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

——————- UPDATE2 ————————–

我可以将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是因为两个参数都是字符串

上一篇:MYSQL事务的概念和事务处理方法


下一篇:mysql-Bind_param非对象错误