gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:51:34 25 4
gpt4 key购买 nike

请帮我重写以下代码,使用准备好的语句 (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";
}

注意没有引号/定界符的问号占位符,当我绑定(bind)参数时,我指定了 SS,因为这两个参数都是字符串

关于PHP,帮助重写代码以使用准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6990961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com