Я пытаюсь создать простую систему входа, и я запрашиваю, чтобы узнать, существует ли в базе данных имя пользователя, которое пользователь предоставил. Однако у меня возникают проблемы с получением строки. Я продолжаю получать переменную num num: error.I также пытались использовать,Неопределенная переменная: num
$num = $stmt->rowCount();
Однако затем я получаю вызов функции члена ROWCOUNT() на не-объект error.I очень новой для PHP и веб-разработки, и это смущало меня, и я не Не знаете, как заставить его работать, может кто-то мне помочь? Вот код для db.php файла
<?php
require "config.php";
function DBconnect($config) {
try {
$conn = new PDO('mysql:host=localhost;dbname=' . $config['database'],
$config['username'],
$config['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch(Exception $e) {
return false;
}
}
function query($query, $bindings, $conn) {
$stmt = $conn->prepare($query);
$stmt->execute($bindings);
return $stmt;
}
А вот код для файла index.php, который является страница Войти.
<?php
// Allow sessions to be passed so we can see if the user is logged in
session_start();
// include the necessary files
require "db.php";
require "functions.php";
include "index.view.php";
//conect to the database so we can check, edit or ,data to our users table
$conn = DBconnect($config);
// if the user has submitted the form
if($_SERVER["REQUEST_METHOD"] === "POST") {
//protect the posted value then store them to variables
$username = protect($_POST["username"]);
$password = protect($_POST["password"]);
//Check if the username or password boxes were not filled in
if (!$username || !$password){
// if not display an error message.
echo "You need to fill in a username and password!";
}else
// if correct continue cheking
//select all the rows where the username and password match the ones submitted by the user
query( "SELECT * FROM users WHERE username = :username",
array("username" => $username),
$conn);
$num = $stmt->fetchColumn();
//check if there was not a match
if($num == 0) {
//if not display an error message
echo "The username you entered does not exist!";
}else{
//if there was a mactch continue chekcing
//select all rows where the username and password match the ones submitted by the user
query("SELECT * FROM users WHERE username =:username && password = :pasword",
array("username" => $username, "password" => $password),
$conn);
$num = $stmt->fetchColumn();
//check if there was not a match
if($num == 0) {
//if not display error message
echo "Username and password do not mactch";
}else {
//if there was continue checking
//split all the fields from the correct row into an associative array
$row = $user->fetch(PDO::FETCH_ASSOC);
//check to see if the user has not activated their account
if($row["active"] != 1) {
//if not display an error message
echo "You have not yet activated your account!";
}else {
//if so then log them in
// set the login session storing their id. We use this to
// see if they are logged in or not.
$_SESSION["uid"] = $row["id"];
//show message confirming that they are loggd in
echo "You have succesfully logged in!";
//update the online field to 50 seconds in the future
$time = date("u")+50;
query("UPDATE users SET online = :time WHERE id = :id",
array("time" => $time, "id" => $_SESSION["uid"]),
$conn);
//redirect them to the usersonline page
header("Location: usersOnline.php");
}
}
}
}
спасибо я попытался это, но тогда я получаю [Фатальная ошибка: неперехваченным исключение «PDOException» с сообщением «SQLSTATE [HY093]: Недопустимый номер параметра: параметр не был определен 'в C: \ wamp \ www \ sideProjects \ loginTut \ db.php в строке 21] ошибка: S i также получает PDOException: SQLSTATE [HY093]: недопустимый номер параметра: параметр не определен в C: \ wamp \ www \ sideProjects \ loginTut \ db.php в строке 21 ошибка, и я не могу понять, что они означают: S – Brock90
@ Brock90 Эй, нужно уйти сейчас с компьютера. Может помочь вам с синтаксическими ошибками позже, если вы захотите. Во время этого вы должны попробовать себя;). Оставьте комментарий здесь, если у вас есть дальнейший вопрос .. см. U – hek2mgl
Благодарим за помощь. Я получил страницу для работы, но я хочу спросить, знаете ли вы, что лучший способ показывать ошибки вместо echo.i попытался поместить пустой массив в верхней части страницы $ data = array(); а затем меняя все эхо-сигналы «.....» на $ data ["status"] = "......", и на моей странице просмотра я сделал if isset ($ stsus):?>
= $ status; ?>
Php endif; ?> но по какой-то причине он не работает. И спасибо за вашу помощь. – Brock90