gpt4 book ai didi

php - 从SQL数据库使用mysql和php获取信息

转载 作者:行者123 更新时间:2023-11-29 14:11:55 25 4
gpt4 key购买 nike

我正在尝试在PHP中创建一个登录类,从SQL DB获取信息。到目前为止,这是我的代码:

class login {
function __construct($username, $password) {
$this->username = $username;
$this->password = $password;

$this->check();
}

function check() {
$query = "
SELECT
User.username
FROM
User
WHERE
User.username = ".(string)$this->username."
AND
User.pass = ".(string)$this->password."
;";

$con = mysql_connect('localhost','root','root');
mysql_select_db('User', $con);
$result = mysql_query($query);
$result = mysql_fetch_array($result);

if(!isset($_SESSION)) session_start();
if(isset($result)) $_SESSION['username'] = $result['username'];

mysql_close($con);

header('Location: ../../');
}

}


我得到这些错误:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in login.php on line 26

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at login.php:26) in login.php on line 28

Warning: Cannot modify header information - headers already sent by (output started at login.php:26) in login.php on line 33


如果我在终端中运行MYSQL代码,则会得到正确的答案。所以我不明白为什么它在PHP中不起作用。

稍有更新的代码;同样的错误:

class login {
function __construct($username, $password) {
(string)$this->username = $username;
(string)$this->password = $password;

$this->check();
}

function check() {
$query = "
SELECT
User.username
FROM
User
WHERE
User.username = '".mysql_real_escape_string((string)$this->username)."'
AND
User.pass = '".mysql_real_escape_string((string)$this->password)."'
;";

$con = mysql_connect('localhost','root','root');
mysql_select_db('User', $con);
$result = mysql_query($query);

if (!$result) {
die('MySQL Error: ' . mysql_error());
}

$result = mysql_fetch_array($result);

if(!isset($_SESSION)) session_start();
if(isset($result)) $_SESSION['username'] = $result['username'];

mysql_close($con);

header('Location: ../../');
}

}

最佳答案

您正在运行的SQL语句中将出现错误,因为您要按字面意义而不是字符串形式包含用户名和密码(即,引号会丢失)。

    $query = "
SELECT
User.username
FROM
User
WHERE
User.username = '".mysql_real_escape_string((string)$this->username)."'
AND
User.pass = '".mysql_real_escape_string((string)$this->password)."'
;";


您可以在尝试使用以下结果之前检查查询中的错误:

$result = mysql_query($query);
if (!result) {
die('MySQL Error: ' . mysql_error()); // this will print the MySQL error message
}


另外,您不应该再使用mysql_函数了,因为它们既旧又不安全。您应该使用mysqli或PDO,以及准备好的语句。 mysqli可以很容易地替代mysql_。

http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

关于php - 从SQL数据库使用mysql和php获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13368449/

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