PHP,帮助重写代码以使用预处理语句

时间:2011-08-09 03:03:14

标签: php mysqli

请问我可以使用预备语句(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 -------------------------- < / p>

我可以将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";
            }

1 个答案:

答案 0 :(得分:3)

这是一般语法。

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

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