I'm creating an online game and I have a problem with updating some fields in database.
Here's the form and the php code.
<form method='post'>
<div style="float: left; width: 630px; color: white;">
<div style="float: left; width: 400px; background: #555; height: 20px;">
<?php
if ($row['Protected'] == 1)
{
?>
<img src="images/pass.png"></img>
<input type="password" name="pass" placeholder="Password" style="height: 18px;" />
<?php
}
echo("<input type='submit' name='enter' style='background: #555; text-decoration: underline;' value='$row[Name]' />");
?>
</div>
<div style="float: right; width: 229px; background: #555; margin-left: 1px; height: 20px;">
<?php
echo($row['NrPlayers']);
echo("/");
echo($row['MaxPlayers']);
echo(" Players");
?>
</div>
<div style="clear: both;">
<?php
echo($row['Descr']);
?>
</div>
<div style="background: #ccc; font-size: 13px; margin-bottom: 2px; color: black;">
<?php
echo($row['FName']);
echo(" ");
echo($row['LName']);
?>
</div>
<input type="hidden" name="id" value="<?php$row['Id_Room']?>" />
<input type="hidden" name="protect" value="<?php$row['Protected']?>" />
<input type="hidden" name="password" value="<?php$row['Pass']?>" />
<input type="hidden" name="nr" value="<?php$row['NrPlayers']?>" />
</div>
</form>
<?php
if (isset($_POST['enter']))
{
if ($_POST['protect'] == 1)
{
if ($_POST['pass'] == $_POST['password'])
{
$nr = $_POST['nr'] + 1;
mysql_query("upadte users set Id_Room = '$_POST[id]' where Id_User = '$_SESSION[id]'");
mysql_query("update rooms set NrPlayers = '$nr' where Id_Room = '$_POST[id]'");
header("Location: game.php");
}
else
{
?>
<span style="color: red; text-align: center;">The password you entered is incorrect.</span>
<?php
}
}
else
if (($_POST['protect'] == 0))
{*/
$nr = $_POST['nr'] + 1;
mysql_query("upadte users set Id_Room = '$_POST[id]' where Id_User = '$_SESSION[id]'");
mysql_query("update rooms set NrPlayers = '$nr' where Id_Room = '$_POST[id]'");
header("Location: game.php");
}
}
?>
There are two updates and one redirect. So, updates don't work but redirect does.
Step 1:
Submit the form to a template, then dump out all your values from the form scope to ensure your getting what you need through from the form.
Step 2:
Using some test values write your queries in a query editor like mysql work bench or php myAdmin so that you have working queries.
Step 3:
Write the code that generates your queries in php, but instead of executing it dump it out to screen. Do this until the outpu looks like the query you designed in the step 2.
Step 4:
Finish the page and execute the query, look out for typos, syntax errors and security holes. then dump out results from the query.
Things you need to check in your current code:
mysql_query("upadte users set Id_Room = '$_POST[id]' where Id_User = '$_SESSION[id]'");
Typos - 'upadte' , inline substition - Id_Room = '{$_POST['id']}'.
Always walk through thorough debugging steps before posting large amounts of code and asking for help.
Related
Hello guys I am working on a freelance project and I faced with a problem I added some php codes in order to change paragraph elements visibility. the paragraph element which has to appear when user entered wrong username or password however paragraph element appears all the time
PHP SECTION
<?php
session_start();
require "db.php";
if ( !empty($_POST)) {
extract($_POST) ;
if ( checkUser($id, $pass) ) {
echo '<style>#wrong-password {display:none;margin-bottom: 5%;padding: 5%;width: 280px;font-family: "Montserrat", sans-serif;font-size: 1em;border-radius: 8px;border: 1px solid #ced4da;background-color: rgb(255, 23, 23);color: white;text-align: center;margin-top: 0;}</style>';
// you are authenticated
// session_start() creates a random id called session id.
// and stores in a cookie.
$_SESSION["user"] = getUser($id) ;
if($_SESSION["user"]["userType"]=='normal'){
header("Location: Analyzes.php?id=$id") ;
exit ;
}else {
header("Location: index.php") ;
exit ;
}
}
echo '<style> #wrong-password{visibility:visible; margin-bottom: 5%;padding: 5%;width: 280px;font-family: "Montserrat", sans-serif;font-size: 1em;border-radius: 8px;border: 1px solid #ced4da;background-color: rgb(255, 23, 23);color: white;text-align: center;margin-top: 0;}</style>';
}
HTML SECTION
<div id="form-container">
<h2>Hoşgeldiniz! 😺</h2>
<form action="?" method="POST">
<input type="number" name="id" placeholder="Kullanıcı Numarası">
<br>
<input type="password" name ="pass" placeholder="Parola">
<p id="wrong-password">Kullanıcı Adı veya Parola Hatalı :(</p>
<button type="submit" title="Giriş Yap">Giriş Yap</button>
</form>
</div>
Thanks in advance:)
I have been struggling to figure out the mystery behind this.
Unable to POST form data when I add name to a particular input field. I been starring at the screen for hours to figure out what went wrong.
My Code goes as,
Form Page:
<form action="upload.php" method="POST">
<div class="customer_records">
<div class="customer_records_sub">
<input type="text" list="o_id" name="o_id[]" class="mb-2 mr-sm-2 o_id_input" placeholder="Order ID"
style="width: auto;padding: 10px 50px;display: inline-block;font-size: 16px;
border: 1px solid lightgray;border-radius:5px;vertical-align: text-bottom;background: none;">
<datalist id="o_id">
<?php
$sql_o_id = "SELECT DISTINCT(o_id) FROM quotes";
$result_o_id = $conn->query($sql_o_id);
if ($result_o_id->num_rows > 0) {
while($row_o_id = $result_o_id->fetch_assoc()) {
$o_id = $row_o_id["o_id"];
?>
<option value="<?= $o_id; ?>">
<?php } } else { } ?>
</datalist>
<div class="asins_visible_input mb-2 mr-sm-2"
style="width: auto;padding: 10px 50px;display: inline-block;font-size: 16px;
border: 1px solid lightgray;border-radius:5px;vertical-align: text-bottom;
background: none;height: 45px;min-width: 300px;" >
</div>
<br/>
<div class="asins_list" style="display:none;height: auto;overflow: auto;width: auto;
border: 1px solid lightgray;padding: 2%;border-radius: 5px;
margin-left: 24%;min-width: 400px;">
<?php
$sql_asin_id = "SELECT * FROM quotespos";
$result_asin_id = $conn->query($sql_asin_id);
if ($result_asin_id->num_rows > 0) {
while($row_asin_id = $result_asin_id->fetch_assoc()) {
$asin_id = $row_asin_id["id"];
$asin_p_id = $row_asin_id["p_id"];
$asin_o_id = $row_asin_id["o_id"];
if($asin_p_id == '' || $asin_p_id == NULL) {
$asin_p_id = '(BLANK)';
} else {
$asin_p_id = $asin_p_id;
}
?>
<div class="asin_id indi_asin_<?= $asin_o_id; ?>" style="display:none;padding-left:10px;">
<input type="checkbox" class="asins_input_checkbox" data-id="<?= $asin_id; ?>" data-pid="<?= $asin_p_id; ?>" style="display:inline-block;width: 20px;height: 20px;" />
<p style="display:inline-block;padding-top: 2px;font-size: 16px;vertical-align: super;"><?= $asin_p_id; ?></p>
<div class="asins_div_percentile"
style="diplay:inline-block;float:right;display:none;">
<i class="fa fa-chevron-right" aria-hidden="true"
style="margin-top: 9px;margin-left: 8px;font-size: 14px;"></i>
<input class="asins_div_percentile_input" name="tada"
style="width: 50px;margin-left: 30px;vertical-align: top;
border: 1px solid gray;font-size: 16px;
border-radius:5px;border:1px solid gray;text-align:center;"
type="text" placeholder="%" />
</div>
<br/>
</div>
<?php $sl++; } } else { } ?>
<input type="hidden" name="asins[]" class="asins_hidden_input" />
</div>
</div>
</div>
<input type="hidden" name="bywhom" value="0" />
<input type="hidden" name="date" value="06/12/201" />
<button type="submit" name="submit" class="btn btn-primary mb-2 expense_form_btn"
style="margin-top: 0.8%;font-size:16px;">Submit</button>
</form>
Upload.php page:
$date = $_POST["date"];
$bywhom = $_POST["bywhom"];
echo $bywhom;
In the above form page, forget the array and all, they all work perfectly fine the moment i remove the name tag from the input tag with class asins_div_percentile_input, But the moment I keep something inside the name tag of that asins_div_percentile_input input, form gets submitted but none of the values gets posted. not even the normal input tag values like date mentioned above.
I don't understand what went wrong. Hope I was clear.
Any help is greatly appreciated.
After thinking a bit, I found a way around. Instead of forcing it to send all the empty fields and then take only the fields which have values, I removed the empty fields from DOM at the time of submission.
$(".form_submit_btn").click(function() {
$(".form_submit_btn").prop("disabled", true);
$('.main_parent').find('.asins_input_checkbox').each(function () {
if($(this).prop("checked")) { } else {
$(this).parent().remove();
}
});
$("#add_expense_form").submit();
});
Works fine. Thanks to all who literally taught me a lot through this query. Appreciate your time.
I'm following through the PDF version on this URL: https://www.neodynamic.com/articles/Print-PDF-from-PHP-directly-to-default-printer-without-print-dialog/
I have managed to have it running. However, I noticed that it can only print one PDF file that is saved, using the $filePath = 'files/LoremIpsum.pdf'; under the PrintPDFController.php file. Is there a way of dynamically getting contents from a database that is output on say a table as follows:
<table id="WebClientPrint">
<tr><td>ONLY PRINT THIS PART AUTOMATICALLY</td></tr>
</table>
<input type="button" onclick="How to call Table ID i.e. WebClientPrint and the default printer" value="Print" />
This means that at button click, only the contents of the table should be printed out.
Hello I once used this type of printing and it helped me, only the window for choosing a printer will pop up.
function PrintDiv() {
var contents = document.getElementById("dvContents").innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title>DIV Contents</title>');
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
return false;
}
Use it like this
<body>
<form id="form1">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Sample code</span>
<hr />
<div id="dvContents" style="border: 1px dotted black; padding: 5px; width: 300px">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Hello,
<br />
This is <span style="color: #18B5F0">Mateo</span>.<br />
Hoping that you are enjoying my articles!</span>
</div>
<br />
<input type="button" onclick="PrintDiv();" value="Print" />
</form>
</body>
I hope it helps you.
I can't seem to get $_POST to work with my sql query. I have tried both mysql_query and PDO.
$newartist = $_POST['newartist']; // This doesn't work with PDO statement
//$newartist = 'Hubert De Lartigue'; // This works with PDO statement!
//$query = $DBH->prepare("SELECT * FROM artist WHERE artist =?"); // Original Method
//$query->bindValue(1, $newartist, PDO::PARAM_STR); // Original Method
$query = $DBH->prepare("SELECT * FROM artist WHERE artist = :newartist"); // Suggested Method
//$query->bindParam(':newartist', $newartist); // Suggested method, tested
$query->bindParam(':newartist', $newartist, PDO::PARAM_STR); // Suggested method
$query->execute();
//foreach ($query as $row) { // Switched to while loop so it can "fetch"
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$selectedartist = '<option value="'.$row['artist_id'].'" selected="selected">'.$row['artist'].'</option>';
}
I can however echo $_POST['newartist']; and it will correctly output the artist's name!
The form per request (NOTE: you have to click the + to submit an artist and newartist echos properly after submitting a new artist):
<div style="background: #270126; padding: 0 20px;" id="artist" >
<form method="post" style="width: 100%">
Artist: <select name="artist" style="width: 200px; background: black;" class="required">
<?php
if(!empty($_POST['newartist'])) {
echo $selectedartist;
} else {
echo '<option value="2" selected="selected">Unknown-Artist</option>
'.$theartist.'';
}
?></select> +</div>
<div style="background: #270126; padding: 0 20px;" id="addnewartist" >
<fieldset style="display: none;height: 35px;" id="artistnew">
Artist Name:
<input name="newartist" id="newartist" style="width: 200px; display:inline;" /> Artist URL:<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" style="display:inline;" />
</fieldset>
</div>
<fieldset id="artworknew" style="width: 100%;">
<div style="background: #270126; padding: 0 20px;">
Artwork Name: <input name="name" id="name" style="width: 300px;" />
</div>
<div style="background: #270126; padding: 0 20px;">
File Name: <input name="file" id="file" style="width: 300px" value=".jpg" /><br />
</div>
<div style="background: #270126; padding: 0 20px; height: 35px;">
Folder: <select name="folder" style="width: 200px; background: black;">
<option value="16">digitalart2</option>
<?=$thefolder;?></select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div></fieldset>
</form>
</div>
<?php
if ($_POST['addartist']) {
mysql_query("INSERT INTO `artist` ( `artist_id` , `artist`, `artist_url`)
VALUES (NULL , '".$_POST['newartist']. "', '".$_POST['artist_url']. "');") or die(mysql_error());
//echo '<meta http-equiv="refresh" content="0;url=?form=addart">';
}
if ($_POST['addartwork']) {
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
mysql_query("INSERT INTO `artwork` (`id`, `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($_POST['name'])."',
'".sql_inj_str($_POST['artist'])."',
'".sql_inj_str(htmlentities($_POST['file']))."',
'".sql_inj_str($_POST['folder'])."',
'".sql_inj_str($_POST['dt1'])."',
'1',
'".sql_inj_str($_POST['disabled'])."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}
include ('footer.php');
?>
I went through all the code you gave me. You have many bad html, css and javascript practices. It make your code hard to debug. I have improved your code and maybe if you can follow my logic and comments, you will figure out what's wrong with you code.
Basically, the code you showed me first is perfectly fine. The problem is with your design. You are entering null values for the id column instead of letting the database do it for you. You have a column for an artist_id and inserting in the artist there. Look at your database definitions to make sure that they have the correct structure and are getting the expected variables. Here is you code but made with good practices. If you can follow my code, you will find it easier to debug the problem.
<?php
/** I have re-wrote your code to give you a better way of writing code that makes it easier to debug**/
/**Store input fields as variables so I don't have to repeat certain things**/
$newartist = isset($_POST['newartist']) ? ($_POST['newartist']) : "Unkown Artist"; // either has a value or the value is Unknown Artist. Only has a value if the $_POST is set
$addartist = isset($_POST['addartist']) ? true : false; // the addartist has been posted or not
$addartwork = isset($_POST['addartwork']) ? true : false; // the addartwork has been posted or not
//This is for add new artist
if($addartist){
$newartist = isset($_POST['newartist']) ? $_POST['newartist'] :null;
$newartist = isset($_POST['artist_url']) ? $_POST['artist_url'] :null;
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
mysql_query("INSERT INTO `artist` ( `artist`, `artist_url`)
VALUES ('". $newartist . "', '". $artist_url . "');") or die(mysql_error());
}else{
$newartist = null;
$artist_url = null;
}
/// this is for adding artwork
if($addartwork){
$name = isset($_POST['name']) ? $_POST['name'] :null;
$artist = isset($_POST['artist']) ? $_POST['artist'] :null;
$file = isset($_POST['file']) ? htmlentities($_POST['file']) :null;
$folder = isset($_POST['folder']) ? $_POST['folder'] :null;
$dt1 = isset($_POST['dt1']) ? $_POST['dt1'] :null;
$disabled = isset($_POST['disabled']) ? 1 : 0;
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
//There is a problem with you artist_id column. The artist has a string value, and you have an id column in the database
//Also you have a sql_inj_str() function. I am guessing that you have difined this function somewhere.
mysql_query("INSERT INTO `artwork` ( `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($name)."',
'".sql_inj_str($artist)."',
'".sql_inj_str(htmlentities($file))."',
'".sql_inj_str($folder)."',
'".sql_inj_str($dt1)."',
'1',
'".sql_inj_str($disabled)."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}else{
$name = null;
$artist = null;
$file = null;
$folder = null;
$dt1 = null;
$disabled = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Query PDO</title>
<!-- Put the styles (CSS) seperate from the html, easier to maintain. You can just copy these styles into an external file and just link it-->
<style>
#artist {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
form {
width: 100%;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
select {
width: 200px;
/**background: black;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
a {
width: 15px;
font-size: 1.5em;
display:inline;
/**added a myself**/
text-decoration: none;
}
#addnewartist{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
fieldset#artistnew{
display: none;
height: 35px;
}
form #newartist {
width: 200px;
display:inline;
}
form .secondaryAction{
display:inline;
}
#artworknew{
width: 100%;
}
/** I now had no choice but to add in a few class names here**/
.ArtworkName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='name'] {
width: 300px;
}
.FileName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='file'] {
width: 300px;
}
.Folder {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
height: 35px;
}
select[name='folder'] {
width: 200px;
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
</style>
</head>
<body>
<form method="post">
<!-- move the div inside the form-->
<div id="artist" >
Artist:
<select name="artist" class="required">
<?php echo '<option value="' . $newartist . '" selected="selected">' . $newartist . '</option>'; ?>
</select>
<!--When the link is clicked it runs the doStyles function-->
+
<!-- get all the javascript out of the anchor tag. You can use jquery or external javscript but doing it this way is really really bad practice-->
<script>
// You can store this code in an external javscript file and embed it here
function doStyles(){
document.getElementById('artistnew').style.display='block';
document.getElementById('artworknew').style.display='none';
document.getElementById('artist').style.display='none';
}
</script>
</div>
<div id="addnewartist" >
<fieldset id="artistnew">
Artist Name:
<input name="newartist" id="newartist" />
Artist URL:
<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" />
</fieldset>
</div>
<fieldset id="artworknew" >
<div class="ArtworkName">
Artwork Name:
<input name="name" id="name" />
</div>
<div class="FileName">
File Name:
<input name="file" id="file" value=".jpg" /><br />
</div>
<div class="Folder">
Folder:
<select name="folder" >
<option value="16">digitalart2</option>
<?=$thefolder;?>
</select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div>
</fieldset>
</form>
</div>
</body>
</html>
Everything looks OK. Check you form again, and make sure the name attribute is correct. Also, if you are typing in the name on the search form, make sure you are taking care of the case sensitive. The name should match the name in the database.
Use bindParam
Try taking out the PDO::PARAM_STR for now.
Lastly try this:
$result = $query->execute();
and then use $result in the for each loop
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.