refresh data after $_POST on same page - php

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

Related

MySQL PHP - Fetch data and present in HTML

I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.

sql can not work within Session_start() in another page

Session is used in my project. After log in successfully, session_start() is called in my login.php page. And then it will go to another page:repair_device.php. In repair_device.php,
isset($_SESSION["admin"])&&$_SESSION["admin"]==true //this can pass
and alert("testInDR") can be showed correctly. But sql did nothing.
If I choose log on directly in repair_device.php, for example:
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
sql= "select * from hpc_repairdevice order by datetime desc" works fine.
Here is the code of login.html
<form class="login" action="index.php" method="post">
<span>account:</span><input type="text" name="username" /><br /><br />
<span>password:</span><input type="password" name="password"/><br /><br />
<span>verificationCode:</span><input type="text" name="code" /><img id="code" src="create_code.php" alt="another" style="cursor: pointer; vertical-align:middle;" onClick="create_code()"/><br /><br />
<input type="submit" style="margin-left:35%" value="logon" /><input type="reset" value="" /> </div>
</form>
Here is the code of index.php
<?php
session_start();
if(!isset($_GET['log_out']) && ($_POST['code'] != $_SESSION['code']))
{
echo "wrong verificationCodeļ¼<br />" . "<meta http-equiv='refresh' content='2;url=index.html'>";
}
if(!isset($_GET['log_out']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
if($user!=null & $pwd!=null)
{
try
{
$conn=new PDO('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd);
}
catch(PDOException $e)
{
echo "faile<br />".$e->getMessage()."<meta http-equiv='refresh' content='1;url=index.html'>";
}
if($conn)
{
$_SESSION["admin"]=true;
$stas = $conn->getAttribute(PDO::ATTR_CONNECTION_STATUS);
.....
echo "<script language='javascript' type='text/javascript'>";
echo "window.location.href='http://xx.xx.xx.xx/repair_device.php'";
echo "</script>";
.....
}
}
}
?>
Here is the code of create_code.php
<?php
session_start();
//create pic
header("Content-type: image/png");
.....
$_SESSION['code'] = $verifyCode; //stor verification code in session
......
?>
Here is the code of repair_device.php
<!DOCTYPE html>
<html>
<head>
......
</head>
<body>
<?php
session_start();
// $conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
//$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
$admin=false;
if(isset($_SESSION["admin"])&&$_SESSION["admin"]==true)
{
alert("testInDR");
$sql = "select * from hpc_repairdevice order by datetime desc";
......
$sel=$conn->query($sql);
......
}
?>
</body>
</html>
I suppose session id should be passed to repair_device.php, but I don't know how. Who can help me ?
A database connection isn't passed with the session. One popular way is to have a DB bootstrap file that is included at the head of any page that needs access to the database (Or an autoloader).
<?php //index.php, repair_device.php
require_once('db.php');
//rest of page
And in the db page you setup your connection (and probably start the session)
<?php // db.php
session_start();
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
Then the result that would be rendered by PHP would be
<?php // index.php
session_start();
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
//rest of page
Including the connection on any page that needs it simply requires the one line of code.

Trying to create login page using PHP and SQL

I've been working on a website login, and so far, I have the database and register page set up, but I'm trying to work on a Login page. I've been trying to retrieve data from the Database's Table. I was successfull at doing so on my register page to make sure there aren't multiple usernames of the same name, so I copied some of the code and pasted it onto this page. The problem: it returns blank. Please help... ._.
`
KHS SiteSpace
<div id="header">
<img src="./IMAGES/khslogo2.png" style="margin-left:4;float:left;" width="100" hieght="100">
<b>KHS<span id="name">SiteSpace</span></a>
<!--img src="./IMAGES/Menu.png" style="float:right;margin-right:6;" height="100" width="90"-->
</div>
<div id="content">
<p id="subTitle">Login</p>
<div style="float:left;height:30%;">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" id="register"><br>
Username:<br>
<input type="text" name="name"><br><br>
Password:<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Confirm">
</form>
</div>
<div style="float:right;width:50%;border-style:none none none solid; border-color:222222;border-width:4;height:30%;">
<p style="margin-left:20;font-size:20;">Output:</p>
<p style="margin-left:20;padding-bottom:15;">
<?php
error_reporting(0);
#ini_set('display_errors', 0);
session_start();
$conn = new mysqli("localhost", "shanedrgn", "getting321", "Users");
if (!$conn) {die("Failure to connect");}
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
if (empty($name) or empty($pass)) {echo "Empty Fields";} else {
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
echo "Check: The fields arent empty...";#OUTPUT
echo "Testing Variables...";#OUTPUT
//Error Trapping
$sql = "SELECT Username FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$nameTrap = $record['Username'];
}
$sql = "SELECT Address FROM Users where Address = '$address'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$ipTrap = $record['Address'];
}
if ($nameTrap == $name) {
echo "Check: Username Exists...";
if ($passTrap == $pass) {
echo "Password is correct!";
$_SESSION['User'] = $name;
$sql = "SELECT * FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
$record=mysqli_fetch_array($Data);
session_start();
$_SESSION['id'] = $record['id'];
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
exit();
} else { echo "Password Invalid";}
} else {echo "That username doesn't exist!";echo $name.";;";echo $nameTrap;}
}
?>
</p></div>
</div>
</body>
</html>`
EDIT: Added missing code
You are doing this:
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
I understand, what you try, but it can't work. You can't set an Header after sending Body-Content - what you do using echo.
You should use JavaScript for your redirect, after the 4 second timeout. Use setTimeout and window.location.

PHP cms submit in textarea not working

i got a problem with my simple cms in php.
I can get website content in an textarea and after i edited it i want to send the new edited content to the database, but thats not working.
here is my form and functions
editContent.php
<html>
<head>
<title> Basic CMS - Admin Area</title>
<h1>Admin Area Edit Content</h1>
</head>
<body>
<?php
include ('includes/functions.php');
$cont = getContent();
session_start();
if(isset($_SESSION['user'])) {
?>
<span>Logged In! Welcome <?php echo $_SESSION['user']; ?></span>
Logout
Wijzig content
Admin Home
<form action="doEditcontent.php" method="post">
<textarea name="contentarea"><?php echo $cont['content'];?></textarea><br>
Submit : <input type="submit" value="submit" />
</form>
<?php
} else {
header("Location: login.php");
}
?>
</body>
</html>
functions.php
<?php
include('includes/connect.php');
function getContent(){
$query = mysql_query("SELECT content FROM taalcontent WHERE taalid = 1 AND contentid = 1") or die (mysql_error());
return mysql_fetch_assoc($query);
echo $query;
}
function editContent($pContent) {
if(isset($pContent)){
$query = "UPDATE taalcontent SET content content = '$pContent' WHERE contendid = 1 AND taalid = 1";
} else {
echo "fout";
}
mysql_query($query);
}
doEditcontent.php
<?php
include('includes/functions.php');
if(isset($_POST['submit'])) {
if(isset($_POST['contentarea'])){
editContent($_POST['contentarea']);
header("Location: ../index.php?page=2");
} else
echo "Please enter some content!";
} else {
header("Location: ../index.php?page=1");
}
?>
Try changing
editContent($_GET['content']);
to
editContent($_POST['contentarea']);
As it is you are asking it to set the content to whatever is in the ?get parameter (which I can't see referenced anywhere else so I'm guessing its not populated with anything).
:)
You're passing the wrong argument when you call the function editContent($pContent). Also, you should define the function before it's referenced.
Try this way:
<form action="doEditcontent.php" method="post">
<textarea name="contentarea"><?php echo $cont['content'];?></textarea><br>
Submit : <input type="submit" value="submit" />
</form>
<?php
include('includes/functions.php');
function editContent($pContent) {
if(isset($pContent)){
$query = "UPDATE taalcontent SET content content = '$pContent' WHERE contendid = 1 AND taalid = 1";
} else {
echo "fout";
}
mysql_query($query);
}
if(isset($_POST['submit'])) {
if(isset($_POST['contentarea'])){
editContent($_POST['contentarea']);
header("Location: ../index.php?page=2");
} else
echo "Please enter some content!";
} else {
header("Location: ../index.php?page=1");
}
?>

Session-based login not working properly

I am currently working on a site and i'm making a login system. I am using sessions to keep track of login status. The pages involving login until now are shown below:
(I change pages defining post variables in the url, like this: site.domain.com/?home)
index.php
/* CONNECTION TO CHECK LOGIN STATUS */
<?php
if (isset($_GET["sair"])){
session_start();
session_destroy();
}
if (isset($_SESSION["user"]) && isset($_GET["entrar"])){
mysql_connect("localhost","dbusr","password") or die("Can't connect to DB");
mysql_select_db("mydb") or die("Can't select DB");
$userinfo = $_SESSION["uinfo"];
}
?> /* START OF THE PAGE, RANDOM UNIMPORTANT HTML */
<?php if (!isset($_SESSION["user"])) { ?> /*NOT LOGGED IN...*/
<form id="loginform" method="post" action="scripts/checklogin.php">
<h2>Login</h2>
<?php if (isset($_GET["falha"])) { echo "<span class='erro'>Nome ou senha incorretos</span>"; }?> /*IF LOGIN ERROR*/
<input type="text" name="user" autofocus placeholder="Apelido"/><br />
<input type="password" name="pass" placeholder="Senha"/><br /> /*LOGIN FORM*/
<input type="submit" value="Entrar"/>
</form>
<?php
} else { /*LOGGED IN...*/
if ($userinfo["sexo"]=="0"){ /*GENDER*/
echo "Bem-vindo, ".$userinfo["nome"];
} else {
echo "Bem-vinda, ".$userinfo["nome"];
}?>
<?php }?>
scripts/checklogin.php
<?php
mysql_connect("localhost","dbusr","password") or die("Can't connect to DB");
mysql_select_db("mydb") or die("Can't select DB");
$user = mysql_real_escape_string(stripslashes($_POST["user"]));
$pass = md5(mysql_real_escape_string(stripslashes($_POST["pass"])));
$result = mysql_query("SELECT * FROM users WHERE apelido = \"".$user."\" AND senha = \"".$pass."\"");
if (count($result)==1) {
session_start();
$_SESSION["user"] = $user;
$_SESSION["pass"] = $pass;
while ($row = mysql_fetch_assoc($result)) {
$_SESSION["uinfo"] = $row;
}
header("location:../?entrar");
} else {
header("location:../?falha");
}
?>
But when i go to the page and enter my info, it still doesn'tshow the logged in part. Also, when i input a incorrect login, it does not show me the text over the login form (the <span>)
You need to add session_start() in index.php before checking $_SESSION["user"].

Categories