Redirect to another page after button submit - php

I am building an application where details are displayed (admin.php).The user clicks on edit(edit.php) and he is redirected to another page to edit his details. Once the edit is done the values are updated and I want to redirect to the previous page once again where the details are displayed. All the operations carry out as desired , but when I try to redirect inside the "submit" to the previous page it doesn't occur.
Admin.php
$event_id = $_SESSION['fedit'];
if($_GET['edit'])
{
$url = "edit.php?event_id=". $event_id;
header("Location: $url");
}
Edit.php
if($_GET["Submit"])
{
$val=$_GET['event'];
$remail=$_GET['email'];
$rname = $_GET['ename'];
$sqt=mysql_query("UPDATE users SET NAME='$rname',EMAIL='$remail' WHERE EID ='$val'");
$page= "admin.php";
header("Location: $page");
}

I don't know where you have placed this code on the page but if somehow a http header output is being sent before that header(location:"") then it wont work. Try the suggestions by other people, but if all else fails, you might wanna use JS.
echo "<script>window.location.assign("admin.php")</script>";
Use that instead of
header("Location: $page");
and it should work I guess.

add action='edit.php' method='get' to your form tag.
and in edit.php page place your rest of the code after submit.

Preferably do this:
if ($_GET["Submit"]) {
...
// Clean any output
ob_clean();
header("Location: $page");
// Exit the PHP process
exit;
}

It's very hard to tell what are you doing from the incomplete code you posted.
However, it looks like that not redirect but form submission is broken.
There are also 2 serious flaws in your code:
Whatever edits have to be done using POST method, not GET
you have to properly format your SQL query.
Anyway, here is an example of such an application (though editing only one field. you can easily add more) which works.
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
And you will need 2 templates too, to hold your HTML
form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>

use header("Location : ". $page); instead of header("Location: $page");
if($_GET["Submit"])
{
$val=$_GET['event'];
$remail=$_GET['email'];
$rname = $_GET['ename'];
$sqt=mysql_query("UPDATE users SET NAME='$rname',EMAIL='$remail' WHERE EID ='$val'");
$page= "admin.php";
header("Location : ". $page);
}

Actually, that is not going to work, isnce your edit.php will never reach its if statement, as you are not sending $_GET["submit"]. You need to do the following (send the submit variable by setting it to any value)
admin.php
$event_id = $_SESSION['fedit'];
if($_GET['edit'])
{
$url = "edit.php?event_id=". $event_id . "&submit=1";
header("Location: $url");
}
edit.php
if($_GET["Submit"])
{
$val=$_GET['event'];
$remail=$_GET['email'];
$rname = $_GET['ename'];
$sqt=mysql_query("UPDATE users SET NAME='$rname',EMAIL='$remail' WHERE EID ='$val'");
header("Location: admin.php");
}

Related

how to display all data on a webpage

I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>
after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to

isset function not working properly

The page is unable to see the login form whose code is written under the isset function statement. I have written the code correctly and have executed it many times , but now the code written inside the isset statement does not works. here is the code:-
<?php
session_start();
echo "<p style=\"font-color: #ff0000;\"> Catogoies </p>";
echo '<link href="var/www/html/sample.css" rel="stylesheet">';
require_once('../html/conn.php');
$query = "select * from catogories";
mysqli_select_db($dbc, 'odit');
$retrieve = mysqli_query($dbc, $query);
if(!$retrieve)
{
die(mysqli_error($query));
}
while($row=mysqli_fetch_array($retrieve, MYSQL_ASSOC)){
echo "<p style=\"font-color: #ff0000;\">".''.$row["Name"].''."</p>";
$_SESSION['cat']=$row["Name"];
}
if(!($_SESSION)) {
session_start();
}if(isset($_SESSION['lgout']))//the variable logout intialization line
{
if($_SESSION['lgout']!=1||$_SESSION['signup']){
echo "Hello : ".''.$_SESSION['unme'].''; echo "<br><br>";
echo '<a href="logout.php">'."Logout";}
else {
include 'lform.php'; echo "<br><br>";
echo '<a href="Sign_up.php">'."Sign up"."<br>";
} }
mysqli_close($dbc);
//include 'lform.php';
?>
<br>
<a href = 'adding_catogory.php'>Create a New Catogory</a><br><br>
<a href = 'Log_in.php'></a>
<?php
$db = #mysqli_connect("localhost", "oddittor", "Odit#123", "odit");
if(isset($_POST['login'])){
$username=mysqli_real_escape_string($db, $_POST['l_id']);
$password=mysqli_real_escape_string($db, $_POST['pswd']);
$sql="SELECT * from users where usrName='$username' and pswrd = '$password'";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
$count=mysqli_num_rows($result) or die(mysqli_error($db));
if($count>0) {
$_SESSION['unme']=$username; //This is the global session variable...used for storing the variables across the pages.
$_SESSION['lgout']=0;
header('Location : session.php'.$_SESSION['unme']);
header("Location : Homepage.php".$_SESSION['unme'].$_SESSION['lgout']); header( "refresh:0;url=Homepage.php" );
$_SESSION['unme']=$username;
}
else {
$error = "Invalid Details! Please Renter them"; }
}
?>
Here the problem is in the
if(isset($_SESSION['lgout']))
line if, I remove this line i can see the login page form but by doing so, I get the error of undefined variable logout whenever, I open the page for the first time.
here is the logout script
<html>
<?php
session_start();
$_SESSION['lgout']=1;
$_SESSION['signup']=0;
echo ' You have been successfully logged out';
header('Location : Homepage.php'.$_SESSION['lgout']);header( "refresh:0;url=Homepage.php" );
?>
</html>
You need to put your
session_start();
globally on the start of page. As it's not able to get $_SESSION object.
Just remove
session_destroy();
As you can access all $_SESSION values.
Your queries not secured. Use Prepared Statements instead of your all queries.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

How to update the data from mysql database with out refreshing the page

I have a website and I need to put a chat box but when someone write the users has to refresh the whole page to read the text but I need to make it automatically update the data please help me.
Now this is the code:
<?
session_start();
include("includes/config.php");
if($_GET['with']){
if($_SESSION['login']){
if($_SESSION['login'] == $_GET['with']){
header("Location: index.php");
}else{
$id = $_SESSION['login'];
$with = intval($_GET['with']);
if($_POST['submit']){
$text = $_POST['text'];
if(empty($text)){
}else{
$query = mysqli_query($connect,"INSERT INTO chat(`from`,`to`,`topic`) VALUES('$id','$with','$text')");
}
}
?>
<form method="post" action="chat.php?with=<?=$with?>">
<textarea name="text" placeholder="Write Here..." style="text-align:right;resize:none;width:100%;height:200px;font-size:24">
</textarea>
<br/>
<input type="submit" name="submit" value="Send"/>
</form>
<div id="chat">
<?
$query = mysqli_query($connect,"SELECT * FROM users WHERE id='$id'");
$f = mysqli_fetch_array($query);
$query = mysqli_query($connect,"SELECT * FROM users WHERE id='$with'");
$ff = mysqli_fetch_array($query);
$query = mysqli_query($connect,"SELECT * FROM chat order by id desc");
while($fetch = mysqli_fetch_array($query)){
if($fetch['from'] == $with && $fetch['to'] == $id or $fetch['from'] == $id && $fetch['to'] == $with){
if($fetch['from'] == $f['id']){
echo "<div style='word-wrap: break-word;'>".$f['fname']." ".$f['lname'].":<br/>".$fetch['topic']."</div>";
}
if($fetch['from'] == $ff['id']){
echo "<div style='max-width:200px;word-wrap: break-word;'>".$ff['fname']." ".$ff['lname'].":<br/>".$fetch['topic']."</div>";
}
}
}?>
</div>
<?}
}else{
header("Location: index.php");
}
}else{
header("Location: index.php");
}
?>
With only using php you cannot achieve what you want. However you can use ajax to accomplish what you asked for. An there is examples with source codes provided. Here is some of them:
https://css-tricks.com/jquery-php-chat/ (i recommend this/ well documented and with source code as well)
http://code.tutsplus.com/tutorials/how-to-create-a-simple-web-based-chat-application--net-5931
http://www.sitepoint.com/9-crazy-jquery-chat-chat-box-plugins/ (lis of ajax/php based chat applicatiosn)
Ajax will help you. But it is a bad practice the way you mix html javascript and php in the same code; Like this, it will be difficult for many people to help you to adapt your code with ajax.

MySQL database is updated with empty value when updating using PHP

I am new in php, i tried this coding i select a value in my drop down list i want a corresponding value to be updated, i have list of user name in my database and a ID for them, i am displaying the user name and when i want to update i written a sql query to find the member id and update to database but it's inserting a null value. Here is my code.
Dropdown list code
<?
session_start();
if(!isset($_SESSION[''])){
header("location:");
}
?>
<?php include('dbconnect.php'); ?>
<?php
$ed=$_GET['ed'];
$query=mysql_query("select * from table1 where id='$ed'");
$query2= "select * from table2";
$row=mysql_fetch_assoc($query);
if($_POST['Submit'])
{
$mem= $_POST['memid'];
$memname =mysql_query("select memid from table2 where name='$mem'");
$memname1= mysql_fetch_assoc($memname);
$tot_count = mysql_fetch_assoc($ro_count);
$date=date("d-m-Y");
$status="Active";
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']);
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=1;
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=1;
}
$insert=mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header("Location");
}
}
?>
<body>
<div id="main_container"><br />
<div class="main_content">
<div class="center_content">
<div class="right_content">
<div class="form">
<form action="" method="post" name="fomo" enctype="multipart/form-data" onsubmit="return fall();" class="niceform">
<h1 align="center">Edit Referal Partner </h1>
<?
if($_GET['val']==1) { echo "<h1 class='FeatureBlockHeader' >Member Added Successfully</h1>"; } ?>
<fieldset>
<dl><dt><label for="Owner Name">Referal Partner Name</label></dt><dd><input name="onamo" type="text" size="53" id="onamo" value="<?=$row['oname']?>"/><b style="color:#CA0000"><?=$onamo1?></b></dd></dl>
<dl><dt><label for="">Health Executives</label>
<?php $result1 = mysql_query($query2);
echo'<select name="memid" >';
while($row = mysql_fetch_assoc( $result1 )) {
echo '<option value="'.$row['name'].'">' . $row['name'] . '</option>';
}
echo '</select>'; ?>
</b></dd></dt>
<dl><dt><label for="submit"></label></dt><dd> <input type="submit" name="Submit" value="Submit"></dd></dl></fieldset>
</table>
</form>
'
My database is updated with empty string, if i directly pass the dropdown value Name it's updating fine. But i want to update the corresponding memberid to my table. Please help me.
Stage 1:
You don't do anything if the field is blank. (Plus you have your logic wrong with $ok).
Suggested code would be:
$ok = 1; // assume ok unless we have an error
if($_POST['heid']=='')
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if($_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.
** Stage 2:**
You should check for isset($_POST['onamo']) before getting the variable. Otherwise it would throw a warning. This will probably give you the error. You have a discrepancy between 'heid' and 'memname1'! :)
$ok = 1; // assume ok unless we have an error
if(!isset($_POST['heid']) || $_POST['heid']=='') // Or is it $_POST['memname1']?
{
$namo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if(!isset($_POST['onamo']) || $_POST['onamo']=='')
{
$onamo1="*Required";
$ok=0; // Set to "0" to say "Not Ok"
}
if ($ok)
{
$onamo=mysql_real_escape_string($_POST['onamo']);
$heid = mysql_real_escape_string($_POST['memname1']); // Or is it $_POST['heid'] ??
// Do your update
$insert = mysql_query("update table1 set oname='$onamo', heid='$heid' where id='$ed'") or die('error');
if($insert)
{
header('location: ???');
exit(); // ALWAYS exit after a header redirect, otherwise the rest of the code will continue to work, then the redirect happens!
}
$ok = 0;
$error = 'Failed to update database'
}
// If you get here, you have an error condition.

creating two different sessions in PHP

I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.

Categories