Potential causes for a php session unset after calling header function? - php

I am setting 2 session variables and then called the header function.
(SecurityCheck.php)
$_SESSION['danger'] = "true";
$_SESSION['priviledgeError'] = "You do not have access";
header('Location: index.php');
However, when the header re-directs to the proper page, only one of the sessions retains its value, even though I never called any type of session unset method.
(index.php)
echo 'line 63 index.php';
echo "<br>danger session is: " . isset($_SESSION['danger']);
echo "<br>priviledge session is: " . isset($_SESSION['priviledgeError']);
line 63 index.php
danger session is:
priviledge session is: 1
I have checked through all relevant files for any places I may have called an unset function, and made sure session_start() is appended to the top of both pages.
I expect that both sessions will return "1" and not just one of them.
Entire Index.php file:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style2.css">
<style>
#userPass
{
padding; 20px;
}
#logIn
{
padding: 20px;
position:relative;
border-style: solid;
margin:auto;
background-color: white;
width: 390px;
height: 160px;
}
#log-in-header
{
position: absolute;
left:46%;
font-size: 35px;
color:black;
}
#submitButton
{
position: relative;
top: 83px;
width: 347px;
}
td
{
padding: 20px;
}
</style>
</head>
<!--ONLY runs when user has clicked LOG-IN-->
<body>
<div id='container'>
<?php
echo 'line 63 index.php';
echo "<br>danger session is: " . isset($_SESSION['danger']);
echo "<br>priviledge session is: " .
isset($_SESSION['priviledgeError']);
// die;
require 'header.php';
require 'messages.php';
?>
<br>
<p id='log-in-header'>
Log-In
</p>
<hr><br><br><br>
<form method="post" action="login.php">
<div id='logIn'>
<!-- <div id='userPass'>-->
<table style = "position: relative; bottom:
40px;">
<tr>
<td style='font-size: 20px'>Username:</td>
<td><input type="text" style='color:
black' name="userName" id='user' ></td>
</tr>
<tr>
<td style='font-size: 20px'>Password:</td>
<td><input type="password" style='color:
black' name="password" id='pass' ></td>
</tr?
</table>
<!-- </div>-->
<div id='submitButton'>
<input type="submit" class="btn btn-default"
style='color: black; font-size: 20px' value="Log In">
</div>
</div>
</form>
</div>
<!-- LOG-IN form ENDS -->
<!-- JS scrips-->
<script src="js/index.js"></script>-->
</body>
</html>`
UPDATE: added a new session entry, as well as a session deleteion to SecurityCheck.php
$_SESSION['danger'] = "true";
$_SESSION['priviledgeError'] = "You do not have access
unset($_SESSION['priviledgeError']);
$_SESSION['newSession'] = "hi";
header('Location: index.php');
Here is code in index.php:
echo 'line 63 index.php';
echo "<br>danger session is: " . isset($_SESSION['danger']);
echo "<br>priviledge session is: " .
isset($_SESSION['priviledgeError']);
echo "<br>new session is: " . $_SESSION['newSession'];
Here is result:
line 63 index.php
danger session is:
priviledge session is:
new session is: hi

Related

PHP comments appearing on the webpage

I commented out PHP comments on my script. but they still appear on my webpage in HTML. Do you have any idea how do I fix this?
kind regards,
/*if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not copied multiple times
require_once('LoginFunctions.php');*/
this text appear on my webpage:
my whole script:
Here is my whole script so you can identify where the mistake is.
<link rel="stylesheet" href="style.css">
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
include 'Header.php';
?>
<style>
body
{
background-color:#FFFFC2;
alignment-adjust: central;
float: none;
background-image: url("images_1/sea-sanctuaries-siteimage01.jpg");
alignment-baseline: central;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height:100%;
}
#div_1 {
width: 40%;
hight: 80%;
background-color: bisque;
border: 5px;
border-radius: 25px;
}
#div_2 {
font-family: sans-serif;
padding-bottom: 10px;
padding-right: 50px;
margin-top: 5px;
margin-right: 50px;
}
</style>
<body>
<div id="container">
<br>
<?php
/*
if($_DEBUG)
{
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
}
$page_title = 'Login';/* */
//in this page we do things slightly differently - the code for validation and displaying messages is done
//before we display the form
echo '<div id = "div_1><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="index.php" method="post">
<label>UserName<br>
<span class="small">enter your username</span>
</label>
<input type="text" name="UserName" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="TRUE">
</form>
</div>
</div>';
/* if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not copied multiple times
require_once('LoginFunctions.php');
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the values in the array to $check and $data
list($check, $data) = checkLogin($_POST['UserName'], $_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time()+ 900 ) ; //cookie expires after 15 mins
setcookie('LName', $data['LName'], time() + 900 ) ;
//
//use session variables instead of cookies
//these variables should now be available to all pages in the application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['UserName'] = $data['UserName'];
//to enable $_SESSION array to be populated we always need to call start_session() - this is done in header.php
//print_r is will print out the contents of an array
//print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in Loginfunctions.php to give absolute path for required page
$logged = true;
//this version of the header function is used to redirect to another page
header("Location: $url");//since we have entered correct login details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br />';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
</body>
<?php
include 'Footer.php';
?>
comment them inside PHP code sections
<?php /* code here will not display in html */ ?>
<!-- code here will be visible (in view source) -->
If your php interpreter is not running there's no way to hide php code.
You forgot one " in the line
echo '<div id = "div_1><h1>Login</h1>';
which apparently causes it, somehow, to continue echoing what comes after.
Solution: add the missing " after the div_1

get first object from result array php

I have view file on my app there is code array I want to get first object of that array without going in loop.
<?php
$result = array_chunk($products->result_array(), 3);
foreach($result as $products){ ?>
<table style="width:100% style="page-break-after:always;" >
<tr>
<?php
foreach($products as $productArray){
$product = (object) $productArray;
echo '<td>';
?>
<div style="width: 100%; height: 210px; border: 1px solid #dddddd; margin: auto 5px 5px 0; padding: 5px;">
<div class="box-header">
<p class="box-title"><FONT SIZE=12><?php echo $product->product_name; ?></FONT></p>
</div>
<div style="height: 100px; text-align: center;">
<?php echo '<img src="'.'uploads/'. $product->photo.'" class="img-responsive" style="height:100px !important; width: 150px !important" />'; ?>
</div>
<div style="clear: both"></div>
<table class="table table-responsive">
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
$result is array of object I'm getting from a form. In below you can clearly see I'm chunking it to 3 more array and looping though individual objects and getting their details to html for example.
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
I want to get the first object details let's say want get $product->product_name of first object of result array without going in loop how to achieve that.
here is complete view file code.
<!DOCTYPE html>
<html class="bg-black">
<head>
<meta charset="UTF-8">
<title><?php if(isset($title)) echo $title.' | '; ?> Sales agent management software (SAMS) </title>
<style>
body{
font-size: 9px;
margin: 20px;
}
th,td,p,div,table,h3{margin:0;padding:0}
#page { margin: 20px; }
.header{
border-bottom: 0px solid #dddddd;
text-align: center;
position: fixed; top: 0;
}
.footer { position: fixed; bottom: 0px; text-align: center }
.pagenum:before { content: counter(page); }
</style>
</head>
<body>
<?php
$usd = get_option('lkr_per_usd', 134);
?>
<div class="footer">
Page: <span class="pagenum"></span>, creation time : <?php echo date('l jS \of F Y h:i:s A') ?>, create by: <?php echo user_full_name(singleDbTableRow(loggedInUserData()['user_id'])); ?>, $ Rate : Rs. <?php echo $usd; ?> </div>
<br />
<div class="box-body">
<?php
$usd = get_option('lkr_per_usd', 134);
?>
<?php
$result = array_chunk($products->result_array(), 3);
foreach($result as $products){ ?>
<table style="width:100% style="page-break-after:always;" >
<tr>
<?php
foreach($products as $productArray){
$product = (object) $productArray;
echo '<td>';
?>
<div style="width: 100%; height: 210px; border: 1px solid #dddddd; margin: auto 5px 5px 0; padding: 5px;">
<div class="box-header">
<p class="box-title"><FONT SIZE=12><?php echo $product->product_name; ?></FONT></p>
</div>
<div style="height: 100px; text-align: center;">
<?php echo '<img src="'.'uploads/'. $product->photo.'" class="img-responsive" style="height:100px !important; width: 150px !important" />'; ?>
</div>
<div style="clear: both"></div>
<table class="table table-responsive">
<tr>
<th><FONT SIZE=12>ID</FONT></th>
<td><FONT SIZE=14><?php echo $product->product_id; ?></FONT></td>
</tr>
<tr>
<th><FONT SIZE=12>LKR</FONT></th>
<td><FONT SIZE=14><?php $lkr = get_selling_price($product);
echo number_format(round($lkr, get_option('round_precision')) ); ?></FONT>
</td>
</tr>
<tr>
<th> <FONT SIZE=12>US $</FONT></th>
<td><FONT SIZE=14><?php echo number_format(round(lkr_to_usd($lkr), get_option('round_precision')) ); ?></FONT></td>
</tr>
</table>
<?php $GLOBALS['a']= $product->product_id; ?>
</div>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
</div><!-- /.box-body -->
</body>
</body>
</html>
ok man as i said u need to change your way of writing codes but about your specific question use this:
$result = array('a', 'b', 'c', 'd', 'e');
reset($array);
$first = current($array);
you can check this:
http://php.net/manual/en/function.reset.php
http://php.net/manual/en/function.current.php
But still about your way of coding. u should soon go to MVC or such ways of programming so u should separate your view and coding logics
like u may have a page like view_profile.php which is going to show user's information. in regular coding u have this:
view_profile.php:
<?php session_start();
// you check sessions to see if the user is logged in and has the right to view this page.
// like:
if ($_SESSIONS['is_user_logged_in']){
$username=$_SESSIONS['username'];
$name=$_SESSIONS['name'];
// ....
}else{
header('location: ./login.php');// if user is not authenticated u redirect to login page
exit();// prevents the rest of codes to be shown and executed
}
?>
<html>
<head>
<title>View <?php echo $name; ?>'s profile</title>
</head>
<body>
<div>Name: <span><?echo $name; ?></span></div>
......
</body>
</html>
But in a better way u can do it like this:
you have files like
'view_profile.htm' // holds the HTML
'view_profile.php // holds the PHP logic
'inc.php' // holds some useful functions that help you in writing PHP logic
view_profile.htm
<html>
<head>
<title>View <?php echo $name; ?>'s profile</title>
</head>
<body>
<div>Name: <span><?echo $name; ?></span></div>
......
</body>
</html>
inc.php
<?php
function ses_start(){
if(!session_id()){
session_start();
}
}
function ses_get($key){
ses_start();
if(!empty($_SESSION[$key])){
return $_SESSION[$key];
}
return NULL;
}
function ses_set($key,$val){
$_SESSION[$key]=$val;
}
function is_user_loggedin(){
ses_start();
if(!empty(ses_get('is_user_loggedin')){
return true;
}
return false;
}
function go($to){
header('location: '.$to);
exit();
}
//and lots of useful functions that help u connect and work with data base.
view_profile.php
<?php
include('inc.php');
if(is_user_loggedin(){
$username=ses_get('username');
$name=ses_get('name');
//...
}else{
go('login.php);
}
include('view_profile.html); // and u call the .htm file that holds the HTML the view file)
?>
this was a simple sample of separating codes logic(php codes) from views(html tags)
and also u may search about MVC Model-View-Controller and try working with simple MVC frameworks.

Session not working on My Web server

Showing Error
Warning: session_start() [function.session-start]: Cannot send session cookie -
headers already sent by (output started at
/home/content/82/11942882/html/praveen/Allyface/index.php:8) in
/home/content/82/11942882/html/praveen/Allyface/index.php on line 11
Warning: session_start() [function.session-start]: Cannot send session cache limiter - >headers already sent (output started at >/home/content/82/11942882/html/praveen/Allyface/index.php:8) in >/home/content/82/11942882/html/praveen/Allyface/index.php on line 11
index.php
<?php
//simple PHP login script using Session
//start the session * this is important
session_start();
//login script
if(isset($_REQUEST['ch']) && $_REQUEST['ch'] == 'login'){
//give your login credentials here
if($_REQUEST['uname'] != '' && $_REQUEST['pass'] != '')
{
$email=$_REQUEST['uname'];
$pass=$_REQUEST['pass'];
//echo $email.$pass;
include("db.php");
mysql_query("select * from users where email='$email' and pass='$pass' ");
if(mysql_affected_rows()>0)
{
$_SESSION['login_user'] = $email;
}
else
{
$_SESSION['login_msg'] = 1;
}
}
else
$_SESSION['login_msg'] = 1;
}
//get the page name where to redirect
if(isset($_REQUEST['pagename']))
$pagename = $_REQUEST['pagename'];
//logout script
if(isset($_REQUEST['ch']) && $_REQUEST['ch'] == 'logout'){
unset($_SESSION['login_user']);
header('Location:index.php');
}
if(isset($_SESSION['login_user'])){
if(isset($_REQUEST['pagename']))
{
?>
//header('Location:'.$pagename.'.php');
<script type="text/javascript">
self.location='<?php echo $pagename.'.php'; ?>';
</script>
<?php
}
else
{
$email=$_REQUEST['uname'];
?>
<script type="text/javascript">
self.location='<?php echo 'home.php'; ?>';
</script>
<?php
}
//header('Location:home.php');
}else{
?>
<form id="" name="form1" method="post" action="">
<table width="452" border="0">
<tr>
<td width="172"> <input name="uname" type="text" style="margin-top:15px; width:150px; height:22px; border:1px solid #CCCCCC; padding-left:30px;" placeholder="Email or Phone" />
</td>
<td width="177"> <input name="pass" type="password" style=" margin-top:15px; width:150px; height:22px; border:1px solid #CCCCCC; padding-left:30px;" placeholder="Password" />
</td>
<td width="81"><input name="login" type="submit" style=" margin-top:15px; background-color:#FFFF00;background-color: #fdd922; margin-left:30px;
border: 1px solid #e0bc27; font-weight:bold;
border-radius: 2px 2px 2px 2px; height:25px; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color: #565656;" placeholder="login" value="Login" /></td>
</tr>
<tr>
<td colspan="3"><?php
//display the error msg if the login credentials are wrong!
if(isset($_SESSION['login_msg'])){
echo '<div style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color:#F00;">Wrong username and password !</div>';
unset($_SESSION['login_msg']);
}
?> </td>
</tr>
</table>
<input type="hidden" name="ch" value="login">
</form>
</div>
<?php }
?>
home.php
<?php
session_start();
//check logged in or not!
if(!isset($_SESSION['login_user'])){
?>
//header('Location:index.php?pagename='.basename($_SERVER['PHP_SELF'], ".php"));
<script type="text/javascript">
self.location='<?php echo 'index.php?pagename='.basename($_SERVER['PHP_SELF'],".php"); ? >';
</script>
<?php
}
else
{
include("db.php");
$uname=$_SESSION['login_user'];
$q=mysql_query("select * from users where email = '$uname'");
while($r=mysql_fetch_array($q))
{
$uid=$r['fname'];
?>
Please Help me
Thanks in advance
Make sure there is no data sent by the server before dealing with Sessions.
This includes White Spaces, Blank Lines or any type of data.
The point where output started is shown in the error message:
output started at /home/content/82/11942882/html/praveen/Allyface/index.php:8
It seems you have a "dispatcher" index.php, which loads other php files (like login.php). The reason for this error is something being printed in index.php on line 8.
If you see nothing printed on index.php, then there might be a newline at the end of file (if you are using Vi, it leaves a trailing new line on every file)
It's not possible to set cookies (or send any other headers) after output is started. You could add
ob_start()
at line 1 to buffer the output.

How to process submission without refreshing the page

Hi I am facing some problems in submitting form without refreshing, I know that it has something to do with "return false " but i just dont know where and how to use it. I tried refreshing the page by placing it in (if there are errors) but it just doesnt seem to work. Can you guys help me out??
<?php
$message = '';
$errors = array();
$noErrors = true;
$haveErrors = !$noErrors;
require_once('validations/tradeformresult.php');
if ($noErrors && $userArriveBySubmittingAForm) {
require_once('price.php');// INSERTION
echo "<script type='text/javascript'>\n";
echo "</script>";
echo "<script type='text/javascript'>\n";
echo "alert('Trade is successfully executed!');\n";
echo "</script>";
///////////MESSAGE/////////////////
}
elseif ($haveErrors && $userArriveBySubmittingAForm) {
echo "<script type='text/javascript'>\n";
echo "alert('Please re-enter your parameters.');\n";
echo "return false";
echo "</script>";
}
else if ($userArriveByClickingOrDirectlyTypeURL) { // we put the original form inside the $message variable
$newTitle = 'The link is broken';
$h1Title = '';
$message = '';
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
</script><head><meta charset="UTF-8"></head>
<style type="text/css">
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
text-align: center;
}
div#specialBox {
display: none;
position: relative;
z-index: 3;
p.padding;
padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;
margin: 150px auto 0px auto;
border: 3px solid blue;
outline: 3px solid darkblue;
width: 500px;
height: 500px;
overflow:auto;
background: #FFF;
color: #000;
}
div#wrapper {
position:absolute;
top: 0px;
left: 0px;
padding-left:24px;
}
</style>
<script type="text/javascript">
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox');
overlay.style.opacity = .8;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
</script>
</head>
<body>
<!-- Start Overlay -->
<div id="overlay"></div>
<!-- End Overlay -->
<!-- Start Special Centered Box -->
<div id="specialBox" style="display:none">
<script>
</script>
<p>Create Order
<p><?php
$timestamp=time(); require_once 'start.php';
?>
<form method="post" name="formSubmitted" **return false;"**>
<input type="hidden" name="formSubmitted" value="true" runat="server">
<?php echo $message; ?>
<?php ?>
<?php if ($haveErrors || $userArriveByClickingOrDirectlyTypeURL) : ?>
<fieldset>
<p>Symbol : <select name = "selection" id="selection">
<option disabled = "disabled" selected = "selected"> Choose one </option>
<option value="eur/usd"<?php If($selection=='eur/usd'){Echo 'selected';}?>>EUR/USD</option>
<option value="usd/jpy"<?php If($selection=='usd/jpy'){Echo 'selected';}?>>USD/JPY</option>
<option value="usd/cad"<?php If($selection=='usd/cad'){Echo 'selected';}?>>USD/CAD</option>
<option value="eur/jpy"<?php If($selection=='eur/jpy'){Echo 'selected';}?>>EUR/JPY</option>
<option value="eur/chf"<?php If($selection=='eur/chf'){Echo 'selected';}?>>EUR/CHF</option>
<option value="gbp/usd"<?php If($selection=='gbp/usd'){Echo 'selected';}?>>GBP/USD</option>
<option value="aud/usd"<?php If($selection=='aud/usd'){Echo 'selected';}?>>AUD/USD</option>
<option value="usd/chf"<?php If($selection=='usd/chf'){Echo 'selected';}?>>USD/CHF</option>
</select><font color="red"><?php echo $selectionError?></font>
<p> Date : <input type="datetime" value="<?php echo date("Y-m-d ",$timestamp); ?>"READONLY name="date"/></p>
<p> Type : <input type="radio" name="type" value="buy"<?php if ($type == 'buy') echo 'checked'; ?>CHECKED> Buy <input type="radio" name="type" value="sell" <?php if ($type == 'sell') echo 'checked'; ?>>Sell<font color="red"><?php echo $typeError;?></font></p>
<p> Size : <input type="number"pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"min="0"name="size"value="<?php echo $size;?>"/><font color="red"><?php echo $sizeError?></font></p>
<p> Bid Price (Sell) : <input id="bidprice" READONLY name="bidprice" type="text" value="<?php echo $bidprice;?>"/><font color="red"><?php echo $bidpriceError?></font></p>
<p> Offer Price (Buy) :<input id="offerprice" READONLY name="offerprice" type="text" value="<?php echo $offerprice;?>"/><font color="red"><?php echo $offerpriceError?></font> </p>
<p> Stop Loss : <input type="number"step="any"min="0" name="stoploss" value="<?php echo $stoploss;?>"/><font color="red"><?php echo $stoplossError?></font></p>
<p> Take Profit : <input type="number"step="any"min="0"name="takeprofit"value="<?php echo $takeprofit;?>"/><font color="red"><?php echo $takeprofitError?></font></p>
</fieldset>
<div align="center">
<input type="submit" value="Submit" Onsubmit =**"return false"**;/><button onmousedown="toggleOverlay()">Close </button>
</div>
<input type="reset" name="Reset" value="Reset" tabindex="50">
<?php endif; ?>
</form>
</script>
</body>
</html></p>
</div>
</div>
<!-- Start Special Centered Box -->
<!-- Start Normal Page Content -->
<div id="wrapper">
<h2>Trade</h2>
<button onmousedown="toggleOverlay();**return false;"**>Create Order</button>
</div>
<!-- End Normal Page Content -->
</body>
</html>
<?php
?>
Unless you are using AJAX, you can't really do this from PHP. Once a form submits, that's it. Simple validation can be done in the browser. Bind a validation function to your form's submit event. That's the thing you return false or true from.
(You would of course validate again on the server.)
It looks from your code like you're trying to run some php code (tradeformresult.php). Loading it this way isn't going to work as expected-that require_once will be run as the page is being built in PHP, not in the browser.
For sending a form without refreshing the page, you should look into AJAX (http://en.wikipedia.org/wiki/Ajax_(programming))
JQuery has a good AJAX method. Here is a simple example of how to use it:
$.ajax({url:"http://www.someserver.com/api/path",
data:{val1:"value",val2:"value"})
.success(function(returnData) {
console.log(returnData);
});
The above will call the given URL with the given data as parameters, then, if successful, will return whatever data the server gave back into the returnData variable.
If you're using AJAX, you don't really even have to use a <form> tag, since you'll be building the query string manually. You can have the function that makes the AJAX call be triggered from the onClick event of a button.

Persistent variables on a page in PHP

On a page I am working on, I have several distinct pieces of PHP, such as one in the head to handle dynamic Javascript and one in the main body for table creation. However, many of the operations, SQL queries, etc. are the same between the two area. For example, I keep having to reconnect to the same database over and over. Is there some way for me to streamline the code so that I do not need to have so much duplication and repeated calculation?
The page code, although it won't look right without the supplementary files. Also, it's very long.
<!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>Our Phones</title>
<style type="text/css">
<!--
#main #list table{
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 12px;
width: 750px;
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: none;
}
#float_tot {
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
color: #000;
background-color: #FFF;
overflow: auto;
position: fixed;
top: 127px;
height: 150px;
width: 198px;
border: 2px groove #999;
background-attachment: scroll;
}
.price {
font-size: 16px;
text-align: center;
}
.descr {
width: 300px;
}
-->
</style>
<?php
$con=mysql_connect(localhost,*****,*******);//connect to database
mysql_select_db("phone_site",$con);//select table
//work out the number of rows in the table
$query="SELECT * FROM phones WHERE 1=1";//set an always true WHERE
//search
$min=$_REQUEST['min_price'];
$max=$_REQUEST['max_price'];
$manuf=$_REQUEST['manufact'];
//if not empty, add them to the condition
if (!empty($min)){
$query.=" AND price>=$min";}
if (!empty($max)){
$query.=" AND price<=$max";}
if (!empty($manuf)){
$query.=" AND manu='$manuf'";}
$result=mysql_query($query);
$num=mysql_num_rows($result);
//prepare 2 substitutions
$pass=NULL;//this will fill in the correct number of input variables
$parse=NULL;//this will parse them into an array of ints.
$prices=NULL;//this will generate the pricelist
$i=0;
while($data = mysql_fetch_array($result)){
$parse.="D[$i]=parseInt(d$i);";
$pass.="d$i, ";
$prices.="P[$i]=" . $data['price'] . ";";
$i++;
}
$passd=substr_replace($pass,"",-2);
//make javascript
print("<script type=\"text/javascript\">
function total($passd){
var D=new Array();
$parse //parse the input into integers. if the field is blank 'NaN' should return.
var P=new Array();
$prices//prices.
var total = 0;//set total to zero.
for (i=0;i<$num;i++){
if (D[i]){//only do something if the field is not blank
total += D[i]*P[i];
}//add D[i] number of that item at P[i] Price to the total
}
document.output.readout.value= (total);//output
}
</script>");
mysql_close($con);
?>
<link href="format.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<img src="Images/Site/Banner.gif" width="1200" height="117" />
</div>
<div id="sidebar">
<img src="Images/Site/Home.gif" width="208" height="48" alt="Home" />
<img src="Images/Site/Phones.gif" width="208" height="58" alt="Phones" />
<img src="Images/Site/About.gif" width="208" height="51" alt="About" />
<img src="Images/Site/R_sibe_b.gif" width="208" height="56" />
</div>
<div id=endorse>
<?php
$quote=Null;
$sign=Null;
$afil=Null;
$con=mysql_connect(localhost,****,*******);//connect to database
mysql_select_db("phone_site",$con);//select table
$query="SELECT * FROM quotes ORDER BY Rand() LIMIT 1";//get one random row
$result=mysql_query($query);
$data = mysql_fetch_array($result);//get data from location $result
//print out text
print ("<p id=\"quote\">" . $data['quote'] . "</p>");
print ("<p id=\"ename\">" . $data['sign'] . "</p>");
print ("<p id=\"afill\">-- " . $data['afil'] . "</p>");
mysql_close($con);//close connection
?>
</div>
<div id="main">
<?php
$con=mysql_connect(localhost,******,********);//connect to database
mysql_select_db("phone_site",$con);//select database
//make maufacturer search
$query="SELECT DISTINCT manu FROM phones";
$result=mysql_query($query);
$manl="<option value=''></option>";
while($data = mysql_fetch_array($result)){
$manl.="<option value=\"" . $data['manu'] . "\">" . $data['manu'] . "</option>";
}
print "<form name=\"search\" action=\"phones.php\" method=\"post\">
Manufacturer?
<select name=\"manufact\">
$manl
</select> <br/>
What is your price range? $<input name=\"min_price\" type=\"text\" value =\"\" maxlength=\"6\" /> to $<input name=\"max_price\" type=\"text\" maxlength=\"6\" value=\"\"/>
<input type=\"submit\" name=\"seek\"/>
</form>
<hr/>
<div id=\"list\">
<form name=\"phonelist\">
<table><!--table populated using PHP/MYSQL-->
<tr>
<th> </th><th> </th><th>Features</th><th>Price</th>
</tr>";
$query="SELECT * FROM phones WHERE 1=1";//set an always true WHERE
//search
$min=$_REQUEST['min_price'];
$max=$_REQUEST['max_price'];
$manuf=$_REQUEST['manufact'];
//if not empty, add them to the condition
if (!empty($min)){
$query.=" AND price>=$min";}
if (!empty($max)){
$query.=" AND price<=$max";}
if (!empty($manuf)){
$query.=" AND manu='$manuf'";}
$result=mysql_query($query);
//work out the number of rows in the table
$num=mysql_num_rows($result);
//make the onkeyup list, giving it that many entries
$hold="total(";
for ($i=1;$i<=$num;$i++){
$hold.="phonelist.a$i.value, ";}
$pass= substr_replace($hold,")",-2);
//now print all the data in the table for population, subject to entered search strings
$count=0;
while($data = mysql_fetch_array($result)){//get data from location $result
$count++;
print("<tr>
<td><img src=\"Images/" . $data['image'] . "\" width=\"100\" /></td>
<td class=\"descr\">" . $data['blurb'] . "</td>
<td><ul>" . $data['features']. "</ul></td>
<td><span class=\"price\">\$" . $data['price'] . "</span><br/>
How many would you like? <br/>
<input name=\"a$count\" type=\"text\" maxlength=\"2\" onkeyup=\"$pass\" /></td>
</tr>");
}
mysql_close($con);
print "</table>
</form>
</div>";
?>
</div>
<div id="lside">
<div id="float_tot">
<p>Your current total is</p>
<br/>
<form name="output">
$<input name="readout" type="text" readonly="readonly" value="0"/>
</form>
</div>
</div>
<div id="footer">
<img src="Images/Site/footer.gif" width="1200" height="74" />
</div>
</body>
You can re-use variables over and over on a single page. This would be a good idea for at least the database connection. Define $con just once at the top of the page and use it multiple times. Just because you close your php tag (?>) doesnt mean you lost your variables.
For code re-use, I would take a look at defining functions for common code fragments. Ideally, you would create classes to encapsulate logic. For example, it is typical to have a database connection object (or framework) which encapsulates connecting, querying, etc.
You may benefit from taking a look at the Zend Framework. It is a great tool for learning PHP developers to see industry standards on how to do many of things you are asking.
http://framework.zend.com/docs/quickstart
There are several ways to reuse code in php. The most basic and powerful one is the concept of functions.

Categories