I have created a form that should submit some content in the database. A make an random numberstring and then when a submit I want the content insert into database. But before submit the random numbers is repeated and I got a new one. How to eliminate that?
<?php
include_once('../includes/connection.php');
$random = rand(1000, 2000)
$dedu = $pdo->prepare("UPDATE users SET user_password ='$random'");
$password = $_POST['password'];
$query = $pdo->prepare("SELECT * FROM users WHERE user_password = ?");
$query->bindValue(1, $password);
$dedu->execute();
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (empty($title) or empty($content)) {
$error = 'All fields are requried';
} else {
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content) Values (?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->execute();
$msg = 'You added the following article!';
}
}
} else {
$error = 'Incorrect details!';
}
?>
<html>
<head>
<title>dwa</title>
<link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">
</head>
<body>
<div class="container">
CMS
<br />
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<div class="error">
<small style="color:#aa0000;"><?php echo $error; ?></small>
</div>
<?php } ?>
<form action="test.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="title" /><br />
<textarea rows="15" cols="50" placeholder="content" name="content"></textarea><br />
<input type="submit" value="Add Article" />
<input type="password" name="password" />
</form>
<?php if (isset($msg)) { ?>
<div class="msg">
<small style="color:orange"><?php echo $msg;?> <br /><H3>
<?php echo $title; ?></h3><h5><?php echo $content; ?></h5></small>
</div><?php } ?>
</div>
</body>
</html>
Not sure if i understand correctly what you want to achieve but try putting
$random = rand(1000, 2000)
after
$query->execute();
Use this cookie concept in your file
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
//dont do anything
} else {
$random = rand(1000, 2000);
}........proceed with your code
?>
if(isset($_POST['password']))$password = $_POST['password'];
else $random = rand(1000, 2000);
I solved it with a session!
If the session is false the rand function runs and the session is set to true. When the page reloads(submit pressed) the session is true so all the other cod runs. In the end of the code (if session is true) the session is destroyd. Because If the user want a new rand the reload the page and the rand function runs again.
Related
whatever I enter I get the same error "all fields are required" but this error should appear only when field/s is empty.
I have other error should appear when I enter incorrect details but I keep only getting the first error.
I'm a beginner and I had one hour reviewing my code but I still can't solve it by myself :/
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])){
//display index
} else {
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or ($password)) {
$error = 'All fileds are required';
}else {
$query = $pdo->prepare("SELECT * FROM user WHERE user_name = ? AND user_password = ? ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
//user entered correct details
}else {
// user enterde false details
echo $error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
<title>CMS Tuterial</title>
<link rel="stylesheet" href="../assets/style.css" />
</head>
<body>
<div class="container">
CMS
<br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small>
<br /><br />
<?php } ?>
<form action="index.php" method="POST" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
<?php
}
?>
This question already has answers here:
How to redirect to the same page in PHP
(9 answers)
Closed 8 months ago.
After submitting information to my database, I want to refresh the page to show those changes, as when the form has been processed. The page "reloads" after submission but does not reflect the changes, so I assumed I would need to add a refresh command in when submit is pressed, but it seems to be too quick?
So I added a refresh time, but even cranking it up to 50 I got the same result.
If I press the button twice it refreshes with the correct information. Is there a better way to do this?
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once '../includes/conn.php';
if(!$user->is_loggedin()){
$user->redirect('../users/login.php');
}
$id = $_SESSION['session'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$location = isset($_POST['location']) ? $_POST['location'] : '';
$about = isset($_POST['about']) ? $_POST['about'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
}
if($location!=''){
$sql = "UPDATE users SET location=:location WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Location update failed. Please try again.";
}
$result = $stmt->execute(array(":location"=>$location, ":id"=>$id));
if($result == false) {
$error = "User location update failed. Please try again.";
}
$count = $stmt->rowCount();
}
if($about!=''){
$sql = "UPDATE users SET about=:about WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "about Me update failed. Please try again.";
}
$result = $stmt->execute(array(":about"=>$about, ":id"=>$id));
if($result == false) {
$error = "about Me location update failed. Please try again.";
}
$count = $stmt->rowCount();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Users Edit Profile</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</ul>
</div>
</div>
<div id="content">
<form method="post"><br />
<h2>Edit Profile</h2>
<label><strong>User Title:</strong></label><br />
<input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
<label><strong>My Location:</strong></label><br />
<input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
<label><strong>About Me:</strong><label><br />
<textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
<button type="submit" name="update">Update</button><br /><br /><br />
<?php
if(isset($_POST['submit'])){
header('refresh:20; Location: '.$_SERVER['REQUEST_URI']);
}
?>
</form>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
You are doing it wrong, you have to process the form submission BEFORE showing the HTML. PHP is being executed line-by-line so in your case you are firstly showing the data and then you are checking if the form is submitted. Simply move this code up where the rest of your PHP code is located (you can even remove the refresh stuff command):
if(isset($_POST['submit'])){
header('Location: '.$_SERVER['REQUEST_URI']);
die;
}
Edit:
People invented MVC because of cases like yours when you are mixing HTML and PHP and wonder why things don't work. Keep your PHP code at the top of the files, try not to write PHP code anywhere inside HTML, you will save yourself a lot of trouble. And also, use exit after calling header to stop code execution any further. Here is an updated version of your code, simplified and more "algorithmic" (I hope you do see and understand how the code flow goes):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once '../includes/conn.php';
if(!$user->is_loggedin()){
$user->redirect('../users/login.php');
}
$id = $_SESSION['session'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['submit'])) {
$location = isset($_POST['location']) ? $_POST['location'] : null;
$about = isset($_POST['about']) ? $_POST['about'] : null;
$title = isset($_POST['title']) ? $_POST['title'] : null;
$sql_part = array();
$prepare = array();
if ($location) {
$sql_part[] = 'location = :location';
$prepare[':location'] = $location;
}
if ($about) {
$sql_part[] = 'about = :about';
$prepare[':about'] = $about;
}
if ($title) {
$sql_part[] = 'title = :title';
$prepare[':title'] = $title;
}
$prepare[':id'] = $id;
if (count($sql_part)) {
$sql = 'UPDATE users SET ';
$sql .= implode(', ', $sql_part);
$sql .= ' WHERE id = :id';
$stmt = $dbh->prepare($sql);
if ($stmt) {
// Find another way too pass these through the refresh
// $result = $stmt->execute($prepare);
// $count = $stmt->rowCount();
header('Location: '. $_SERVER['REQUEST_URI']);
exit;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Users Edit Profile</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</ul>
</div>
</div>
<div id="content">
<form method="post"><br />
<h2>Edit Profile</h2>
<label><strong>User Title:</strong></label><br />
<input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
<label><strong>My Location:</strong></label><br />
<input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
<label><strong>About Me:</strong><label><br />
<textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
<button type="submit" name="update">Update</button><br /><br /><br />
</form>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
I managed to get the desired result by adding header('Location: ./editprofile.php'); after the database was updated. See bellow:
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
}
After:
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
header('Location: ./editprofile.php');
}
just use JavaScript's-
window.location.reload().
In PHP you can use-
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
This question already has answers here:
How to redirect to the same page in PHP
(9 answers)
Closed 8 months ago.
After submitting information to my database, I want to refresh the page to show those changes, as when the form has been processed. The page "reloads" after submission but does not reflect the changes, so I assumed I would need to add a refresh command in when submit is pressed, but it seems to be too quick?
So I added a refresh time, but even cranking it up to 50 I got the same result.
If I press the button twice it refreshes with the correct information. Is there a better way to do this?
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once '../includes/conn.php';
if(!$user->is_loggedin()){
$user->redirect('../users/login.php');
}
$id = $_SESSION['session'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$location = isset($_POST['location']) ? $_POST['location'] : '';
$about = isset($_POST['about']) ? $_POST['about'] : '';
$title = isset($_POST['title']) ? $_POST['title'] : '';
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
}
if($location!=''){
$sql = "UPDATE users SET location=:location WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Location update failed. Please try again.";
}
$result = $stmt->execute(array(":location"=>$location, ":id"=>$id));
if($result == false) {
$error = "User location update failed. Please try again.";
}
$count = $stmt->rowCount();
}
if($about!=''){
$sql = "UPDATE users SET about=:about WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "about Me update failed. Please try again.";
}
$result = $stmt->execute(array(":about"=>$about, ":id"=>$id));
if($result == false) {
$error = "about Me location update failed. Please try again.";
}
$count = $stmt->rowCount();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Users Edit Profile</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</ul>
</div>
</div>
<div id="content">
<form method="post"><br />
<h2>Edit Profile</h2>
<label><strong>User Title:</strong></label><br />
<input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
<label><strong>My Location:</strong></label><br />
<input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
<label><strong>About Me:</strong><label><br />
<textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
<button type="submit" name="update">Update</button><br /><br /><br />
<?php
if(isset($_POST['submit'])){
header('refresh:20; Location: '.$_SERVER['REQUEST_URI']);
}
?>
</form>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
You are doing it wrong, you have to process the form submission BEFORE showing the HTML. PHP is being executed line-by-line so in your case you are firstly showing the data and then you are checking if the form is submitted. Simply move this code up where the rest of your PHP code is located (you can even remove the refresh stuff command):
if(isset($_POST['submit'])){
header('Location: '.$_SERVER['REQUEST_URI']);
die;
}
Edit:
People invented MVC because of cases like yours when you are mixing HTML and PHP and wonder why things don't work. Keep your PHP code at the top of the files, try not to write PHP code anywhere inside HTML, you will save yourself a lot of trouble. And also, use exit after calling header to stop code execution any further. Here is an updated version of your code, simplified and more "algorithmic" (I hope you do see and understand how the code flow goes):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include_once '../includes/conn.php';
if(!$user->is_loggedin()){
$user->redirect('../users/login.php');
}
$id = $_SESSION['session'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if (isset($_POST['submit'])) {
$location = isset($_POST['location']) ? $_POST['location'] : null;
$about = isset($_POST['about']) ? $_POST['about'] : null;
$title = isset($_POST['title']) ? $_POST['title'] : null;
$sql_part = array();
$prepare = array();
if ($location) {
$sql_part[] = 'location = :location';
$prepare[':location'] = $location;
}
if ($about) {
$sql_part[] = 'about = :about';
$prepare[':about'] = $about;
}
if ($title) {
$sql_part[] = 'title = :title';
$prepare[':title'] = $title;
}
$prepare[':id'] = $id;
if (count($sql_part)) {
$sql = 'UPDATE users SET ';
$sql .= implode(', ', $sql_part);
$sql .= ' WHERE id = :id';
$stmt = $dbh->prepare($sql);
if ($stmt) {
// Find another way too pass these through the refresh
// $result = $stmt->execute($prepare);
// $count = $stmt->rowCount();
header('Location: '. $_SERVER['REQUEST_URI']);
exit;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Users Edit Profile</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<img id="logo" src="../images/logo.png" />
<div id="navigation">
<ul>
<li>Home</li>
<li>My Profile</li>
<li>Admin Panel</li>
</ul>
</div>
</div>
<div id="content">
<form method="post"><br />
<h2>Edit Profile</h2>
<label><strong>User Title:</strong></label><br />
<input type="text" name="title" maxlength="50" placeholder="<?php echo ($userRow['title']); ?>" /><br /><br />
<label><strong>My Location:</strong></label><br />
<input type="text" name="location" maxlength="50" placeholder="<?php echo ($userRow['location']); ?>" /><br /><br />
<label><strong>About Me:</strong><label><br />
<textarea name="about" rows="13" cols="60" maxlength="255" placeholder="<?php echo ($userRow['about']); ?>"></textarea><br /><br />
<button type="submit" name="update">Update</button><br /><br /><br />
</form>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
I managed to get the desired result by adding header('Location: ./editprofile.php'); after the database was updated. See bellow:
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
}
After:
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
header('Location: ./editprofile.php');
}
just use JavaScript's-
window.location.reload().
In PHP you can use-
$page = $_SERVER['PHP_SELF'];
$sec = "10";
header("Refresh: $sec; url=$page");
I am trying to delete a row from a table using PHP (PDO) on a page listing the rows entered into the database. I've been tinkering with the delete.php code to try to make it work but to no avail. I appreciate any help.
Below is my code:
listview.php
session_start();
include_once('../includes/connection.php');
include_once('../includes/events.php');
$event = new Event;
$events =$event->fetch_all();
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to the admin page</title>
</head>
<body>
<div class="container">
<h1>The List of Events</h1>
<ol>
<?php foreach ($events as $event) { ?>
<li>
<?php echo $event['event_name']; ?>
<?php echo $event['event_date']; ?>
<?php echo $event['event_location']; ?>
<?php echo $event['description']; ?>
<?php echo $event['start_time']; ?>
<?php echo $event['end_time']; ?>
<?php echo $event['poc_name']; ?>
<?php echo $event['poc_email']; ?>
<?php echo $event['poc_number']; ?>
<!--edit/delete links-->
Edit
Delete
<!--end edit/delete links-->
</li>
<?php } ?>
</ol>
</div>
</body>
</html>
<?php
} else {
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
//check the fields in the login form
if(empty($username) or empty($password)) {
$error = 'All fields are required';
} else {
$query = $dbh->prepare("SELECT * FROM admin WHERE username = ? AND userpassword = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if($num == 1) {
//correct
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
//incorrect
$error = 'Incorect details';
}
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Squeegee Admin Login</title>
</head>
<body>
<div class="container">
Squeegee Admin
<br/>
<?php if (isset($error)) { ?>
<small style="color:#aa000; "><?php echo $error; ?> </small>
<?php } ?>
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
<?php } ?>
Connection
<?php
// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=squeegee", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
events.php
<?php
class Event {
//queries from database
public function fetch_all() {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events");
$query->execute();
return $query->fetchAll();
}
//queries specific article via id
public function fetch_data($event_id) {
global $dbh;
$query = $dbh->prepare("SELECT * FROM events WHERE event_id = ? ");
$query->bindValue(1, $event_id);
$query->execute();
return $query->fetch();
}
}
?>
delete.php
<?php
include('../includes/connection.php');
$event_id=$_GET['event_id'];
$result = $dbh->prepare("DELETE FROM events WHERE event_id= :event_id");
$result->bindParam(':event_id', $event_id);
$result->execute();
header("location: index.php");
?>
As your question stands, it seems you're accessing the wrong index.
In your link it is defined as id:
Delete
// ^
But then accessed in your PHP file as:
$event_id=$_GET['event_id'];
Must be: $event_id = $_GET['id'];
Either you change your url as ?event_id in the anchor or change the array index in your PHP $event_id = $_GET['id'];. The important things is they must match.
I made a login that worked perfectly, but now im copying the original and editing it to work on another one of my web projects and it jsut dosnt seam to want to work, any help would be appreciated!
Here is the login that worked:
<?php
session_start();
include('../includes/connect-db.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
</head>
<body>
<div>Message would go here</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM users WHERE user_username = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
?>
<html>
<head>
</head>
<body>
<div>Login form would go here</div>
</body>
</html>
<?php } ?>
And here is the login im trying to get to work (some more info about it under the code):
<?php
//Start Session
session_start();
//Connect To DataBase
include($_SERVER['DOCUMENT_ROOT'].'includes/connect-db.php');
//Login
if (isset($_SESSION['logged_in'])) {
header('Location: http://localhost/logged-in.html');
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM admins WHERE admin_username = ? AND admin_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: http://localhost/techbite/logged-in.html');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
//Page Content
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
//Select Theme
include($_SERVER['DOCUMENT_ROOT'].'themes/theme-select.php');
}
?>
Keep in mind that database connection is successful, the login form appears but just dosnt seam to log in or show an error when nothing is entered/wrong credentials, everything else works perfect, including importing the form into the theme with $content.
Here is the connect-db.php:
<?php
//Connect To Database
try {
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
} catch (PDOException $e) {
exit('Database error, could not connect.');
}
?>
What iv done here is included the theme:
include($_SERVER['DOCUMENT_ROOT'].'/themes/theme-select.php');
And inside the theme where i want the content i have:
<?php echo($content); ?>
and in the login php file i have this which will be put into the php theme file:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
I hope someone can help, hopefully its something small i have missed!
Thanks for any help and let me know if anything else is needed.
Kind Regards,
Hayden.
it's not showing an error because
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
is all just a string, and the <?php ?> sections inside this string are never parsed by the php interpreter. View the page source of your login page and you should see them there.
If you're set on using this $content variable and the theme-select.php file, try changing it to this:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>';
if (isset($error)) {
$content .= '<small style="color:#aa0000">'.$error.'</small>';
}
As for why it's not logging in, it's a silly question, but have you created a table in your database named admins and a record there with a username and password set?
Try replacing
$num = $query->rowCount();
with
$num = count($query->fetchAll(PDO::FETCH_ASSOC));
UPDATE
Just noticed this...
if (isset($_POST['username'], $_POST['password'])) {
should be
if( isset($_POST['username']) && isset($_POST['password']) ) {
I would add an else condition here to display an error message of some description
UPDATE 2
Slight modification to your connect.php
try {
// create a new instance of a PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
I fixed it!
i knew it would be something so small and simple, it was the form action which was set to the wrong file name, it was set to index.php instead of login.php.
Thank you to everyone for your help! :)