PHP数据库处理

标签 php mysql

我在一个 php 页面上工作,该页面将客户端收到的信息与数据库中的信息进行比较,但我的 php 不太好,我不知道我做错了什么,我总是得到响应代码 500 , 内部服务器错误。 这是代码:

<?php
/**
 * @var object $payload The payload sent from the client
 */
$payload = json_decode(file_get_contents("php://input"), true);
/**
 * @var object $user_name The username sent by the client
 * @var object $user_name The password sent by the client
 */
$user_name = $payload['username'];
$user_password = $payload['password'];
$response = null;
$responseCode = 200;
$result_row = null;
/**
 * The form representing a positive response
 */
class Response {
    public $accessToken = "";
    public $availableProfiles = "";
    public $selectedProfile = "";
}
/**
 * The form representing a negative response
 */
class negativeResponse {
    public $error = "";
    public $errorMessage = "";
}
/**
 * @var object $db_connection The database connection
 */
$db_connection = null;
try {
    $db_connection = new PDO('mysql:host=localhost;dbname=launcher_login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
    //Catch exception
}

// user can login with his username or his email address.
// if user has not typed a valid email address, we try to identify him with his user_name
if (!filter_var($user_name, FILTER_VALIDATE_EMAIL)) {
    // database query, getting all the info of the selected user
    $query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');
    $query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
    $query_user->execute();
    // get result row (as an object)

    $result_row = $query_user->fetchObject();
// if user has typed a valid email address, we try to identify him with his user_email
} else  {
    // database query, getting all the info of the selected user
    $query_user = $db_connection->prepare('SELECT * FROM users WHERE user_email = :user_email');
    $query_user->bindValue(':user_email', trim($user_name), PDO::PARAM_STR);
    $query_user->execute();
    // get result row (as an object)
    $result_row = $query_user->fetchObject();
}

// if this user not exists
if (!isset($result_row->user_id)) {
    $response = new negativeResponse();
    $response->error = "Credenziali Invalide";
    $response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
    $responseCode=201;
// if the password isn't correct
} else if (!password_verify($user_password, $result_row->user_password_hash)) {
    $response = new negativeResponse();
    $response->error = "Credenziali Invalide";
    $response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
    $responseCode=201;
// if the account exists but it isn't activated
} else if ($result_row->user_active != 1) {
    $response = new negativeResponse();
    $response->error = "Account non attivo";
    $response->errorMessage = "Devi attivare l'account! Controlla l'email inserita";
    $responseCode=201;
} else {
    $response = new Response();
    $response->accessToken = hash('md5', $user_name);
    $response->availableProfiles = array(array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true));
    $response->selectedProfile = array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true);
}
echo json_encode($response);
http_response_code($responseCode);

我的表是用这个查询创建的:

CREATE TABLE IF NOT EXISTS `launcher-login`.`users` (
 `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index',
 `user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name, unique',
 `user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s password in salted and hashed format',
 `user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email, unique',
 `user_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s activation status',
 `user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s email verification hash string',
 `user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password reset code',
 `user_password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request',
 `user_rememberme_token` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s remember-me cookie token',
 `user_failed_logins` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s failed login attemps',
 `user_last_failed_login` int(10) DEFAULT NULL COMMENT 'unix timestamp of last failed login attempt',
 `user_registration_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
 `user_registration_ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
 PRIMARY KEY (`user_id`),
 UNIQUE KEY `user_name` (`user_name`),
 UNIQUE KEY `user_email` (`user_email`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data';

编辑:我觉得自己很愚蠢,错误是 $query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');。我在课外使用这个,现在我在客户端工作,谢谢大家的帮助

最佳答案

我几乎可以肯定问题是 $db_connection 为空,因为连接失败。根据您提供的内容,您的数据库名称应该是 launcher-login 而不是您在连接字符串中指定的 launcher_login 。因此,以下编辑应该可以解决您的问题。

try {
    $db_connection = new PDO('mysql:host=localhost;dbname=launcher-login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
    echo 'Unable to connect to database'; exit;
}

关于PHP数据库处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30006781/

相关文章:

php - Laravel 获取二级关系

mysql - 如何仅选择最近(和多个)值一次?

mysql - 更改特定存储过程的 DEFINER 吗?

php - MySQL 按随机顺序但显示不同的前 5 个结果?

php - 如果字段为空或 !empty 运行查询并且不显示空字段的错误

mysql - 选择2列并合并数据

php - 确保每个用户从一台计算机访问 Web 应用程序

php - 使用 MySQL 和 PHP 将数据插入数据库时​​出现 SQL 错误

php - 绕过我的需要明文大小的 XOR 加密的方法

php - 允许在我网站的 <video> 元素中播放视频,但不允许通过直接链接播放