I'm pretty new to scripting but I've been following code logic pretty well. I've got two working scripts (posted below,) one that posts a form to a mysql database and another the pulls up the information on a same page in a table. I'm having trouble finding help on the following things I want to accomplish.
1.) Sanitizing the form, I've been told it's very open to injection/other. The most people will submit is text, and I'd like for them to eventually be able to post html links that are called up and clickable by the second script.
2.) I want the callback script to sort the information so that the most recent post is on top. (can I create a new mysql column alongside category and contents called "date" that auto detects the date/time and uses it for sorting? I'd love to see some example code of that.
Here's the submit form
<html>
<div style="width: 330px; height: 130px; overflow: auto;">
<form STYLE="color: #f4d468;" action="send_post.php" method="post">
Category: <select STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" name="category">
<option value="category 1">category 1</option>
<option value="category 2">category 2</option>
<option value="category 3">category 3</option>
<option value="Other">Other</option>
</select> <br>
<textarea overflow: scroll; rows="4" cols="60" STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000; width:300px; height:80px; margin:0; padding:0;" name="contents"></textarea><br>
<input type="submit" STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" value="Create Log">
</form>
</div>
</html>
sendpost.php
<?php
//Connecting to sql db.
$connect=mysqli_connect("localhost","myuser","mypassword","mydb");
header("Location: http://mywebsite.com/myhomepage.php");
if (mysqli_connect_errno()) { echo "Fail"; } else { echo "Success"; }
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO mydbtable (category, contents)
VALUES ('$_POST[category]', '$_POST[contents]')");
?>
And the get php to call it back on the page
<?php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mydbtable");
echo "<table border='1'>
<tr>
<th>Category</th>
<th>Contents</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['contents'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Also in the cases of connecting with the $con=mysqli_connect command in two of the scripts, is that basically exposed? Can't someone just get to the php and see that information?
I really appreciate the help, very willing to read and learn the right way to do things!
These two questions will help you.
How can I prevent SQL injection in PHP?
How can I specify sql sort order in sql query
SELECT * FROM mydbtable ORDER BY date
And for having db passwords and connections in the open... typically people just include that php file (even though it doesn't make it any safer). However, if you have root access to your filing systems, you could put it in a high enough directory where it is above your htdocs, and it won't be accessible by url.
dbconnect.php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
index.php
include 'dbconnect.php';
However, this doesn't actually make it any safer, it only is convenient that you won't accidentally post your code with your password.
Related
I'm currently developing a simple web page that enables the user to: upload an image and a corresponding caption to a DB, let the user view the images and delete them.
I have already accomplished the first two with the following code:
<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); #$_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
// execute query
mysqli_query($db, $sql);
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Di algo de esta imagen ^^"></textarea>
</div>
<div>
<button type="submit" name="upload">Publicar</button>
</div>
</form>
</div>
</body>
</html>
It looks like this:
Now, the only part I'm missing is being able to delete an image (basically I only echo each image), how would you suggest for me to accomplish this, to make each item clickable and let's say, pop up a dialog or button to perform an action (delete from DB).
I really don't know much about PHP or CSS/HTML, any help would be much appreciated, Thank you!
Within this loop:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
Personally I would add an element to click on - like an 'x' or whatever - with a unique data attribute:
https://www.abeautifulsite.net/working-with-html5-data-attributes
You have to add the unique id of the image obviously, so you can let SQL know which row to delete... Like this:
echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';
Then I would link this class to an AJAX call to make an asynchronous request to the server and delete the image without reloading the page. It's not very hard.
An easier solution would be to create a new form in the loop, so you create multiple forms per image, add a hidden field with the image id in the form and make a submit button with the valeu 'delete' or simply 'x'.
The same way you created the check:
if (isset($_POST['upload'])) { ... }
You can create something like this:
if (isset($_POST['delete-image'])) { ... }
You will be carrying the image id value like a normal form input. And you can do whatever you want with it.
I would HIGHLY suggest you to look into how to work with jquery and ajax calls though.
Opening a dialogue and ask the user before he deletes an item will require that you either go another page for deletion or use javascript for this.
In both cases, you should somehow set an identifier for your image in your html-code.
I would suggest you give every image an id
'<img ... id="'.$yourImageId.'">'
or a data-attribute
'<img ... data-identifier="'.$yourImageId.'" >'
with that identifier.
First variant:
...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...
and on this delete-view-page, you just have a form that triggers your delete-code
<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->
The other way is not server side rendered.
You should give your Elements some class like "my-clickable-image".After that, you have a script on your page, that looks something like the following
<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});
// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
// return a function that adds a Pop Up to the page
// the Pop Up has approximately the code of the first options second page
// except that now, it must create and remove elements in javascript
return function createPopUp(){
removePopUp();
var popup = document.createElement("div");
popup.setAttribute("id","deletePopUp");
var deleteForm = document.createElement("form");
deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
var deleteContents = '<p> Do you want to delete this image? </p>'
+ '<button type="submit"> yes </button>'
+ '<button onclick="removePopUp()"> no </button>'
deleteForm.innerHTML = deleteContents;
document.body.appendChild()
}
}
// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
var existingPopUp = document.getElementById("deletePopUp");
if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>
<!-- just add some styling to make the popup show on top of the page -->
<style>
#deletePopUp{
width: 50vw;
height: 50vh;
position: absolute;
z-index: 1;
padding: 1em;
}
</style>
In this case, you just call the server to delete the image, not to show the delete form.
I would suggest the second one but stack overflow is not made for opinion based answers.
Regarding simple security:
It looks like your users could give titles or texts to images.
try what happens if a user gives a title like <bold>some title</title>
and guess what would happen if the title is <script>window.location.href="google.com"</script>
(XSS * hint hint *)
Regarding code structure:
If you want to do something like web development more often, think about separating your database accessing code, and your logic code from your php page template code, this is called 3 tier architecture and standard for bigger projects but i guess this is really just a first, short prototype or test.
What i'm trying to achieve is to link my already completed SQL table query to another SQL table query. So to give some more information we need to make a game for my school assignment. I'm making a little Pokemon battle game. I've queried my SQL table and it's giving me all the Pokemon_Type that it currently has in the table. I want users to be able to click on that table entry that's being displayed and then it queries the database again displaying information on that type. Here is the webpage in question. Don't judge my html skills xD. So as you can see atm there is the 'Electric' type so i'd like to be able to click on that and it refreshes the page and shows all the Pokemon that's associated with that type in the SQL table. Is this possible? and if so how?
Here is my code so far if you'd like to see it.
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px
}
</style>
<title>Pokemon Fight!</title>
<center>Pokemon Fight!</center>
</head>
<body>
Select your type!
<?php
require_once('../mysqli_connect.php');
$query = "SELECT pokemon_type FROM pokemon";
$response = #mysqli_query($dbc, $query);
if($response){
echo '<table align="left"
cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Pokemon Type</b></td></tr>';
while($row = mysqli_fetch_array($response)){
echo '<tr><td align="left">' .
$row['pokemon_type'] . '</td><td align="left"></td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</body>
</html>
the easiest is to create a link into you pokemon type label to another page passing your type id through href.
Look at this post, it's about what you want to do : PHP passing variable id through href
But using ajax would be better to load informations dynamically without reloading the page
I've tried the following code for inserting data into the database. The database is getting connected. But the data is not getting added to the database. I dont know where i have gone wrong. Can anyone help me with this?
<html>
<head>
<title>registration</title>
<meta charset="UTF-8">
<link href="site.css" rel="stylesheet">
<div align="center">
<link rel="stylesheet" href="mine.css"/>
<table border="0" align="center" style="border-spacing: 40px 20px;">
<align="center"> <td>
</head>
<body bgcolor=" #b3ffe0">
<style>
html {
font-family: "Lucida Sans", sans-serif;
}
ul li {display: block;position: relative;float: left;border:1px }
ul li a {display: block;text-decoration: none; white-space: nowrap;color:#fff;}
ul {
list-style-type: none;
padding: 2px ;
margin-left: auto;
background-color: #666;
}
li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 10px 20px;
text-decoration: none;
}
li a:hover, .dropdown:hover .dropbtn {
background-color: #111;
}
</style>
</head>
<body>
<form action="df1.php" method="post">
<ul>
<li><a class="active" href="df.html">Disease</a></li>
<li>Drug</li>
<li>Interaction</li>
Alternate Drug
</ul>
<div>
<table border="2" align="center" style="border-spacing: 40px 30px;">
<caption><strong>DISEASE DETAILS:</br></br></strong></caption></br></br>
<tr>
<td><center> Disease_ID
<select name="Day">
<option value="1">1</option>
<option value="2">2</option>
</select></center>
</td>
<td>Disease
<select name="DisType">
<option value="Select">Select</option>
<option value="Acute">Acute</option>
<option value="Chronic">Chronic</option>
<option value="Acquired">Acquired</option>
</select>
</td>
<td>SubDisease
<select name="DisType">
<option value="Select">Select</option>
<option value="Acute">Acute</option>
<option value="Chronic">Chronic</option>
</select>
</td>
<td>Associated_Disease<input type="text" name="DisDu"></td>
</tr>
<td>Ethinicity<select name="DisType">
<option value="Select">Indian</option>
<option value="Acute">European</option>
<option value="Chronic">oman</option>
<option value="Acquired">German</option>
</select>
</td>
<td>Source<textarea name="comments" cols="30" rows="4"></textarea><br></td>
</tr>
</table>
</div>
</br>
<div><center>
<input type="submit" name="submit">
</center></div></div>
</form>
<?php
if(isset($_POST['submit'])){
$conn = mysqli_connect('localhost','root','');
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
echo "DB Connected successfully";
mysqli_select_db("tool",$conn);
$sql="INSERT INTO disease (Disease_id, Disease,SubDisease, Associated_Disease, Ethinicity,Source)
VALUES ('$_POST[Disease_ID]', '$_POST[Disease]','$_POST[SubDisease]', '$_POST[Associated_Disease]','$_POST[Ethinicity]', '$_POST[Source]')";
mysqli_query($sql,$conn);
mysqli_close($conn);
}
?>
</body>
</html>
If you're ok with leaving yourself open to SQL injection and getting hacked, go ahead and follow this advice. If not, you better read up on prepared statements instead..
1) Unless your config file lists the database, you need to specify it in your constructor:
$conn = mysqli_connect('localhost','root','', 'myDatabaseName');
2) When using arrray indexes in a string you should wrap them in curlies:
$sql="INSERT INTO disease(Disease_id,Disease,SubDisease,Associated_Disease,Ethinicity,Source) VALUES ('{$_POST[Disease_ID]}','{$_POST[Disease]}','{$_POST[SubDisease]]','{$_POST[Associated_Disease]}','{$_POST[Ethinicity]}','{$_POST[Source]}')";
1) Disease_ID should be an auto-incremental primary index column in your MySQL so should not be referenced directly by the HTML output. When inserting a row in the database this value will be self-generating and unique.
2) Check your syntax. Your error log should be mysqli_error($conn) <== you need to specify the connection variable. This goes for most actions using MySQLi procedural. Ask yourself how does the command know which database to apply the action to?
3) mysqli_query($sql,$conn); This is the primary cause of your issue.
The correct syntax is:
mysqli_query($conn,$sql);
Read the manual.
4) $conn = mysqli_connect('localhost','root',''); should also reference the correct database, again, simple stuff - read the manual!
So:
mysqli_connect('localhost','root','', 'tool');
And delete your mysqli_select_db reference in the code.
5) Add mysqli_error to your query insert so:
mysqli_query($conn,$sql) or die("error: ".mysqli_error($conn));
6) Secondary Cause - Your form submits data with the name attribute, buy all your form data seems to be subitted with the same name, so the data is not being received by the PHP code:
Example:
<form method="post">
<input value="whatever" name="myName">
</form>
And PHP recieves:
$_POST['myName'] = "whatever";
You need to update your whole HTML form with this in mind as currently your PHP is referencing value which do not exis and your HTML form is only posting a few unique values.
your post indexes are wrong you can not use your drop down title in that, you need to use value of your name attribute of input field so $_POST['Day'] instead of $_POST['Disease_ID'], use $_POST['DisDu'] instead of $_POST[Associated_Disease] and so on for other inputs.
Beginner to PHP, so I am pretty sure this is a stupid question...but, was hoping someone can help me out.
I have a html/php form, which basically dynamically pulls in values from a DB for a dropdown.
//HTML/PHP (original page)
<div style="position: relative; float: left; width:236px; margin-right: 20px;">
<div id="variablebox" style="position: relative; float: left; width:215px; border: solid #0096D6; border-width: 1px; padding: 10px;">
<H2>Step 2: Select Variable Type</H2>
<form id="var" enctype="multipart/form-data">
<span style="float: left; margin-top:8px;">
<label class="fieldlabel"><span>Variable Type:</span></label></br>
<select id="variabletype" name="variabletype" class="selectfieldshadow">
<option value="">Select</option>
<?php
$list=mysqli_query($con, 'SELECT * FROM valuelist');
while($row_list=mysqli_fetch_array($list)){
?>
<option value="<?php echo $row_list['valuelistid']; ?>">
<?php echo $row_list['valuename']; ?>
</option>
<?php
}
?>
</select>
</span>
When this form is submitted, it basically submits to PHP file via AJAX and then return the same form to the screen within the same DIV.
//PHP Page
echo "<H2>Step 2: Select Variable Type</H2>";
echo "<form id='var' enctype='multipart/form-data'>";
echo "<span style='float: left; margin-top:8px;'>";
echo "<label class='fieldlabel'><span>Variable Type:</span></label></br>";
echo "<select id='variabletype' name='variabletype' class='selectfieldshadow'>";
echo "<option value=''>Select</option>";
echo "<?php";
echo "$list=mysqli_query($con, 'SELECT * FROM valuelist');";
echo "while($row_list=mysqli_fetch_array($list)){";
echo "?>";
echo "<option value="<?php echo $row_list['valuelistid']; ?>">";
echo "<?php echo $row_list['valuename']; ?>";
echo "</select>";
echo "</span>";
echo "<span style='position: relative; float: left; display: inline-block; margin-top: 7px; font: 12px Lucida Grande,Helvetica,Arial,Verdana,sans-serif; padding-right: 60px;'>";
echo "<p>Add Value Control Screenshot:</p>";
echo "<input id='controlimage' type='file' name='controlimage'>";
echo "</span>";
I keep getting errors with my output...T_Variable this and Exception that...my question is, am I going about doing this correctly? I mean, looking at my PHP file that will return content back to the original page, do I have to echo php tags so they work on the original page when returned? ie. echo "<?php" etc..
Any assistance would be much appreciated!
echo is used to output content. As it's currently written, you're just trying to display the PHP code. To execute it, you'll have to restructure your code as follows:
<!-- some HTML code -->
<?php
// display stuff
?>
<!-- continue with HTML -->
Well first of all, PHP is all rendered server-side. So that means returning PHP in an AJAX response doesn't make sense. It won't render on the client side.
Second of all, those echos look crazy too. There are several different ways to output large text like that. Personally, I like to just close the PHP tag and write it. So your second file could look like this instead:
// end all PHP for now
?>
<H2>Step 2: Select Variable Type</H2>
<form id='var' enctype='multipart/form-data'>
<span style='float: left; margin-top:8px;'>
...
<input id='controlimage' type='file' name='controlimage'>
</span>
<?php
// continue writing PHP here
Send PHP is a nonsens cause PHP is a Server side language (run on server and not on the client, the browser).
Why don't you run your PHP code in this script and return the result. (Just display it)
But, please, make us proud of our favorite language and its beginners:
Use mysqli_fetch_assoc() instead of mysqli_fetch_array()
Use only one echo to do a multiline display, PHP natively supports it.
Indent your code, you will really like how it's more readable.
Use jQuery, its AJAX methods and autocomplete widget. Somebody did the job for you. ;-)
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.