Showing error message on correct page in PHP - php

I have 4 forms in my PHP Project. Index.php will store the user's name and id number then they may click next and it will take them to Form2.php. Form2.php will store some random answers of theirs, Form3.php will do the same as Form2 and Form4.php will store a few details then the user can click submit and the record should save in my DB. The issue I am having is that my ID number field is a unique field, and I want an error to show on Index.php when the user clicks Next if the ID input is the same as one in the DB. Currently, it is showing after the submit button is clicked in the last Form. Is there any way to do this?
Index.php
<body>
<center>
<div class="div2">
<h1>Welcome</h1>
<form action="form2.php" method="post">
<p>
<label for="firstName">Named:</label>
<input size="30" class="rounded-input" type="text" name="name" id="name" autocomplete="off" required>
</p>
<p>
<label for="lastName">S ID:</label>
<input size="30" class="rounded-input" type="text" name="Sid" id="Sid" autocomplete="off" required>
</p>
<input class="btn" type="submit" value="Next" style="float: right;">
</form>
</div>
</center>
</body>
Form2.php:
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['Sid'] = $_POST['Sid'];
?>
<div class="div2">
<h1>How disappointed would you be if this product ceased to exist?</h1>
<form action="form3.php" method="post">
<input type="radio" style="height:20px; width:20px;" required
name="product_exist_satisfaction"
<?php if (isset($product_exist_satisfaction) && $product_exist_satisfaction == "Very disappointed") echo "checked"; ?>
value="Very disappointed">
<label style="font-size: 20px;"> Very disappointed</label><br />
<input type="radio" style="height:20px; width:20px;" required
name="product_exist_satisfaction"
<?php if (isset($product_exist_satisfaction) && $product_exist_satisfaction == "Mildly disappointed") echo "checked"; ?>
value="Mildly disappointed">
<label style="font-size: 20px;"> Mildly disappointed</label><br />
<input type="radio" style="height:20px; width:20px;" required
name="product_exist_satisfaction"
<?php if (isset($product_exist_satisfaction) && $product_exist_satisfaction == "Not at all") echo "checked"; ?>
value="Not at all">
<label style="font-size: 20px;"> Not at all</label><br />
<input type="button" onclick="history.back()"
value="Previous" style="float: left;">
<input type="submit" value="Next" style="float: right;">
</form>
</div>
Insert.php
<?php
session_start();
?>
<body>
<div class="div2">
<?php
$conn = mysqli_connect("localhost", "root", "", "survey");
if ($conn === false) {
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$stmt = $conn->prepare('insert into `cus_survey`
( `fullname`, `Sid`, `product_exist_satisfaction`,
`system_battery_runout`, `rank_appliances` )
values (?, ?, ?, ?, ?)');
$stmt->bind_param('sssss', $_SESSION['fullname'], $_SESSION['Sid'],
$_SESSION['product_exist_satisfaction'],
$_SESSION['system_battery_runout'],
$_POST['rank_sequence']);
$stmt->execute();
$msg = ($stmt->affected_rows == 1)
? 'Your survey was captured successfully. Thank You!'!'
: 'Sorry, your S ID is used already, Please use another and resubmit.' . "<h3><a href='/index.php'>Click here to edit your S ID</a></h3>" . mysqli_connect_error();
$stmt->close();
$conn->close();
printf('<h3>%s</h3>', $msg);
?>
</div>
</body>

I have not checked the code, but the basic steps are:
-In your index.php, you could post the index to self, by changing to action="<?php echo $_SERVER['PHP_SELF']; ?>"
-You would then run a select query for the Sid
-If Sid is not already in sql table, then you would redirect to form2.php
-else you have Sid already, then set the error message and then display of the index form with the error message.
<?php
// Start/resume sessions
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
//set your error message to empty string
$error_message = "";
// ensure that you actually have values to check
if ((isset($_POST['name'])) &&(isset($_POST['Sid']))) {
// use select statement to verify that the Sid is not already in table
$sql_check = 'SELECT Sid FROM cus_survey...
//...
//... put your check on the result of select statement
if (Sid not already there) {
// redirect to form 2
header("Location: form2.php");
}else{
// If Sid already used found, populate the error message, which will get displayed in your body
$error_message = "Sorry, your S ID is used already, Please use another and submit.";
}
}
?>
<body>
<center>
<div class="div2">
<?php if ($error_message != ""){
?>
<h1>Oops: <?php echo "{$error_message}"; ?></h1>
<?php
}else{
?>
<h1>Welcome</h1>
<?php
};
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<label for="firstName">Named:</label>
<input size="30" class="rounded-input" type="text" name="name" id="name" autocomplete="off" required>
</p>
<p>
<label for="lastName">S ID:</label>
<input size="30" class="rounded-input" type="text" name="Sid" id="Sid" autocomplete="off" required>
</p>
<input class="btn" type="submit" value="Next" style="float: right;">
</form>
</div>
</center>
</body>

Related

can't see edited info in user info panel

I made a page for user info containing a button for updating their info. When I change the fields and push the button, the info changed in the database and the web page shows everything is ok and changed, but when I refresh the page (after pushing the button), there the fields aren't changed and contain still the same info (but changed in data base). So how can I solve this?
Here is html codes:
<div class="custom-container">
<div class="row">
<div class="col-10">
<div class="user_content custom-container">
<div class="row">
<div class="col-11 fields">
<form method="post" action="user_updates.php">
<fieldset id="right">
<label>نام کاربری</label>
<br>
<input type="text" name="username" value="<?php echo $_SESSION["member_username"] ?>" disabled style="direction: ltr;">
<br><br>
<label>رمز عبور</label>
<br>
<input type="text" name="password" value="<?php echo $_SESSION["member_password"] ?>" style="direction: ltr;">
<br><br>
<label>نام</label>
<br>
<input type="text" name="first-name" value="<?php echo $_SESSION["member_name"] ?>">
<br><br>
<label>نام خانوادگی</label>
<br>
<input type="text" name="last-name" value="<?php echo $_SESSION["member_last_name"] ?>">
</fieldset>
<fieldset id="left">
<label>نام پدر</label>
<br>
<input type="text" name="father-name" value="<?php echo $_SESSION["member_father_name"] ?>">
<br><br>
<label>کد ملی</label>
<br>
<input type="text" name="melli-code" value="<?php echo $_SESSION["member_melli_code"] ?>" style="direction: ltr; font-family: Iran_Sans_M;">
<br><br>
<label>شماره موبایل</label>
<br>
<input type="text" name="mobile-number" value="<?php echo $_SESSION["member_mobile_number"] ?>" style="direction: ltr; font-family: Iran_Sans_M;">
<br><br>
<label>ایمیل</label>
<br>
<input type="email" name="email" value="<?php echo $_SESSION["member_email"] ?>" style="direction: ltr;">
</fieldset>
<input type="hidden" name="user-id" value="<?php echo $_SESSION["member_id"] ?>">
<input type="submit" name="change" value="ثبت تغییرات">
</form>
<?php
if (isset($_GET["empty"]))
{
echo '<div class="php_texts"> <p>لطفاً تمامی قسمت ها رو پر نمایید.</p> </div>';
}
if (isset($_GET["changes"]))
{
echo '<div class="php_texts"> <p>اطلاعات با موفقیت ویرایش شد.</p> </div>';
}
if (isset($_GET["error"]))
{
echo '<div class="php_texts"> <p>عدم ارتباط با سرور.</p> </div>';
}
?>
</div>
</div>
</div> <!-- User Content-->
</div> <!-- User Content-->
and here is php codes:
<!-- General Codes-->
include("connect_to_sql.php");
session_start();
if(isset($_POST["change"]))
{
$password = $_POST["password"];
$first_name = $_POST["first-name"];
$last_name = $_POST["last-name"];
$father_name = $_POST["father-name"];
$melli_code = $_POST["melli-code"];
$mobile_number = $_POST["mobile-number"];
$email = $_POST["email"];
$id = $_POST["user-id"];
if (empty($username) && empty($password) && empty($first_name) && empty($last_name) && empty($father_name) && empty($melli_code) && empty($mobile_number) && empty($email))
{
header("location:user_changes.php?empty=fill+all+fields");
exit;
}
if (isset($_SESSION["member_username"]))
{
$member_update= "UPDATE `member_info` SET `password` = '".$password."', `first_name` = '".$first_name."', `last_name` = '".$last_name."', `father_name` = '".$father_name."', `melli_code` = '".$melli_code."', `mobile_number` = '".$mobile_number."', `email` = '".$email."' WHERE `member_info`.`id` = '".$id."';";
$member_query = mysqli_query($connect_to_mysql,$member_update);
#$member_fetch = mysqli_fetch_assoc($member_query);
if($member_query)
{
header("location:user_changes.php?changes=ok");
exit;
}
else
{
header("location:user_changes.php?error=data+base");
exit;
}
}
}
The main problem is that you read the information for the user from the session, but never write the updated data into the session.
So either rewrite the values to the session in the if($member_query) block or fetch and map the actual values from the database on each page load to the session.
Another huge issue of your code is that it's vulnerable for SQL Injection attacks.

php session dropped after form submit

Seems, that I can't add password protection to the script: it should allow to login with the pass and to submit data from the form to mysql. Login looks fine, but if I try to press submit, it returns me to login page. Seems, that session is dropped or overwritten, but is not clear, how:
//login area
<?php
$password = "test";
session_start();
$_SESSION['txtPassword']= $_POST['txtPassword'] ;
if ( $_SESSION['txtPassword']!=$password ) {
?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><label for="txtPassword">Password:</label>
<br /><input type="text" title="Enter your password" name="txtPassword" /></p>
<p><input type="submit" name="Submit" value="Login" /></p>
</form>
<?
}
elseif ( $_SESSION['txtPassword']=$password ) {
echo $_SESSION['txtPassword'] ; // tried to print password, result is correct: test
//my db connection, just in case:
include "config.php";
$connect = mysqli_connect(HOST, USER, PASSWORD, NAME);
// data which should be inserted to db
if
(#$_POST['posted']=='1' $_POST['posted'])) {
$sSQL = "UPDATE users SET user_login='".mysqli_real_escape_string($connect, $_POST['usern'])."',user_pass='".mysqli_real_escape_string($connect, dohashpw($_POST['passw']))."' WHERE ID=1";
mysqli_query($connect, $sSQL) or print(mysql_error());
print ' <div class="container"> <p class="pstype">Password updated! </p>';
...
//input form
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"><input type="hidden" name="posted" value="1" />
<div class="col-xs-3">
<label for="ex2">New Username: </label>
<input type="text" class="form-control input-lg" name="usern" >
</div>
<div class="col-xs-3">
<label for="ex2">New Password: </label>
<input type="password" class="form-control input-lg" name="passw" >
</div>
<div class="col-xs-3">
<input type="submit" value="Submit" onclick="<? mysqli_query ($connect, $sSQL);?>; ">
</div>
</form>
I am able to login this page, but when I fill the form and click Submit, I get login area again. If echo $_SESSION show a correct result, I think that it was established, but data are lost after for submit. Could you please help to find my error?
You are assigning and not comparing here :
elseif ( $_SESSION['txtPassword']=$password ) {
this is better
elseif ( $_SESSION['txtPassword']==$password ) {
but thats a bad idea anyway, passwords should not be stored in session variables like this, and you have to hash them once the user submit them and only manipulate and store the hashed passwords in your code and database
<?php
$password = "test";
session_start();
$_SESSION['txtPassword']= $_POST['txtPassword'] ;
if($_SESSION['txtPassword']!=$password ){
?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ? >">
<p><label for="txtPassword">Password:</label></p>
</br>
<p><input type="text" title="Enter your password" name="txtPassword"/> </p>
<p><input type="submit" name="Submit" value="Login"/></p>
</form>
<?php
}
else{
echo $_SESSION['txtPassword'];
}
?>
i am not understanding why the elseif stands for? you are already checking inside the if condition which both are not equal?.

Stuck at one simple PHP UPDATE table, UPDATE just do nothing

This code is just refreshing my page. I cant see any errors. Maybe someone else can see the error here in code? I have the same code in two other pages and they do UPDATE.
The code below is in one page:
<body>
<?php
$query=mysqli_connect("localhost","user","","mydb") or die ("Ne moga da se svyrja s bazata danni.");
if(isset($_GET['id']))
{
$id=$_GET['id'];
if(isset($_POST['submit']))
{
$datetime=$_POST['datetime'];
$vlekach_teltur=$_POST['vlekach_teltur'];
$driver1=$_POST['driver1'];
$telnomer=$_POST['telnomer'];
$belejka=$_POST['belejka'];
$user=$_POST['user'];
mysqli_set_charset($query,"utf8");
$sql="update teltur set datetime = '$datetime', vlekach_teltur = '$vlekach_teltur', driver1 = '$driver1', telnomer = '$telnomer', belejka = '$belejka', user = '$user' where id='$id'";
$query3 = mysqli_query($query, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR);
if(mysqli_query($query3, $sql)){
echo "
<!DOCTYPE html>
<script>
function redir()
{
alert('Успешен запис!');
window.location.assign('index.php');
}
</script>
<body onload='redir();'></body>";
}
else{
echo "Не успешен запис, свържете се с администратора $query3. " . mysqli_error($query);
}
}
mysqli_set_charset($query,"utf8");
$sql2="select * from teltur where id='$id'";
$query1=mysqli_query($query, $sql2);
$query2=mysqli_fetch_array($query1);
?>
<h3 style="text-align:center;">Редакция на телефони Турция</h3>
<form id="docContainer" class="fb-toplabel fb-100-item-column selected- object" enctype="multipart/form-data" method="post" action="">
<div id="section1" class="section">
<div id="column1" class="column ui-sortable">
<div class="fb-grouplabel">
<p>Дата<input type="text" id="datetime" name="datetime" value="<?php echo $query2['datetime']; ?>"/>
<label id="datecheckalert" style="color: red; font-style: italic;"> </label></p>
</div>
<p>Влекач:
<input type="text" name="typeahead" class="typeahead tt-query" autocomplete="on" spellcheck="false" value="<?php echo $query2['vlekach_teltur']; ?>">
</p>
<div id="scrollable-dropdown-menu">
<p>Шофьор:
<input type="text" name="driver1" class="driver1 tt-query" autocomplete="on" spellcheck="false" value="<?php echo $query2['driver1']; ?>">
</p>
</div>
<div id="scrollable-dropdown-menu">
<p>Телефонен номер:
<input type="text" name="telnomer" class="telnomer tt-query" autocomplete="on" spellcheck="false" value="<?php echo $query2['telnomer']; ?>"/>
</p>
</div>
<p>Забележка:
<input type="text" name="belejka" value="<?php echo $query2['belejka']; ?>"/>
</p>
<p>Потребител:
<select id="user" name="user">
<option value="<?php echo $query2['user']; ?>"><?php echo $query2['user']; ?></option>
</select></p>
<p align="center">
<input type="submit" value="ЗАПИС" />
</p>
</div>
</div>
<?php
}
?>
</form>
</body>
I have error reporting as you see but no errors found.
Yeah im so stupid, i missed to name the Submit button.
<input type="submit" value="ЗАПИС" />
Changed to this code: <input type="submit" name="submit" value="ЗАПИС" />
I spend tree hours and after make a post here i found it by my self.
Can some one just delete this thread?

Post data for comment is not being transferred to query

I have a update query that I want to use and it's not working. All data is being posted except for CommentID and I can't understand why.
This is my query's output:
UPDATE comments SET
title='PHP',universitet='Högskolan',
kurs='Objekt orienterad programmering i PHP',
kurskod='HIG480-34', betyg='8', message='kom igen nu PHP'
WHERE CommentID = ''
As you can see WHERE CommentID = '' is empty.
<?php
require_once 'DBConnection/connection.php';
class EditPost{
public $comment;
public $id;
public function __construct() {
$this->comment = comment;
$this->id = mysql_real_escape_string($_GET['CommentID']);
}
public function EditThePost(){
if(!isset($_POST['editComment'])){
$query = "SELECT * FROM comments WHERE CommentID = '$this->id'";
$result = mysql_query($query);
$this->comment = mysql_fetch_array($result);
}elseif(isset($_POST['CommentID'])){
$updateQuery = "UPDATE comments SET title='$_POST[title]',universitet='$_POST[universitet]',kurs='$_POST[kurs]',kurskod='$_POST[kurskod]',betyg='$_POST[betyg]',message='$_POST[TheComment]' WHERE CommentID = '$_POST['CommentID]'";
mysql_query($updateQuery) or die(mysql_error());
echo $updateQuery;
header("Location: loggedin.php");
exit();
}
}
}
Here is the edit page with HTML:
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
require_once 'DBConnection/connection.php';
require_once 'Posting/editPost.php';
$edit = new EditPost();
$edit->EditThePost();
?>
<!DOCTYPE html>
<html lang="sv">
<?php include('incl/header.php'); ?>
<body>
<!--The Navbar-->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container" align="center">
Hem ||
<?php include('incl/logoutUser.php'); ?>
</div>
</div>
<!--The page container-->
<div id="container" >
<img src="logo.png" id="logoType" align="center">
<br>
<br>
<span class="label label-warning">Redigera inlägg:</span>
<div class="container" align="left">
<br>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p><span class="label label-info">Titel: </span> <br><input type="text" require name="title" placeholder="Ange titel.." value="<?php echo $edit->comment['title'] ;?>"</p>
<p><span class="label label-info">Högskola: </span> <br><input type="text" require name="universitet" placeholder="Ange högskola.." value="<?php echo $edit->comment['universitet']?>"></p>
<p><span class="label label-info">Kurs: </span> <br><input type="text" require name="kurs" placeholder="Ange kurs.." value="<?php echo $edit->comment['kurs']; ?>"></p>
<p><span class="label label-info">Kurskod: </span> <br><input type="text" require name="kurskod" placeholder="Ange kurskod.." value="<?php echo $edit->comment['kurskod']; ?>"></p>
<p><span class="label label-info">Betyg: </span> <br><input type="text" require name="betyg" placeholder="Betyg mellan 1-10" value="<?php echo $edit->comment['betyg']; ?>"></p>
<p><span class="label label-info">Meddelande: </span></p>
<textarea rows="10" cols="80" require name="TheComment" placeholder="Skriv ditt meddelande.." ><?php echo $edit->comment['message'];?></textarea>
<br><br>
<input type="hidden" name="CommentID" value="<?php echo $_POST['CommentID'];?>"/>
<p><input type="submit" class="btn btn-primary" name="editComment" value="Redigera inlägg"></p>
<br>
</form>
<br />
</div>
</div>
<?php include('incl/footer.php'); ?>
</div>
</body>
</html>
I will answer your question while ignoring the security issues, mostly because I don't have much time right now.
You have one issue in your constructor, where you're assigning the contents of a $_GET['CommentID'] to one variable a the $_POST['CommentID']. This is a really bad idea, you should use either $_GET['CommentID'] or $_POST['CommentID'], using both is asking for trouble.
The reason why your comment ID isn't posting is because it's not in your HTML form. From your link, you are doing
<input type="hidden" name="id" value="<?php echo $_GET['CommentID'];?>"/>
To do what you want, it should read
<input type="hidden" name="CommentID" value="<?php echo $_POST['CommentID'];?>"/>
Change the name attribute of this input to be CommentID, read the contents of $_POST['CommentID'], and your code should work.

how to update a qunatity if itemname is same in mysql using php

when i got a item from company then i enter a all item detail in my PHP form and its save in MySQL
and there are two table in MySQL
one is receive and 2nd is stock
so when i got a item its save in two table receive and stock
but some time stock (table) item is same so i want to update if item name and company is same then it will change quantity only
and some time its new item then it will save normally
so how can i do this please help me to fix this issue
thanks
mysql_query("INSERT INTO receive SET date='$date',company='$company',itemname='$itemname',quantity='$quantity',category='$category',signature='$signature'");
$result = mysql_query("INSERT INTO stock SET date='$date',company='$company',itemname='$itemname',quantity='$quantity',category='$category',signature='$signature'")
this is my complete script
// creates the new 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 ,$date ,$company,$itemname,$quantity,$category,$signature, $error)
{
?>
<form id="searchform" action="" method="post" enctype="multipart/form-data">
<div align="center">
<fieldset>
<div align="center">
<legend align="center" >Stock Receive!</legend>
</div>
<div class="fieldset">
<p>
<label class="field" for="date">Date: </label>
<input name="date" type="text" class="tcal" value="<?php echo date("Y-m-d");; ?>" size="30"/>
</p>
<p>
<label class="field" >Company :</label>
<input name="company" type="text" id="company" value="<?php echo $company; ?>" size="30"/>
</p>
<p>
<label class="field" for="item">Item: </label>
<input name="itemname" type="text" id="itemname" value="<?php echo $itemname; ?>" size="30"/>
</p>
<p>
<label class="field" >Quantity :</label>
<input name="quantity" type="text" id="quantity" value="<?php echo $quantity; ?>" size="30"/>
</p>
<p>
<label class="field" >Category :</label>
<input name="category" type="text" id="category" value="<?php echo $category; ?>" size="30"/>
</p>
<p>
<label class="field" for="username">Signature : </label>
<input name="signature" type="text" id="signature" readonly value="<?php echo $_SESSION['SESS_FIRST_NAME']; ?>">
</p>
</div>
</fieldset>
<p align="center" class="required style3">Please Fill The Complete Form </p>
<div align="center">
<input name="submit" type="submit" class="style1" value="Submit">
</div>
</form>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<?php
}
$itemname = $_GET['itemname'];
// connect to the database
include 'connect-db.php';
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$company = mysql_real_escape_string(htmlspecialchars($_POST['company']));
$itemname = mysql_real_escape_string(htmlspecialchars($_POST['itemname']));
$quantity = mysql_real_escape_string(htmlspecialchars($_POST['quantity']));
$category = mysql_real_escape_string(htmlspecialchars($_POST['category']));
$signature = mysql_real_escape_string(htmlspecialchars($_POST['signature']));
// check to make sure both fields are entered
if ($date == '' || $quantity == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($id ,$date ,$company,$itemname,$quantity,$category,$signature, $error);
}
else
{
// save the data to the database
mysql_query("INSERT INTO receive SET date='$date',company='$company',itemname='$itemname',quantity='$quantity',category='$category',signature='$signature'");
$result = mysql_query("INSERT INTO stock SET date='$date',company='$company',itemname='$itemname',quantity='$quantity',category='$category',signature='$signature'")
or die(mysql_error());
echo "<center>Recive Complete!</center>";
// once saved, redirect back to the view page
}
}else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','','','','','','');
}
?>
INSERT INTO stock SET
date='$date',company='$company',itemname='$itemname',quantity='$quantity',
category='$category',signature='$signature'
ON DUPLICATE KEY UPDATE quantity='$quantity'
Or do
...ON DUPLICATE KEY UPDATE quantity='$quantity'+quantity
if you want to add to the existing quantity.
After you put an unique composite key on company and itemname so that the duplicate condition is triggered.
ALTER IGNORE TABLE stock ADD UNIQUE someName (company, itemname);

Categories