All fields in database updated at once using PHP - php

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");

Related

Creating a new user and trying to get the user_id for session id but getting first id PHP

I'm trying to fix my sign up in PHP, when I create a new user my user id instantly becomes the first one available, if I have 100 users and I create a new one the user id should be 101 which it is on the database but on my session it becomes 1, if I delete the first user and the only user available has the id of 2 it becomes 2. What is wrong in my code? Cant seem to debug it.
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$con = mysqli_connect("localhost", "root", "", "smarttime");
$query = mysqli_query($con,"INSERT INTO users (use_name, use_email, use_pass) values ('$username', '$email', '$pass')");
$test = mysqli_query($con,"SELECT * from users");
$row = mysqli_fetch_array($test);
if(empty($username) || empty($pass) || empty($email) || empty($pass2))
{
header("Location:signup.php");
}else{
if($row['use_email'] == $email){
header("Location:login.php");
}else{
$query;
session_start();
$_SESSION['user_id'] = $row['use_id'];
$_SESSION['nome'] = $row['use_name'];
header('Location:logged.php');
exit();
}
}
?>
html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SmartTime</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css\main.css" rel="stylesheet">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/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-expand-lg navbar-light bg-light">
<a class="navbar-brand" >SmartTime</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="index.php">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<span class="navbar-text">
<a href="/login.php" >Login</a> 
<a href="/signup.php" >Sign Up</a>
</span>
</div>
</nav>
<div class="container">
<div class="card card-container">
<!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> -->
<img id="profile-img" class="profile-img-card" src="images/Doge.png" />
<p id="profile-name" class="profile-name-card"></p>
<form action="validatesignup.php" method="post" class="form-signin">
<span id="reauth-email" class="reauth-email"></span>
<input type="text" id="inputEmail" class="form-control" name="username" placeholder="Username" required>
<input type="email" id="inputEmail" class="form-control" name="email" placeholder="Email address" required>
<input type="password" id="inputPassword" class="form-control" name="pass" placeholder="Password" required>
<input type="password" id="inputPassword" class="form-control" name="pass2" placeholder="Confirm Password" required>
<button class="btn btn-lg btn-primary btn-block btn-signin" type="submit">Login</button>
</form><!-- /form -->
<a href="login.php" class="forgot-password">
Already have an account? Sign in!
</a>
</div><!-- /card-container -->
</div><!-- /container -->
</body>
</html>
new code
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$con = mysqli_connect("localhost", "root", "", "smarttime");
// Insufficient input
if(empty($username) || empty($pass) || empty($email) || empty($pass2)) {
header("Location:signup.php?msg=please+fill+all");
} else {
$stmt_email_test = mysqli_prepare($con, 'SELECT use_email FROM users WHERE use_email=?');
$stmt_email_test->bind_param('s',$email); // 's' for one string
$stmt_email_test->execute();
$stmt_email_test->bind_result($email_test);
if($email_test != null) { // Email exists
header("Location:login.php");
} else if( $pass != $pass2 ) { // Check if password repetition is ok
header("Location:signup.php?msg=passwords+do+not+match");
} else { // Everything is fine, do insert and fill session
$stmt = mysqli_prepare($con, "INSERT INTO users (use_name, use_email, use_pass) values (?,?,?)");
var_dump($stmt->error);
$stmt->bind_param('sss', $username, $email, $pass); // 'sss' for 3 strings
$stmt->execute();
// Get the new user_id
$new_user_id = mysql_insert_id();
// Fill Session
$_SESSION['user_id'] = $new_user_id;
$_SESSION['name'] = $username;
header('Location:logged.php');
exit();
}
}
?>
I've made a prepared-statement version.
You should use prepared statements to prevent sql-injections have a look at mysqli_prepare
Furthermore, I highly recommend to NOT store the password as plain text. Php offers a easy and safe way to store passwords: password_hash and password_verify is all you will need :)
<?php
// Insufficient input
if (empty($_POST['username']) || empty($_POST['pass']) || empty($_POST['email']) || empty($_POST['pass2'])) {
header("Location:signup.php?msg=please+fill+all");
exit;
}
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = mysqli_connect("localhost", "root", "", "smarttime");
$stmt_email_test = $con->prepare('SELECT email FROM users WHERE email=?');
$stmt_email_test->bind_param('s', $email); // 's' for one string
$stmt_email_test->execute();
$stmt_email_test->bind_result($email_test);
$stmt_email_test->close();
if ($email_test !== null) { // Email exists
header("Location:login.php");
exit();
}
if ($pass !== $pass2) { // Check if password repetition is ok
header("Location:signup.php?msg=passwords+do+not+match");
exit();
}
// Everything is fine, do insert and fill session
$stmt = $con->prepare("INSERT INTO users (name, email, pass) values (?,?,?)");
$stmt->bind_param('sss', $username, $email, $pass); // 'sss' for 3 strings
$stmt->execute();
// Get the new user_id
$new_user_id = $stmt->insert_id;
$stmt->close();
// Fill Session
session_start();
$_SESSION['user_id'] = $new_user_id;
$_SESSION['name'] = $username;
header('Location:logged.php');
exit();
Use mysqli_insert_id to get last id and use in select query, like this :-
$query = mysqli_query($con,"INSERT INTO users (use_name, use_email, use_pass) values
('$username', '$email', '$pass')");
$id = mysqli_insert_id($con);
$res = mysqli_query($con,"SELECT * from users WHERE user_id={$id}");
if($row = mysqli_fetch_assoc($res)) {
$_SESSION['user_id'] = $row['user_id'];
}
$test = mysqli_query($con,"SELECT * from users");
In this line you have to pass the email or email & password to get the corresponding id
$test = mysqli_query($con,"SELECT * from users where use_email = ".$email);
It will work for you .. just add where condition to that query to retrieve particular user details.
Try adding this code in you first else condition-
$sql = "SELECT user_id FROM users WHERE email = '".$email."' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// store the user_id of the person newly registered to $_SESSION['user_id]
while($row = $result->fetch_assoc()) {
$_SESSION['user_id] = $row["user_id"];
}
header('Location:dashboard.php');
} else {
echo "No user found!";
}
Hope that helps!

Admin page won't show

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>

Inserting data into database not working

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";
}

PHP profile update page MySql Error

Can anyone see the error in this code as the code is only giving me back :
the name does not exist
It was all working fine now it does not.
If anyone can spot it please and correct me as I am still new to this.
<?php
// see if the form has been completed
include_once("php_includes/check_login_status.php");
include_once("php_includes/db_conx.php");
// Initialize any variables that the page might echo
$username = "";
$firstname = "";
$surname = "";
$gender = "Male";
$country = "";
$weight = "";
$height = "";
if(isset($_GET["u"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
}
$sql = "SELECT * FROM users WHERE username='$username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$username = $row ["username"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$weight = $row["weight"];
$height = $row["height"];
$email = $row["email"];
$gender = $row ["gender"];
}
if (isset($_POST['submit'])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$weight = $_POST['weight'];
$height = $_POST['height'];
$email = $_POST['email'];
$gender = $_POST['gender'];
mysql_connect ("host","****","*****"); mysql_select_db('db_k1003140');
// check if that user exist
$exists = mysql_query ("SELECT * FROM users WHERE firstname='" . $username . "'") or die ("query cant connect");
if (mysql_num_rows ($exists) != 0) {
// update the description in the database
mysql_query("UPDATE users SET firstname='$firstname', surname='$surname', weight='$weight', height='$height' WHERE username='$username'") or die ("update could not be applied");
echo "successful";
} else echo "the name does not exist";
}
?>
Here is the HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Profile Update: <?php echo $u; ?></title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/main.js"></script>
<script src="js/javascript.js"></script>
<script src="js/ajax.js"></script>
<style type="text/css">
#updateform{
margin-top:24px;
}
#updateform > div {
margin-top: 12px;
}
#updateform > input {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
</style>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<div id="usernamecss"> Username: <?php echo $username; ?></div>
<form action="update.php" method="POST" id="updateform">
<div>
<div>First Name: </div>
<input id="firstname" type="text" name="firstname" value="<?php echo $firstname?>" maxlength="16">
<div>Surname: </div>
<input id="surname" type="text" name="surname" value="<?php echo $surname?>" maxlength="16">
<div>Weight: </div>
<input id="weight" type="text" name="weight" value="<?php echo $weight?>" >
<div>Height: </div>
<input id="height" type="text" name="height" value="<?php echo $height?>" >
<p> <input type="submit" name="submit" id="submit" value="Update Description"></p>
Go to Profile
</div>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
Just a guess you comparing username field with firstname,
SELECT * FROM users WHERE firstname='" . $username . "'";
While it needs to be,
SELECT * FROM users WHERE username='" . $username . "'";
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

How To Edit Single Record From Database?

Code as of 20 January 2014
<?php
session_start();
// connect to the database
include('connect.php');
$message = $_GET['message'];
// check if the form has been submitted then process it
if (isset($_POST['submit']))
{
// Get data from table
//set the id manually for test purposes
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check for empty fields and display error message
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
$message = "Please enter data in all fields" ;
header("Location: edit.php?message=$message");
}
else
{
// save the data to the table
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
}
// redirecr and display message
$message = "Your changes have been saved";
header("Location: edit.php?message=$message");
exit;
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from the table
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
print $message;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/all.css" />
<link rel="stylesheet" href="styles/forms.css" />
<script type="text/javascript" src="javascript/jquery-1.7.1.min.js"></script>
<link href='//fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Voltaire' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Ubuntu:400,500' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
</head>
<div class="container">
<form action="" method="post" enctype="multipart/form-data" name="edit" id="editrecord">
<fieldset>
<legend><span class="headingreg">Edit Details</span></legend>
<div class="formreg">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<br style="clear:left;"/>
<label for="forename">Forename</label><div><input type="text" id="forename" name="forename" class="insetedit" value="<?php echo $forename; ?>"/><br/></div>
<label for="forename">Surname</label><div><input type="text" name="surname" class="insetedit" value="<?php echo $surname; ?>"/><br/></div>
<label for="forename">Username</label><div><input type="text" name="username" class="insetedit" value="<?php echo $username; ?>"/><br/></div>
<label for="forename">Password</label><div><input type="text" name="password" class="insetedit" value="<?php echo $password; ?>"/><br/></div>
<label for="forename">email</label><div><input type="text" name="email" class="insetedit" value="<?php echo $email; ?>"/><br/></div>
<input type="submit" name="submit" class="submit2" value="submit">
</div>
</fieldset>
</form>
<br style="clear:left;"/>
<br style="clear:left;"/>
</body>
</html>
INDENTS REMOVED
I am following a tutorial for editing and deleting stored records in a database.
http://www.falkencreative.com/forum/records/view.php
In the tutorial one page displays the records in a database and another is used to edit the records :
http://www.falkencreative.com/forum/records/edit.php?id=33004
The problem is all the records in the database are displayed. What changes do I need to make so that I can display and edit a record based on a specified id on a single page? e.g.
$id = "429";
Eventually I will use sessions but for testing purpose I want to set the id manually.
I tried putting the code in a single page but got numerous errors e.g. headers already sent.
Here's the edit.php page with my attempt to set the id manually.
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $forename, $surname, $username, $password, $email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</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="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<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>Username: *</strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>email: *</strong> <input type="text" name="password" value="<?php echo $password; ?>"/><br/>
<strong>password: *</strong> <input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.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['id']))
{
// get form data, making sure it is valid
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check that forename/surname fields are both filled in
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $forename, $surname, $username, $password, $email, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE login SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.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['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
// show form
renderForm($id, $forename, $surname, $username, $password, $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!';
}
}
?>
And the view.php page :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>
<?php
/*
VIEW.PHP
Displays all data from 'players' table
*/
// connect to the database
include('connect-db.php');
// get results from database
$result = mysql_query("SELECT * FROM login")
or die(mysql_error());
// display data in table
echo "<p><b>View All</b> | <a href='view-paginated.php?page=1'>View Paginated</a></p>";
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Forename</th> <th>Surname</th> <th>Username</th> <th>eMail</th> <th>Password</th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['forename'] . '</td>';
echo '<td>' . $row['surname'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['password'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
REMOVED FUNCTION AND ERROR VARIABLE
<?php
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data
$id = "429";
$forename = mysql_real_escape_string(htmlspecialchars($_POST['forename']));
$surname = mysql_real_escape_string(htmlspecialchars($_POST['surname']));
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$password = mysql_real_escape_string(htmlspecialchars($_POST['password']));
// check empty fields
if ($forename == '' || $surname == '' || $username == '' || $password == '' || $email == '')
{
// generate error message
echo 'ERROR: Please fill in all required fields!';
}
else
{
// save the data to the database
mysql_query("UPDATE registration SET forename='$forename', surname='$surname', username='$username', email='$email', password='$password' WHERE id='$id'")
or die(mysql_error());
// Redirect
echo "Your changes have been saved";
header("Location: edit.php");
}
}
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM registration WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$forename = $row['forename'];
$surname = $row['surname'];
$username = $row['username'];
$email = $row['email'];
$password = $row['password'];
//dummy echo
echo 'formatting is messed up';
}
?>
You will just need to replace the $_GET['id'] with the code that provides the id.
If you are using sessions for example, replace $_GET['id'] with $_SESSION['id']
In your code from the file edit.php:
// 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['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
Change to:
$id=429;// this line could have been $id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM login WHERE id=$id LIMIT 1")
or die(mysql_error());
$row = mysql_fetch_array($result);
Of course, in order to get to the point of executing that code, you would need to remove the conditional statements, since you are no longer getting the information from the $_GET.
I also added a LIMIT 1 to the query, so that you only return one record; you probably would anyway, but if id didn't have a unique index (such as a primary key), it may return multiple records.
Also, in this example, you could nearly replace all of the deprecated mysql_ references with mysqli_. It won't protect you the way mysqli can with prepared statements, but it still should work.
Finally, the renderForm function is a poorly formed function. You can only have one <html> declaration per page, and if you called the function more than once, it would have multiple declarations.

Categories