PHP Form , session data not being stored - php

we are working with php session data, but the data is not being stored in the database
login.php
<h2>Welcome</h2>
<form action = "Customer.php" method = "POST">
Customer Name:<input type = "text" name="customerName">
<input type = "submit" name = "submit">
</form>
Customer.php
<?php
session_start();
#include("Connection.php);
if (isset($_POST['submit'])) {
$name = $_POST['customerName'];
$_SESSION['user'] = $name;
}
if (isset($_SESSION['user']))
{
echo "Hello {$_SESSION['user']}, welcome to starbucks!";
}
else
{
echo "walang tao";
$sql="INSERT INTO `customer`.`people` ('ID', `NAME`) VALUES ('','$name')";
mysql_query($sql);
?>
Logout
and logout.php
<?php
session_start();
session_destroy();
?>
Click me to return to login
please tell me what's wrong

try displaying the mysql_error and see what the problem is
mysql_query($sql) or die(mysql_error());

Related

Session Variable not accessible when opening website on other device [php code]

I have local host website. Connected two devices to a hotspot and accessing the website using the ip of the server. All the pages open properly but the session variable is not recognised as "Undefined Index" error throws up.
While when I access the same on the localhost I donot face this issue.
I have used session_start() in all the files.
Have the code snipped of Login.php
<?php
session_start();
?>
<html>
<head><title>LOGIN</title></head>
<body>
<form action= "Dashboard.php" method = "POST">
<br/>Name: <input type = "text" name = "name">
<br/>Password: <input type = "password" name = "password">
<br/><input type="submit" name = "submit" value = "submit"> or Register
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$password = $_POST['password'];
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
$query = mysqli_query($connect,"SELECT * FROM users WHERE Name = '$name' and Password='$password'");
$count = mysqli_num_rows($query);
if($count == 1){
$_SESSION['username'] = $name;
echo "Login Successful";
}else{
echo "Invalid Login Credentials";
}
}
?>
After login Dashboard.php
<?php
session_start();
?>
<html>
<head><title>Dashboard</title></head>
<body>
<form action= "" method = "POST">
<?php echo "Welcome ".$_SESSION['username'].".<br>";
?>
<br/>Sex: <select name="sex"> <option value ="Male">Male</option> <option value = "Female">Female</option></select>
<br/>Age: <select name="years">
<?php
for($i=1; $i<=50; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
<option name="years"> </option>
</select>
<br/>Citizen: <select name="citizen"><option value="Singaporean">Singaporean</option><option value="International">International</option></select>
Click to Download!
<br/><input type="submit" name = "submit2" value = "Save Changes"> orLogout
</form>
</body>
</html>
<?php
if(isset($_POST['submit2'])){
$name = $_SESSION['username'];
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
$query1 = mysqli_query($connect,"SELECT Sex,Age,Citizen FROM users where Name = '$name'");
while ($row = mysqli_fetch_row($query1))
/* {
echo "Details Entered in Database:".".<br>";
echo "<br>";
echo "Name:".$_SESSION['username'].".<br>";
echo "Sex:".$row[0].".<br>";
echo "Age:".$row[1].".<br>";
echo "Citizen:".$row[2].".<br>";
}*/
$sex = $_POST['sex'];
$years = $_POST['years'];
$citizen = $_POST['citizen'];
$query2 = mysqli_query($connect, "UPDATE users SET Sex = '$sex', Age='$years', Citizen='$citizen' WHERE Name = '$name'");
echo "Saved changes";
}
?>
Please suggest
Your form has the action "Dashboard.php", so that script will handle the submission of your login form.
In other words, the logic inside the code block for the if statement if(isset($_POST['submit'])){ is probably not executed, so your session variable isn't set.
You can set the action to "Login.php" or leave it blank to let Login.php handle the login, then you can redirect to Dashboard.php if you desire and the session variable should be set.
Do mind that if you want to redirect using PHP, it must be done before the HTML. Otherwise it won't work.

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

HTML/PHP login redirects to php

I have an html page that uses a php file to query a database, then log the user in, or deny access. The problem I'm having is that it simply redirects to the url of the php file, and never gives feedback on what happened. This is my first assignment with html, php, and mysql, so please excuse my lack of technical terms/knowledge.
HTML File
<html><head><title> Sign-In </title></head>
<body>
<h1> Login Form </h1>
<div id="Sign-In">
<form method="POST" action="connectivity.php">
Username: <input type='text' name='username'> <br><br>
Password: <input type='password' name='password'> <br><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</div>
</body>
</html>
PHP File
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'project2');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn()
{
session_start(); //starting the session for user profile page
if(!empty($_POST['user'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM customers where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
try this:
<?php
if (!empty($row['userName']) AND !empty($row['pass'])) {
$_SESSION['userName'] = $row['pass'];
header("Location: mypage.php?is_login=1");
exit; // exit is must or you can use retun also
}
else {
header("Location: mypage.php?is_login=0");
exit; // exit is must or you can use retun also
}
?>
on the page mypage.php
<?php
if (isset($_GET['is_login']) ) {
if ('1' == $_GET['is_login']) {
echo "sucess";
}
else {
echo "failure";
}
}
?>
In your PHP File try to redirect to previous URL or to a new HTML Page Like Home Page :
header('Location: ' . $_SERVER['HTTP_REFERER']);
in your:
if(isset($_POST['submit']))
{
SignIn();
}
Example for you answer
Redirect to your PROFILE PAGE using header() OR Javascript
header("Location: profilepage.php"); //PHP
<script>window.location = 'profilepage.php'</script> //JS

I can't get the string $_POST['add'] to save so instead it updates my database with an empty string. where is the issue?

I am trying to make an update in my database using two post variables, one from file clientpag.php and another from login.php. The variable $_POST['add'] which is an input from clientpag.php is not being saved. Can you help please? it is my first project using php!
LoginScript.php
<?php
session_start();
include_once'config/connect.php'; //database connection
if($_POST['submit']) {
$address = mysql_query("UPDATE venue SET location='".$_POST['add']."'
WHERE vid = (select vid from user_venue where id = (select user_id from iangadot_user
where username='".$_POST['username']."' ))");
while($row = mysql_fetch_assoc($address)){
$_SESSION['add'] = $row['location'];
}
header("Location: clientpag.php");
} else {
echo "<script language=javascript>alert('error')</script>";
}
?>
clientpag.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<form action="LoginScript.php" method="POST">
<p>Address:</p> <input class = "field" name="add" placeholder= "<?php
if(isset($_SESSION['address'])) { echo $_SESSION['address']; } ?>" type="text" >
<input class = "button" type = "submit" Value = "Save"><br>
</form>
</body>
</html>
Change
<input class = "button" type = "submit" Value = "Save">
to
<input class = "button" type = "submit" Value = "Save" name="usubmit">
and then in PHP script change
if($_POST['submit'])
to
if($_POST['usubmit'] !='')
This should work unless there is an error in the query

refresh data after $_POST on same page

I have a page with a who does a post to the same page. I want that page to be refreshed with new data after a succesful database INSERT.
Let me add some code.
default.php
<?php
session_start();
require("dbconfig.php");
include("head.php");
//if user is not signed in, redirect to login page
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
?>
<body>
<div id="menu">
<?php
include("menu.php"); //include the menu
?>
</div>
<div id="page_content">
<?php
include ($p); //Include selection from menu.php
?>
</div>
?>
dbconfig.php
<?php
DEFINE ('DB_USER', 'someuser');
DEFINE ('DB_PASSWORD', 'somepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'somedatabase');
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or
die('Connection to the specified database couldn\'t be established');
mysql_select_db(DB_NAME) or
die ('Specified database couldn\'t be selected');
function db_escape ($post)
{
if (is_string($post) ) {
if (get_magic_quotes_gpc() ) {
$post = stripslashes($post);
}
return mysql_real_escape_string ($post);
}
foreach ($post as $key => $val) {
$post [$key] = db_escape($val);
}
return $post;
}
?>
page/cities.php
<?php
//if not signed in correctly, redirect to login page
session_start();
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
?>
<h2>Available cities</h2>
<?php
//List all available cities from database
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
while ($row = mysql_fetch_assoc($cities_result)) {
echo $row['city_name'] . "<br />";
}
?>
<?php
//Add new city to list
if(isset($_POST['submit'])){
$city_name = $_POST['city_name'];
$query="INSERT into city_selection (city_name) values ('$city_name')";
$result = mysql_query($query);
}
?>
<hr>
<h2>Add new city</h2>
<form method="post" action="default.php?p=settings_cities">
Namn: <input type="text" name="city_name">
<input type="submit" name="submit" value="Add city">
</form>
This code may not be pretty but it works. It succesfully adds a new record to the database however I want the page/cities.php to be refreshed with my ny record after the post. Is this possible?
Let me add that this i my first ever php page. I've only read some books so don't bash me for beeing a bad programmer :)
Yes, just move your insert part to above your select part.
page/cities.php
<?php
//if not signed in correctly, redirect to login page
session_start();
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
//Add new city to list
if(isset($_POST['submit'])){
$city_name = $_POST['city_name'];
$query="INSERT into city_selection (city_name) values ('$city_name')";
$result = mysql_query($query);
}
?>
<h2>Available cities</h2>
<?php
//List all available cities from database
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
while ($row = mysql_fetch_assoc($cities_result)) {
echo $row['city_name'] . "<br />";
}
?>
<hr>
<h2>Add new city</h2>
<form method="post" action="default.php?p=settings_cities">
Namn: <input type="text" name="city_name">
<input type="submit" name="submit" value="Add city">
</form>
You can also refresh a page with javascript :
<script type="text/javascript">
document.location = "URL"
</script>
Read up on the Post-Redirect-Get pattern, and redirect the browser to the same page after saving the record. The redirect should be done through PHP's header function.
As your code works now, someone refreshing through F5 will insert the same value again... P-R-G avoids this problem.
Just do the
if(isset($_POST['submit'])){
//yada yada
before you do the select

Categories