How To Edit Single Record From Database? - php

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.

Related

if statement to determine $_SESSION data

I have created a customer database in which 4-5 staff will have access to login to view, edit and delete records.
I need the html table that lists the customer records to show an 'Edit' and 'Delete' link only when the logged in userID ($_SESSION[userID]) matches the userID of who created the record. So, if a staff member created 3 out 5 records, they should only see an 'edit' and 'delete' hyperlink against these three records, and nothing on the other two.
I have managed to get to the point of the sessions working - however, being new to PHP I am not sure where exactly to put my IF statement to echo the 'Edit' and 'Delete' links - and completely lost in how to write it exactly. I have tried many attempts, but am tearing my hair out now! Any help will be hugely appreciated.
This is my session start file (authenticate.php):
<?php
session_start();
$_SESSION["staffID"] = "staffID";
?>
Staff login file (staff_login.php):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Staff login</title>
</head>
<body>
<?php
require("db.php");
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking if user existing in the database or not
$query = "SELECT * FROM `staff login` WHERE username='$username'
and password='$password'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION[staffID] = $rows["$staffID"];
// Redirect user to edit_contact.php - was index.php -
header("Location: edit_contact.php");
}
else
{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='staff_login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Staff login</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
And the php file to show the records in a table with the 'Edit' and 'Delete' hyperlinks:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit contact</title>
</head>
<body>
<h2>Tate Finance Customer contact details</h2>
<?php
//***edit_contact.php***///
// Developed by: []
// Contact: []
// Created: [November 2018]
// Last Modified: [26 November 2018]
/* Purpose: This file lists all contacts from the mycontacts database in a table for logged in users to add, edit or delete their contacts.*/
//include authenticate.php file on all secure pages
require('db.php');
include("authenticate.php");
?>
<!--Add welcome note to staff user-->
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p>Logout</p>
<h3>Add new customer</h3>
<?php
$con = mysqli_connect("localhost","root","xxxxxx","mycontacts");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// Show all contacts from database in a table list
$query = "SELECT * FROM contact ORDER BY conName ASC";
$rst = mysqli_query($con,$query);
if($rst)
{
if(mysqli_num_rows($rst)>0)
{
// Table design for contacts list
echo "<table border='1'><tr><td>Edit contact</td><td>Name</td><td>Address</td><td>Phone</td><td>Mobile</td><td>Email</td></tr>";
while ($row = mysqli_fetch_assoc($rst))
{
/* Present contacts details in table list according to id selected, with links to edit or delete according to contactID selected */
/* This is where I think my IF statement needs to go, but can't figure out how/what to write to make it work */
echo "<tr><td>Edit Delete</td><td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
echo "</table>";
}
}
else
{
echo "No results found";
}
}
?>
</body>
</html>
while ($row = mysqli_fetch_assoc($rst))
{
echo "<tr>";
if($_SESSION["staffID"] == $id_of_creator){
echo "<td>".
"Edit".
"<a href=delete_record.php?
id=".$row['contactID']."> Delete</a> ".
"</td>";
}else echo "<td></td>";
echo "<td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
<?php
while($row = mysqli_fetch_assoc($selectAllCustomer)){
$id = $row['customer_id'];
$name= $row['customer_id'];
$email= $row['customer_email'];
echo "<tr>";
if($_SESSION['staffID'] == $Admin_Id){
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
echo "<td>";
echo "<a href='editPage.php?edit='".$id."'>Edit</a>";
echo "</td><td>";
echo "<a href='deletePage.php?delete='".$id."'>Delete</a>";
echo "</td>";
}else{
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
}
echo "</tr>";
}
NB: the valiable $admin_Id, is a id of the creator
?>

PHP mysql Pdo search exact match using Email and date as input

hi i found a code on internet and edited a bit but i stuck on showing the correct result i want.. when i type the email address i get the correct result but if i have more than 1 entry i always get the last one is it possible to make it show the result based on the email and the date?
here is my code so far
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
$id = "";
$reservation_name = "";
$persons = "";
$date = "";
$time = "";
$email = "";
$status= "";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=multi_edit","root","");
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$email = $_POST['email'];
// mysql search query
$pdoQuery = "SELECT * FROM member WHERE email = :email";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your id to the query id
$pdoExec = $pdoResult->execute(array(":email"=>$email));
if($pdoExec)
{
// if id exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$id = $row['id'];
$reservation_name = $row['reservation_name'];
$persons = $row['persons'];
$date = $row['date'];
$time = $row['time'];
$status = $row['status'];
}
}
// if the id not exist
// show a message and clear inputs
else{
echo 'No Reservation Found On This Email';
}
}else{
echo 'ERROR Something Is Wrong Try Again';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="search.php" method="post">
<center>
Please Enter Your Email Address : <br><br><br><input type="text" name="email" value="<?php echo $email;?>"><br><br>
Reservation Name : <br><input type="text" readonly name="reservation_name" value="<?php echo $reservation_name;?>"><br><br>
Persons : <br><input type="text" readonly name="persons" value="<?php echo $persons;?>"><br><br>
Date Y-M-D : <br><input type="text" name="date" value="<?php echo $date;?>"><br><br>
Time : <br><input type="text" readonly name="time" value="<?php echo $time;?>"><br><br>
Status : <br><input type="text" readonly name="status" value="<?php echo $status;?>"><br><br>
<input type="submit" name="Find" value="Find Data">
</center>
</form>
</body>
</html>
I have work out what you need, it require email (like foobar#gmail.com) and date (like 2018-09-23) in the form input field, if you submit it return the Reservation Name.
Notice for simplicity reason I removed these 3 columns "persons", "time" and "status", but you can add it back, it doesn't change the logic because the finding/query don't need those fields for input
This is my code:
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
function sqlInitConn ($args) {
// Initialze connection.
$serverName = $args["serverName"];
$userName = $args["userName"];
$password = $args["password"];
$dbName = $args["dbName"];
$conn = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
// Those variables are for input to mysql.
$idIpt = "";
$reservation_nameIpt = "";
$emailIpt = "";
$dateIpt = "";
// Those variables are for output to front-end.
$idOpt = "";
$reservation_nameOpt = "";
$emailOpt = "";
$dateOpt = "";
if(isset($_POST['find']))
{
try {
// Connect to mysql.
$pdoConnect = sqlInitConn([
"serverName" => "localhost",
// Change it to your server name.
"userName" => "root",
"password" => "change_it_to__your_password_here_if_your_mysql_need_password",
"dbName" => "multi_edit",
]);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
$emailIpt = $_POST['email'];
$dateIpt = $_POST['date'];
$pdoQuery = "SELECT * FROM member WHERE email = :email AND date = :date";
// Mysql search query
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->bindValue(":email", $emailIpt);
$pdoResult->bindValue(":date", $dateIpt);
$pdoExec = $pdoResult->execute();
if($pdoExec) {
// If record exist, show data in inputs
if($pdoResult->rowCount() > 0) {
foreach($pdoResult as $row) {
$idOpt = $row['id'];
$reservation_nameOpt = $row['reservation_name'];
$emailOpt = $row['email'];
$dateOpt = $row['date'];
break;
// only get first occurrences (get first matching record) to prevent corrupted data
// , because same email might wrongly log twice in same day (= same date), like morning and afternoon.).
}
}
else {
echo 'No Reservation Found On This Email';
// If the id not exist, show a message and clear inputs
}
} else {
echo 'ERROR Something Is Wrong Try Again';
// If the id not exist, show a message and clear inputs
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="" method="post">
<center>
<div>
<p>Please Enter Your Email Address :</p>
<input type="text" name="email" value="<?php echo $emailOpt;?>">
</div>
<div>
<p>Reservation Name :</p>
<input type="text" readonly name="reservation_name" value="<?php echo $reservation_nameOpt;?>">
</div>
<div>
<p>Date Y-M-D :</p>
<input type="text" name="date" value="<?php echo $dateOpt;?>">
</div>
<div>
<input type="submit" name="find" value="Find Data">
</div>
</center>
</form>
</body>
</html>

Using Sessions (or otherwise) what can I do to make my page remember the variables when I go back to it?

On this page, volleyLogin.php, when the user hits it for the first time everything works well - they log in with their username and from there can go on to AddNew.php. When the user clicks 'Create' on AddNew.php, it goes back automatically to volleyLogin.php. The details of AddNew.php are saved to the mysql database, but on going back to volleyLogin.php we see :
http://screencast.com/t/esgXUJlMa
which is the line :
$sql = "SELECT * FROM user WHERE username = '$username'";
How can I fix this ?
Here's my code:
volleyLogin.php
<?php
require('dbConnect.php');
//if the session is already active, like we are coming back to this page from AddNew.php
if (session_status() == PHP_SESSION_ACTIVE) {
//session_start();
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
}
//if user is logging in
if(isset($_POST['username'])){
//helps stop sql injection
$username = mysqli_real_escape_string($con,$_POST['username']);
}
//select everything from user
$sql = "SELECT * FROM user WHERE username = '$username'";
//get the result of the above
$result = mysqli_query($con,$sql);
//get every other record in the same row
$row = mysqli_fetch_assoc($result);
//make the user_id record in that row a variable
$user_id = $row["user_id"];
$username = $row["username"];
echo "user id is " . $user_id . "<br>";
echo "user name is " . $username . "<br>";
session_start();
$_SESSION['user_id']= $user_id;
$_SESSION['username'] = $username;
$sql2 = "SELECT * FROM review WHERE user_id = '$user_id'";
$result2 = mysqli_query($con,$sql2);
//if username isn't in the db
if (mysqli_num_rows($result)==0) {
echo "Failed, sorry";
}
//if username is in the db
if (mysqli_num_rows($result) > 0) {
//if username has reviews in the db
while($rows = mysqli_fetch_assoc($result2)) {
$review_id=$rows['review_id'];
$_SESSION['review'] = $review_id;
echo "review id is " . $review_id . "<br>";
echo "<br>";
echo "Category: " . $rows['cat_name'] . "<br>";
echo "Name: " . $rows['name'] . "<br>";
echo "Phone: " . $rows['phone'] . "<br>";
//html stuff comes next
?>
<!-- show the + button, click for more details -->
<html>
<body>
<form action="showreview.php?id=<?=$review_id?>" method="post">
<input type="submit" value="+" name="show_review"><br>
</form>
<p></p>
</body>
</html>
<?php
}
?>
<html>
<body>
<form action="AddNew.php" method="post">
<input type="submit" value="Add New" name="username"><br>
</form>
</body>
</html>
<?php
}
$con->close();
?>
AddNew.php
<?php require('dbConnect.php');
//use the variables we created in volleyLogin.php
session_start();
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
echo "user name is " . $username . "<br>";
echo "user id is " . $user_id . "<br>";
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
//in the review table, create a new id, put in the cat_id it comes under, the user id...
$sql2 = "INSERT INTO review VALUES(NULL,'666','{$category}','$user_id', '{$name}','{$phonenumber}','{$address}', '{$comment}')";
if ($con->query($sql2) === TRUE) {
header('Location:volleyLogin.php');
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
}
}
$con->close();
?>
<!doctype html>
<html>
<body>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>
<h2>Visible to :</h2>
<input type="radio" name="allmycontacts" value="All my Contacts">All my Contacts
<input type="radio" name="selectwho" value="Select Who">Select Who
<input type="radio" name="public" value="Public">Public
<input type="radio" name="justme" value="Just me">Just me
<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
Exit
</form>
</body>
</html>
Thanks for any help.
Hm, strange.
In my volleyLogin.php I have :
session_start();
$_SESSION['user_id']= $user_id;
$_SESSION['username'] = $username;
I simply took session_start(); out of there and put it right at the very top, after my opening
<?php tag and now it works correctly.

Php form is not adding data to my database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this form which is meant to take in user input then once submit is pressed it stores the values in the database. For some reason upon pressing submit the user is redirected to the view page but the data is not inserted in the database.
Here is the Add Record Code:
<?php
/*
Allows the user to both create new records and edit existing records
*/
// connect to the database
include("connection.php");
// creates the new/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($memberID = '', $username = '', $password ='', $firstname ='', $lastname ='', $address ='', $email ='', $error = '')
{ ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
<?php if ($memberID != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1><?php if ($memberID != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solmemberID red; color:red'>" . $error
. "</div>";
} ?>
<form action= "" method="post">
<div>
<?php if ($memberID != '') { ?>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>" />
<p>MemberID: <?php echo $memberID; ?></p>
<?php } ?>
<strong>Username: *</strong> <input type="text" name="username" value="<?php echo $username; ?>"/><br/>
<strong>Password: *</strong> <input type="password" name="password" value="<?php echo $password; ?>"/><br/>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/><br/>
<strong>Address: *</strong> <input type="text" name="address" value="<?php echo $address; ?>"/><br/>
<strong>Email: *</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 }
/*
NEW RECORD
*/
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// get the form data
$username = htmlentities($_POST['username'], ENT_QUOTES);
$password = htmlentities($_POST['password'], ENT_QUOTES);
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
$address = htmlentities($_POST['address'], ENT_QUOTES);
$email = htmlentities($_POST['email'], ENT_QUOTES);
// check that firstname and lastname are both not empty
if ($username == '' || $password == '' || $firstname == '' || $lastname == '' || $address == '' || $email == '')
{
// if they are empty, show an error message and display the form
$error = 'ERROR: Please fill in all required fields!';
renderForm($username, $password, $firstname, $lastname, $address, $email, $error);
}
else
{
// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT into members (username, password, firstname, lastname, address, email) VALUES (?, ?, ?, ?, ?, ?)"))
{
$stmt->bind_param($username, $password, $firstname, $lastname, $address, $email, $error, $memberID);
$stmt->execute();
$stmt->close();
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
// redirec the user
header("Location: view.php");
}
}
// if the form hasn't been submitted yet, show the form
else
{
renderForm();
}
}
// close the mysqli connection
$mysqli->close();
?>
Here is the view page:
<!DOCTYDOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>View Records</h1>
<p><b>View All</b> | View Paginated</p>
<?php
// connect to the database
include('connection.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM members ORDER BY memberID"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>memberID
</th><th>username
</th><th>password
</th><th>firstname
</th><th>lastname
</th><th>address
</th><th>email";
while ($row = $result->fetch_object())
//print "<pre>"; print_r($row); exit;
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->memberID . "</td>";
echo "<td>" . $row->username . "</td>";
echo "<td>" . $row->password . "</td>";
echo "<td>" . $row->firstname . "</td>";
echo "<td>" . $row->lastname . "</td>";
echo "<td>" . $row->address . "</td>";
echo "<td>" . $row->email . "</td>";
echo "<td><a href='edit.php?memberID=" . $row->memberID . "'>Edit</a></td>";
echo "<td><a href='delete.php?memberID=" . $row->memberID . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
Add New Record
</body>
</html>
The first error is the bind_param called with incorrect arguments. See the documentation of mysqli_stmt_bind_param
An other error is the number of params to bind required (by the sql query you build with prepare() which differs from how many you bind with bind_param.
I also suggest you to replace the line $stmt->***; to add more error checkpoint
$res = $stmt->bind_param(/* correct your code according to the doc :) */);
if (!$res)
echo 'error when binding params : '.$stmt->error;
else
{
$res = $stmt->execute();
if (!$res)
echo 'error at stmt->execute() '.$stmt->error;
}
You need to tell the datatypes like so:
$stmt->bind_param("sssssssi", $username, $password, $firstname, $lastname, $address, $email, $error, $memberID);
that is assuming all are strings except the id which i assume is integer

profile page not working with session id

i am creating a profile page and a login page where i store the session id and then in the profile file i check if isset or not but the problem that i get is that the system always display an error message and i used print_r($_SESSION); the browser display :
Important data are missingArray ( [first_name] => [email] => )
how to fix this error?????
login.php
<?php
session_start();
error_reporting(E_ALL);
require_once('include/connect.php');
$message = "";
if(!empty($_POST['email']))
{
$email = $_POST['email'];
$pass = $_POST['pass'];
$email = strip_tags($email);
$pass = strip_tags($pass);
$email = mysql_real_escape_string($email);
$pass = mysql_real_escape_string($pass);
//$pass = md5($pass);
$sql=mysql_query( "SELECT user_id, email_address, first_name FROM user WHERE email_address='$email'AND password='$pass'LIMIT 1") or die("error in user table");
$login_check = mysql_num_rows($sql);
if($login_check > 0)
{
$row = mysql_fetch_array($sql);
$id = $row['user_id'];
$_SESSION['user_id'] = $id;
$firstname = $row['first_name'];
$_SESSION['first_name']= $firstname;
$email = $row['email_address'];
$_SESSION['email_address']= $email;
mysql_query("UPDATE user SET last_log_date=now() WHERE user_id='$id'");
header("Location: profile.php");
}//close if
else
{
$message = "incorrect Email or Password!!";
//exit();
}
}//close if
?>
<!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>RegisterPage</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel|Satisfy' rel='stylesheet' type='text/css' />
<link href="default.css" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<div id="loginborder">
<p style="color:#FF0000" align="left"><?php print("$message") ?></p>
<!--Login form where user submit his registered email and password-->
<form action="login.php" method="post">
email-address:<br />
<input type="text" name="email" placeholder="Email Adress" />
<br />
<br />
Password:<br />
<input type="password" name="pass" placeholder="Password" />
<br />
<br />
<input type="submit" name="login" value="Login" />
<strong> Register</strong>
</form>
</div>
profile.php
<?php
session_start();
require_once('include/connect.php');
if(isset($_GET['user_id']))
{
$id=$_GET['user_id'];
var_dump($id);
}
elseif(isset($_SESSION['user_id']))
{
$id= $_SESSION['user_id'];
}
else
{
print "Important data are missing";
print_r($_SESSION);
exit();
}
$sql = mysql_query("SELECT * FROM user WHERE user_id='$id'") or die(mysql_error());
$row = mysql_fetch_array($sql);
$firstname=$row['first_name'];
$lastname=$row['last_name'];
$birth_date=$row['birth_date'];
$registered_date=$row['registered_date'];
//***************for upload img*****************//
$check_pic="members/$id/image01.jpg";
$default_pic="members/0/image01.jpg";
if(file_exists($check_pic))
{
$user_pic="<img src=\"$check_pic\"width=\"100px\"/>";
}
else
{
$user_pic="<img src=\"$default_pic\">";
}
echo $id, $firstname, $birth_date;
?>
You need to changes several things
First : get first_name and email in your request
'SELECT user_id,email,first_name FROM user WHERE email_address='$email'AND password='$pass'LIMIT 1'
Second, remove while loop and do
$row = mysql_fetch_array($sql);
You are limiting to 1 result so no need to loop inside result
Change $id=$_SESSION['user_id']; to $_SESSION['user_id'] = $id;
Also, limit to 1 the result from profile and remove loop (user_id => UNIQUE => LIMIT 1)
all you need to do is just store a value in a session variable [$_SESSION['username']] after everything checks out then select the data from the mysql table using the value in the session
----------------------------------for example------------------------------------------------------
on login.php
if($login_check > 0)
{
$_SESSION['email']=$email;//storing variable in SESSION
header("Location: profile.php");
}
else
{
$message = "incorrect Email or Password!!";
die();// kill the script
}
on profile.php
<?php
session_start();// start session
require_once('include/connect.php'); //include connection file
$sql = mysql_query("SELECT * FROM user WHERE email='(mysql_real_escape_string($_SESSION['email']))'") or die(mysql_error());
$row = mysql_fetch_array($sql);
// then just echo all the data you need
?>

Categories