Warning: Cannot modify header information - headers already sent by
(output started at/admin/index.php:21) in
/var/www/web143366/html/admin/index.php on line 24
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<?php
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
} else {
?>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
<?php
}
?>
</body>
</html>
Edit all: This is the error. When I remove line 24 I get the following error.
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/var/www/web143366/html/admin/login.php on line 32
Line 32: $result = $sql->get_result();
Code:
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
Login.php=
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<?php
if (isset($_POST['loginBtn'])) {
$email = htmlspecialchars($_POST['mail']);
$pass = htmlspecialchars($_POST['password']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
if (isset($_POST['forgotBtn'])) {
$code = randomChars(20);
$email = htmlspecialchars($_POST['mail']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>No user with that email</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['id'];
}
$sql = $conn->prepare('INSERT INTO resetpass (userID, code) VALUES (?, ?)');
$sql->bind_param('ss', $uid, $code);
$sql->execute();
$message = "Your reset link: " . "http://" .$_SERVER['SERVER_NAME'] . '/admin/login?r=' . $code;
$to = $email;
$title = "Reset Password";
if (sendEmail($to, $message, $title)) {
echo "Email with reset code has been sent";
} else {
echo "Error while sending email";
}
}
}
if (isset($_POST['resetBtn'])) {
$nPass = htmlspecialchars($_POST['nPass']);
$code = $_POST['code'];
$password = password_hash($nPass, PASSWORD_DEFAULT);
$sql = $conn->prepare('SELECT * FROM resetpass WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Error</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['userID'];
}
$sql = $conn->prepare('UPDATE resetpass SET used = "1" WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$sql = $conn->prepare('UPDATE admin SET password = ? WHERE id = ?');
$sql->bind_param('ss', $password, $uid);
$sql->execute();
echo "Password changed successfuly, you can now login";
}
}
?>
<?php
if (!isset($_SESSION['adminid'])) {
if (isset($_GET['forgot'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">Account Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<input type="submit" name="forgotBtn" value="Reset">
</form>
<?php } else if (isset($_GET['r'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">New Password:</div>
<input type="password" name="nPass" placeholder="New password" required>
<input type="hidden" name="code" value="<?php echo $_GET['r'] ?>" required>
<input type="submit" name="resetBtn" value="Reset">
</form>
<?php
} else { ?>
<h2 style="text-align: left;">Login to admin panel</h2>
<form action="" method="POST">
<div class="formularzowyNaglowek">Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<div class="formularzowyNaglowek">Password:</div>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" name="loginBtn" value="Login">
</form>
Forgot your password?
<?php
}
} else {
header('Location: /admin');
}
?>
</body>
</html>
The line header('Location: /admin/login'); will redirect to the login page when the user is not logged in.
The problem is, that the function header() doesnt work when there has been content outputted already (echo or html).
<?php
session_start(); // only if you havent called session_start in config.php or functions.php
require_once('../config.php');
require_once('../php/functions.php');
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
exit();
}
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
</body>
</html>
Related
I have tried to update data through edit page by deleting all of the existing data from the 'positions' table and then re-insert them. When I press the 'Save' button, the page redirects perfectly to index page, but when i view the profile I see that the 'positions' database is empty.
Plz help as I have been grinding on this problem for a week now.
Edit.php
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['first_name']) && isset($_POST['last_name'])
&& isset($_POST['email']) && isset($_POST['headline'])
&& isset($_POST['summary']) && isset($_POST['profile_id'])) {
// Data validation
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
if ( !isset($_POST['first_name']) || !isset($_POST['last_name'])
|| !isset($_POST['email']) || !isset($_POST['headline']) || !isset($_POST['summary'])) {
$_SESSION['failure'] = "All fields are required";
header("Location: edit.php?profile_id=". $_REQUEST["profile_id"]);
return;
}
}
else{
$_SESSION["failure"] = "Email address must have an # sign.";
header("Location: edit.php?profile_id=". $_REQUEST["profile_id"]);
return;
}
$sql = "UPDATE `profile` SET first_name = ?,
last_name = ?, email = ?,
headline = ?, summary=?
WHERE profile_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
$_POST['first_name'],
$_POST['last_name'],
$_POST['email'],
$_POST['headline'],
$_POST['summary'],
$_POST['profile_id']));
$profile_id = $_GET['profile_id'];
$stmt = $pdo->prepare("DELETE FROM `Position` WHERE `profile_id` = ?");
$stmt->execute(array($_GET['profile_id']));
$rank=1;
for($i=1; $i<=9; $i++) {
if ( ! isset($_POST['year'.$i]) ) continue;
if ( ! isset($_POST['desc'.$i]) ) continue;
$year = $_POST['year'.$i];
$desc = $_POST['desc'.$i];
$stmt = $pdo->prepare("INSERT INTO `position`
(`profile_id`, `rank`, `year`, `description`)
VALUES ( ?, ?, ?, ?)");
$stmt->execute(array($profile_id, $rank, $year, $desc));
$rank++;
}
$_SESSION["success"]="Record Added";
header("Location: index.php");
return;
}
$stmt = $pdo->prepare("SELECT `profile_id`, `first_name`, `last_name`, `email`, `headline`, `summary` FROM `profile` WHERE `profile_id` = ?");
$stmt->execute(array($_GET['profile_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Flash pattern
if ( isset($_SESSION['failure']) ) {
echo '<p style="color:red">'.$_SESSION['failure']."</p>\n";
unset($_SESSION['failure']);
}
$fname = htmlentities($row['first_name']);
$lname = htmlentities($row['last_name']);
$email = htmlentities($row['email']);
$headline = htmlentities($row['headline']);
$summary = htmlentities($row['summary']);
$profile_id = $row['profile_id'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rounak Simlai</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Editing profile for<?php echo" ".$_SESSION['name'];?></h1>
<form method="post">
<p>First Name:
<input type="text" name="first_name" value="<?php echo($fname); ?>" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" value="<?php echo($lname); ?>" size="40"/></p>
<p>Email:
<input type="text" name="email" value="<?php echo($email); ?>"/></p>
<p>Headline:<br>
<input type="text" name="headline" value="<?php echo($headline); ?>"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"> <?php echo($summary); ?> </textarea></p>
<input type="hidden" name="profile_id" value="<?php echo($profile_id); ?>">
<p>Position: <input type="submit" id="addPos" value="+">
<div id="position_fields">
<?php
$stmt = $pdo->prepare("SELECT * FROM `position` WHERE profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){
$year=$row['year'];
$desc=$row['description'];
$countPos = 1;
echo"<div id='position'".$countPos.">";
echo"<p> Year: <input type='text' name=\"year ".$countPos."\" value='".$year."' /> ";
echo"<input type=\"button\" value=\"-\" onclick=\"$(\'#position'+countPos+'\').remove();return false;\"></p> ";
echo"<textarea name=\"desc".$countPos."' rows=\"8\" cols=\"80\" >$desc</textarea>";
echo"</div>";
$countPos++;
}
?>
</div>
</p>
<p>
<input type="submit" id="submit" value="Save"/>
Cancel</p>
</form>
</div>
<script>
countPos = 1;
$(document).ready(function(){
window.console && console.log('Document ready called');
$('#addPos').click(function(event){
event.preventDefault();
if ( countPos >= 9 ) {
alert("Maximum of nine position entries exceeded");
return;
}
countPos++;
window.console && console.log("Adding position "+countPos);
$('#position_fields').append(
'<div id="position'+countPos+'"> \
<p>Year: <input type="text" name="year'+countPos+'" value="" /> \
<input type="button" value="-" \
onclick="$(\'#position'+countPos+'\').remove();return false;"></p> \
<textarea name="desc'+countPos+'" rows="8" cols="80"></textarea>\
</div>');
});
});
</script>
</body>
</html>
VIEW.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt= $pdo->prepare("SELECT * FROM profile WHERE profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$fname=htmlentities($row['first_name']);
$lname=htmlentities($row['last_name']);
$email=htmlentities($row['email']);
$headline=htmlentities($row['headline']);
$summary=htmlentities($row['summary']);
$profile_id=htmlentities($row['profile_id']);
?>
<!DOCTYPE html>
<html>
<head>
<title>Rounak Simlai</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Profile information</h1>
<form method="post">
<p>First Name: <?php echo(" ".$fname); ?></p>
<p>Last Name: <?php echo(" ".$lname); ?> </p>
<p>Email: <?php echo(" ".$email); ?> </p>
<p>Headline: <?php echo(" ".$headline); ?> <br/></p>
<p>Summary: <?php echo(" ".$summary); ?> <br/><p>
<input type="hidden" name="profile_id" value="<?= $profile_id ?>">
</p>
<p>Position</p><ul>
<?php
$stmt= $pdo->prepare("SELECT * FROM position WHERE profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){
echo"<li>".$row['year']." : ".$row['description']."</li>";
}
?>
</ul>
Done
</form>
</div>
</body>
</html>
ADD.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function validatePos() {
for($i=1; $i<=9; $i++) {
if ( ! isset($_POST['year'.$i]) ) continue;
if ( ! isset($_POST['desc'.$i]) ) continue;
$year = $_POST['year'.$i];
$desc = $_POST['desc'.$i];
if ( strlen($year) == 0 || strlen($desc) == 0 ) {
return "All fields are required";
}
if ( ! is_numeric($year) ) {
return "Position year must be numeric";
}
}
return true;
}
$failure=false;
$success=false;
if(isset($_POST['first_name'])&& isset($_POST['last_name'])
&& isset($_POST['email']) && isset($_POST['headline'])
&& isset($_POST['summary'])){
if(strlen($_POST['first_name'])<1 || strlen($_POST['last_name'])<1
||strlen($_POST['email'])<1 || strlen($_POST['headline'])<1
||strlen($_POST['summary'])<1){
$_SESSION['failure'] = "All values are required";
header("Location: add.php");
return;
}
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$_SESSION["failure"]="Email address must contain # sign.";
header("Location: add.php");
return;
}
$stmt = $pdo->prepare('INSERT INTO `profile`(`user_id`, first_name, last_name, email, headline, summary)
VALUES ( ?, ?, ?, ?, ?, ?)');
$stmt->execute(array($_SESSION['user_id'],
$_POST['first_name'],
$_POST['last_name'],
$_POST['email'],
$_POST['headline'],
$_POST['summary']));
$profile_id = $pdo->lastInsertId();
if($stmt==true){
$rank=1;
for($i=1; $i<=9; $i++) {
if ( ! isset($_POST['year'.$i]) ) continue;
if ( ! isset($_POST['desc'.$i]) ) continue;
$year = $_POST['year'.$i];
$desc = $_POST['desc'.$i];
$stmt = $pdo->prepare('INSERT INTO Position
(profile_id, `rank`, `year`, `description`)
VALUES ( ?, ?, ?, ?)');
$stmt->execute(array($profile_id, $rank, $year, $desc));
$rank++;
}
$_SESSION["success"]="Record Added";
header("Location: index.php");
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Rounak Simlai</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Adding profile for<?php echo" ".$_SESSION['name']; ?></h1>
<form method="post">
<?php
if ( isset($_SESSION["failure"]) ) {
echo('<p style="color: red;">'.htmlentities($_SESSION["failure"])."</p>\n");
unset($_SESSION["failure"]);
}
?>
<p>First Name:
<input type="text" name="first_name" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" size="40"/></p>
<p>Email:
<input type="text" name="email"/></p>
<p>Headline:<br>
<input type="text" name="headline"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"></textarea></p>
<p>
Position: <input type="submit" id="addPos" value="+">
<div id="position_fields">
</div>
</p>
<input type="submit" value="Add">
Cancel
</form>
</div>
<script>
countPos = 0;
$(document).ready(function(){
window.console && console.log('Document ready called');
$('#addPos').click(function(event){
event.preventDefault();
if ( countPos >= 9 ) {
alert("Maximum of nine position entries exceeded");
return;
}
countPos++;
window.console && console.log("Adding position "+countPos);
$('#position_fields').append(
'<div id="position'+countPos+'"> \
<p>Year: <input type="text" name="year'+countPos+'" value="" /> \
<input type="button" value="-" \
onclick="$(\'#position'+countPos+'\').remove();return false;"></p> \
<textarea name="desc'+countPos+'" rows="8" cols="80"></textarea>\
</div>');
});
});
</script>
</body>
</html>
INDEX.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<html>
<head>
<title>Rounak Simlai</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Rounak Simlai's Resume Registry</h1>
<?php
if (!isset($_COOKIE['data']))
{
echo '<p>Please log in</p>';
echo('<table border="1">'."\n");
$stmt= $pdo->prepare("SELECT profile_id, first_name, last_name, headline FROM `profile`");
$stmt->execute();
if($stmt->rowCount()==0){
echo "No Rows Found";
}
else{
echo"<thead><tr>
<th>Name</th>
<th>Headline</th>
</tr></thead>";
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
echo''.htmlentities($row['first_name']).' '.htmlentities($row['last_name']).'';
echo("</td><td>");
echo(htmlentities($row['headline']));
echo("</td><td>");
}
}
}
if (isset($_COOKIE['data'])){
$msg=false;
if(isset($_SESSION["success"])) {
echo('<p style="color: green;">'.htmlentities($_SESSION["success"])."</p>\n");
unset($_SESSION['success']);
}
echo('<table border="1">'."\n");
$stmt= $pdo->prepare("SELECT profile_id, first_name, last_name, headline FROM `profile`");
$stmt->execute();
if($stmt->rowCount()==0){
$msg="No Rows Found";
}
else{
echo"<thead><tr>
<th>Name</th>
<th>Headline</th>
<th>Action</th>
</tr></thead>";
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>";
echo''.htmlentities($row['first_name']).' '.htmlentities($row['last_name']).'';
echo("</td><td>");
echo(htmlentities($row['headline']));
echo("</td><td>");
echo('Edit / ');
echo('Delete');
echo("</td></tr>\n");
}
}
echo"<p>".htmlentities($msg)."</p>
<p>Add New Entry</p>
<p>Logout</p>
</div>";
}
?>
</body>
</html>
DELETE.PHP
<?php
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ( isset($_POST['delete']) && isset($_POST['profile_id']) ) {
$sql = "DELETE FROM `profile` WHERE profile_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($_POST['profile_id']));
$_SESSION['success'] = 'Record deleted';
header( 'Location: index.php' ) ;
return;
}
$stmt = $pdo->prepare("SELECT first_name, last_name, profile_id FROM `profile` where profile_id = ?");
$stmt->execute(array($_GET['profile_id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rounak Simlai</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Deleting profile</h1>
<form method="post">
<p>First Name: <?php echo($row['first_name']); ?> </p>
<p>Last Name: <?php echo($row['last_name']);?> </p>
<input type="hidden" name="profile_id" value="<?= $row['profile_id'] ?>">
<input type="submit" value="Delete" name="delete">
Cancel
</form>
</div>
</body>
</html>
LOGIN.PHP
<?php // Do not put any HTML above this line
session_start();
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=misc',
'rs', 'rs123');
// See the "errors" folder for details...
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$salt = 'XyZzy12*_';
$failure = false; // If we have no POST data
// Check to see if we have some POST data, if we do process it
if ( isset($_POST['email']) && isset($_POST['pass']) ) {
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
if ( strlen($_POST['email']) < 1 || strlen($_POST['pass']) < 1 ) {
$_SESSION["failure"] = "Email and password are required";
header("Location: login.php");
return;
} else {
$check = hash('md5', $salt.$_POST['pass']);
$stmt = $pdo->prepare('SELECT `user_id`, `name` FROM users WHERE email = ? AND pass = ?');
$stmt->execute(array($_POST['email'], $check));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( $row !== false ) {
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
setcookie('data','1999');
// Redirect the browser to index.php
header("Location: index.php");
return;
} else {
$_SESSION["failure"] = "Incorrect password";
error_log("Login fail ".$_POST['email']." $check");
header("Location: login.php");
return;
}
}
}
else{
$_SESSION["failure"] = "Email must have an # sign.";
header("Location: login.php");
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Rounak Simlai</title>
</head>
<body>
<?php require_once "bootstrap.php"; ?>
<div class="container">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION["failure"]) ) {
echo('<p style="color: red;">'.htmlentities($_SESSION["failure"])."</p>\n");
unset($_SESSION["failure"]);
}
?>
<form method="POST">
<label for="nam">User Name</label>
<input type="text" name="email" id="email"><br/>
<label for="id_1723">Password</label>
<input type="text" name="pass" id="id_1723"><br/>
<input type="submit" onclick="return doValidate();" value="Log In">
Cancel
</form>
<p><br>
For a password hint, view source and find a password hint
in the HTML comments.
<!-- Hint: The password is the three character name of the
programming language used in this class (all lower case)
followed by 123. -->
</p>
</div>
<script>
function doValidate() {
console.log('Validating...');
try {
addr = document.getElementById('email').value;
pw = document.getElementById('id_1723').value;
console.log("Validating addr="+addr+" pw="+pw);
if (addr == null || addr == "" || pw == null || pw == "") {
alert("Both fields must be filled out");
return false;
}
if ( addr.indexOf('#') == -1 ) {
alert("Invalid email address");
return false;
}
return true;
} catch(e) {
return false;
}
return false;
}</script>
</body>
</html>
LOGOUT.PHP
<?php
session_start();
setcookie('data');
unset($_SESSION['name']);
unset($_SESSION['user_id']);
header("Location: index.php");
?>
<?php
if (!isset($_SESSION['adminid'])) {
exit();
}
?>
Stops the page from loading when I delete it I can load the page. Anyone knows what the problem is? Yes I am very bad at coding.
Edit:
<?php
if (!isset($_SESSION['adminid'])) {
if (isset($_GET['forgot'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">Account Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<input type="submit" name="forgotBtn" value="Reset">
</form>
<?php } else if (isset($_GET['r'])) { ?>
Edit 2: All I can could find was:
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
exit();
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
} else {
Edit 3:
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<?php
if (isset($_POST['loginBtn'])) {
$email = htmlspecialchars($_POST['mail']);
$pass = htmlspecialchars($_POST['password']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
exit();
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
if (isset($_POST['forgotBtn'])) {
$code = randomChars(20);
$email = htmlspecialchars($_POST['mail']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>No user with that email</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['id'];
}
$sql = $conn->prepare('INSERT INTO resetpass (userID, code) VALUES (?, ?)');
$sql->bind_param('ss', $uid, $code);
$sql->execute();
$message = "Your reset link: " . "http://" .$_SERVER['SERVER_NAME'] . '/admin/login?r=' . $code;
$to = $email;
$title = "Reset Password";
if (sendEmail($to, $message, $title)) {
echo "Email with reset code has been sent";
} else {
echo "Error while sending email";
}
}
}
if (isset($_POST['resetBtn'])) {
$nPass = htmlspecialchars($_POST['nPass']);
$code = $_POST['code'];
$password = password_hash($nPass, PASSWORD_DEFAULT);
$sql = $conn->prepare('SELECT * FROM resetpass WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Error</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['userID'];
}
$sql = $conn->prepare('UPDATE resetpass SET used = "1" WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$sql = $conn->prepare('UPDATE admin SET password = ? WHERE id = ?');
$sql->bind_param('ss', $password, $uid);
$sql->execute();
echo "Password changed successfuly, you can now login";
}
}
?>
<?php
if (!isset($_SESSION['adminid'])) {
exit();
}
?>
<?php
if (!isset($_SESSION['adminid'])) {
if (isset($_GET['forgot'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">Account Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<input type="submit" name="forgotBtn" value="Reset">
</form>
<?php } else if (isset($_GET['r'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">New Password:</div>
<input type="password" name="nPass" placeholder="New password" required>
<input type="hidden" name="code" value="<?php echo $_GET['r'] ?>" required>
<input type="submit" name="resetBtn" value="Reset">
</form>
<?php
} else { ?>
<h2 style="text-align: left;">Login to admin panel</h2>
<form action="" method="POST">
<div class="formularzowyNaglowek">Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<div class="formularzowyNaglowek">Password:</div>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" name="loginBtn" value="Login">
</form>
Forgot your password?
<?php
}
} else {
}
?>
</body>
</html>
I am not sure what the problem is here. The user data is in my MySQL database, and correct. However when I try to login I get an error saying user/password is incorrect. I am trying to login using the users email address. In addition I want to add the first name, and user id to the session.
<?php
session_start();
include_once 'dbconnect_new.php';
if(isset($_SESSION['user'])!="")
{
header("Location: ../index.php");
}
if(isset($_POST['btn-login']))
{
$s_email = mysql_real_escape_string($_POST['email']);
$s_password = mysql_real_escape_string($_POST['password']);
$s_email = trim($s_email);
$s_password = trim($s_password);
$res=mysql_query("SELECT student_id, student_password, student_firstname FROM studentdata WHERE student_email='$s_email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if($count == 1 && $row['student_password']==md5($s_password))
{
$_SESSION['user'] = $row['student_id'];
header("Location: ../index.php");
}
else
{
?>
<script>
alert('Username / Password Seems Wrong !');
</script>
<?php
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Reg Page</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td>
<input type="text" name="email" placeholder="Your Email" required />
</td>
</tr>
<tr>
<td>
<input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td>
<button type="submit" name="btn-login">Sign In</button>
</td>
</tr>
<tr>
<td>Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>
Try this code:-
$s_email = mysql_real_escape_string($_POST['email']);
$s_password = mysql_real_escape_string($_POST['password']);
$s_email = trim($s_email);
$s_password = md5(trim($s_password));
$res=mysql_query("SELECT student_id, student_firstname FROM studentdata WHERE student_email='$s_email' AND student_password = '$s_password'");
if (!$res) {
// Debug query result by below code
//echo 'Could not run query: ' . mysql_error();
//exit;
echo '<script language="javascript">';
echo 'alert("Username / Password Seems Wrong !")';
echo '</script>';
}else{
$row = mysql_fetch_row($result);
$stu_id = $row[0];
$stu_fname = $row[1];
$_SESSION['user'] = $stu_id;
header("Location: ../index.php");
}
Hope this will help you :)
I have a form that comes from a link in a table that should just update one record in my database. When I changed some details in the table and pressed my submit button it changed all of my fields in the database and not just the one I wanted to change. Below is my form code and also the table that is being edited.
Edit user code
<?php
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit User</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="userID" value="<?php echo $userID; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $userID; ?></p>
<strong>Username: </strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>Password: </strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
<strong>Telephone: </strong> <input type="text" name="telephone" value="<?php echo $telephone; ?>"/><br/>
<strong>Address: </strong> <input type="text" name="address1" value="<?php echo $address1; ?>"/><br/>
<strong>Town: </strong> <input type="text" name="town" value="<?php echo $town; ?>"/><br/>
<strong>Postcode: </strong> <input type="text" name="postcode" value="<?php echo $postcode; ?>"/><br/>
<strong>Forename: </strong> <input type="text" name="forename" value="<?php echo $forename; ?>"/><br/>
<strong>Surname: </strong> <input type="text" name="surname" value="<?php echo $surname; ?>"/><br/>
<strong>Email: </strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<input type="submit" name="submit" value="Edit details">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include "config.php";
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['userID']))
{
// get form data, making sure it is valid
$userID = $_POST['userID'];
$username = $_POST['username'];
$password = $_POST['password'];
$telephone = $_POST['telephone'];
$address1 = $_POST['address1'];
$town = $_POST['town'];
$postcode = $_POST['postcode'];
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
// check that firstname/lastname fields are both filled in
if ($username == '' || $password == '' || $telephone == '' || $address1 == '' || $town == '' || $postcode == '' || $forename == '' || $surname == '' || $email == '' )
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, $error);
}
else
{
// save the data to the database
$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' ");
$query->execute();
// once saved, redirect back to the view page
header("Location: view_user.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['userID']) && is_numeric($_GET['userID']) && $_GET['userID'] > 0)
{
// query db
$userID = $_GET['userID'];
$query = $db->prepare("SELECT * FROM user WHERE userID=$userID");
$query->execute();
$dbRow = $query->fetch(PDO::FETCH_ASSOC);
// check that the 'id' matches up with a row in the databse
if($dbRow)
{
// get data from db
$username = $dbRow['username'];
$password = $dbRow['password'];
$telephone = $dbRow['telephone'];
$address1 = $dbRow['address1'];
$town = $dbRow['town'];
$postcode = $dbRow['postcode'];
$forename = $dbRow['forename'];
$surname = $dbRow['surname'];
$email = $dbRow['email'];
// show form
renderForm($userID, $username, $password, $telephone, $address1, $town, $postcode, $forename, $surname, $email, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
View user info code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Ballymena Sports</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="home2.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="home2_template.html">Ballymena Sports</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li>Administrator</li>
<li>Log out</li>
</ul>
</div>
</nav>
<!-- Main part of homepage -->
<div class="jumbotron">
<div class="container">
<h2>Users</h2>
<p>This table shows all registered users of Ballymena Sports:</p>
<div class="table-responsive">
<tbody>
<?php
include "config.php";
$query = $db->prepare("SELECT * FROM user ORDER BY userID asc");
$query->execute();
echo "<table id='user' class='table table-bordered'>
<tr>
<th>User ID</th>
<th>Username</th>
<th>Forename</th>
<th>Surname</th>
<th>Email</th>
<th>Address</th>
<th>Town</th>
<th>Postcode</th>
<th>Edit User</th>
<th>Delete User</th>
</tr>";
while ($dbRow = $query->fetch(PDO::FETCH_ASSOC)) {
$userID = $dbRow['userID'];
$username = $dbRow['username'];
$forename = $dbRow['forename'];
$surname = $dbRow['surname'];
$email = $dbRow['email'];
$address1 = $dbRow['address1'];
$town = $dbRow['town'];
$postcode = $dbRow['postcode'];
// code to display information
{ echo "<tr>
<td>$userID</td>
<td>$username</td>
<td>$forename</td>
<td>$surname</td>
<td>$email</td>
<td>$address1</td>
<td>$town</td>
<td>$postcode</td>
<td><a href='edit_user.php?userID=".$userID."'>Edit</a></td>
<td><a href='delete_user.php?userID=".$userID."'>Delete</a></td>
</tr>";}
} //while
?>
</tbody>
</div>
</table>
</div>
</div>
<?php
if(!$_SESSION['admin_username']){
header('location:admin_login.php');
$name = $_SESSION['admin_username'];
}
?>
<hr>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
<!-- Header and footer later to be used as include statements -->
</body>
</html>
Your problem is that your update statement doesn't specify a where clause:
$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' ");
You need to use the User ID to specify that you only want to update the row for this particular user:
$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' where userId=$userID");
You should also look into using prepared statements to guard your code from SQL injection attacks.
you need check query.missing where clause in update query.try it
$query = $db->prepare("UPDATE user SET username='$username', password='$password', telephone='$telephone', address1='$address1', town='$town', postcode='$postcode', forename='$forename', surname='$surname', email='$email' where userId=$userID");
I am writing simple blog in PHP/MySQL and I have a problem to insert some data into my database. I am trying to add comment always receive an error - Comment not added. I can't figure it out what is wrong with the code. Is anybody able to help?
<?php
if(!isset($_GET['id'])) {
header('Location: index.php');
exit();
} else {
$id = $_GET['id'];
}
if(!is_numeric($id)) {
header('Location: index.php');
}
// Include database connection
include('includes/db_connect.php');
$sql = "SELECT post_title, post_body FROM posts WHERE post_id='$id'";
$query = $db->query($sql);
//echo $query->num_rows;
if($query->num_rows != 1) {
header('Location: index.php');
exit();
}
if(isset($_POST['submit-comment'])) {
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$comment = $db->real_escape_string($comment);
$id = $db->real_escape_string($id);
if($email && $name && $comment) {
$sqlComment = "INSERT INTO comments (post_id, email, name, comment) VALUES ('$id','$email','$name','$comment')";
$queryComment = $db->query($sqlComment);
if($queryComment) {
echo "Comment was added";
} else {
echo "Comment not added";
}
} else {
echo "Error";
}
}
?>
<! DOCTYPE html >
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--><html class=""><!--<![endif]-->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog System</title>
<link rel="stylesheet" href="css/application.css" type="text/css">
<style type="text/css">
label {
display: block;
}
</style>
</head>
<body>
<div id="container">
<div id="post">
<?php
$row = $query->fetch_object();
echo "<h2>" . $row->post_title . "</h2>";
echo "<p>" . $row->post_body . "</p>";
?>
</div>
<hr>
<div id="add-comments">
<form action="<?php echo $_SERVER['PHP_SELF'] . '?id=' . $id ?>" method="post">
<label for="email">Email Address:</label>
<input type="text" name="email" id="email"><br>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea><br>
<br><br>
<input type="submit" name="submit-comment" value="Post your comment" id="postyourcomment">
</form>
</div>
</div>
<script type="text/javascript" src="js/application.min.js"></script>
</body>
</html>
<?php
if(isset($_POST['submit-comment'])) {
if(!isset($_GET['id'])) {
header('Location: index.php');
exit();
} else {
$id = $_GET['id'];
}
if(!is_numeric($id)) {
header('Location: index.php');
}
// Include database connection
include('db_connect.php');
$sql = "SELECT post_title, post_body FROM posts WHERE post_id=".$id." ";
$query = $db->query($sql);
//echo $query->num_rows;
if($query->num_rows != 1) {
header('Location: index.php');
exit();
}
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$comment = $db->real_escape_string($comment);
$id = $db->real_escape_string($id);
if($email && $name && $comment) {
$sqlComment = "INSERT INTO comments (post_id, email, name, comment) VALUES (".$id.",'".$email."','".$name."','".$comment."')";
$queryComment = $db->query($sqlComment);
if($queryComment) {
echo "Comment was added";
} else {
echo "Comment not added";
}
} else {
echo "Error";
}
}
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog System</title>
<link rel="stylesheet" href="file:///C|/Users/Jaydeep Jivani/Desktop/css/application.css" type="text/css">
<style type="text/css">
label {
display: block;
}
</style>
</head>
<body>
<div id="container">
<div id="post">
<?php
$row = $query->fetch_object();
echo "<h2>" . $row->post_title . "</h2>";
echo "<p>" . $row->post_body . "</p>";
?>
</div>
<hr>
<div id="add-comments">
<form action=<?=$_SERVER['PHP_SELF']?> method="get">
<input type="hidden" name="id" value=<?=$id?> />
<label for="email">Email Address:</label>
<input type="text" name="email" id="email"><br>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="comment">Comment</label>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea><br>
<br><br>
<input type="submit" name="submit-comment" value="Post your comment" id="postyourcomment">
</form>
</div>
</div>
<script type="text/javascript" src="file:///C|/Users/Jaydeep Jivani/Desktop/js/application.min.js"></script>
</body>
</html>
Thank you everyone for help. I found a problem which was related to my database, unfortunately I constructed table with comment_id and forgot to add AI attribute.
Thanks to #tadman I was able to rewrite my code and here is the final working result:
if(isset($_POST['submit-comment'])) {
$email = $_POST['email'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $db->real_escape_string($email);
$name = $db->real_escape_string($name);
$comment = $db->real_escape_string($comment);
$id = $db->real_escape_string($id);
if($email && $name && $comment) {
// Prepare statemnt
$sqlComment = "INSERT INTO comments (post_id, email, name, comment) VALUES (?, ?, ?, ?)";
$queryComment = $db->prepare($sqlComment);
$queryComment->bind_param('ssss', $id, $email, $name, $comment);
// Execute prepared statement
$queryComment->execute();
if($queryComment) {
echo "Comment was added.";
} else {
echo "There was a problem. Error: " . mysqli_error($db);
}
// Close statement
$queryComment->close();
} else {
echo "Error";
}