im working on a page that populates a drop down menu, from an sql query to show vehicles that belong to a certain user. once a vehicle is selected it runs a function that opens a table with invoices tied to that vehicle. the problem is the number of invoices is rather large and i would like to use pagination to move forward and backwards through them. so far, it brings up the first page just fine. when i click next it gives me an error saying undefined index q and it also looses all my html formatting, most likely because in forwards to my getuser.php page. please take a look at my code and tell me what im doing wrong, ive been trying to get this to work for hours
source code for securedpage.php
<?php
include('config.inc');
include('func.inc.php');
include('db.inc.php');
$hostname = 'localhost'; // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname = 'ServiceHistoryDB'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
// Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
// This could be supplied by a user, for example
$username = $_SESSION['username'];
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM customers
WHERE username='%s'",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['CustNum'];
$custnum = $row['CustNum'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
<!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>Arndt Automotive</title>
<style type="text/css">
body {
background-image: url(Background.png);
}
</style>
</head>
<body>
<table width="1050" border="0" align="center">
<tr align="center">
<td><img src="Banner.png" width="1050" height="275" alt="Banner" /></td>
</tr>
</table>
<table width="1200" height="638" border="0" align="center" background="backgroundmaybe2.png" " style="background-repeat: no-repeat; background- position: center;>
<tr align="center">
<td><table width="1090" height="638" border="0" align="center">
<tr align="left">
<td width="225"><table width="225" height="638" border="0" id="Left">
<tr>
<td align="center" valign="top" background="backgroundtable1.png"><p> </p>
<p><img src="Home.png" width="170" height="30" alt="Home" /></p>
<p><img src="About Us.png" width="170" height="30" alt="About Us" /></p>
<p><img src="Services.png" width="170" height="30" alt="Services" /></p>
<p><img src="Recent Work.png" width="170" height="30" alt="Recent Work" /></p>
<p><img src="My Account.png" width="170" height="30" alt="My Account" /></p>
<p><img src="Contact Us.png" width="170" height="30" alt="Contact Us" /></p>
<p><img src="Promotions.png" width="170" height="30" alt="Promotions" /></p>
<p><img src="Location.png" width="170" height="30" alt="Location" /></p>
<p><img src="Hours.png" width="170" height="150" alt="Hours" /></p></td>
</tr>
</table></td>
<td width="125"> </td>
<td width="850"><table width="850" height="638" border="0" background="backgroundtable2.png" >
<tr>
<td align="center"><html>
<head>
<title></title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
<body>
<?php echo $username?></b>
<?php echo $custnum?></b>
<form>
<select name="dropdown" onChange="showUser(this.value)">
<?php query() ;
?>
</select>
<?php close() ?>
</form>
<div id="txtHint"><b>Invoice info will be listed here.</b></div></td>
<p>Logout</p>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
<table width="1050" height="275" border="0" align="center" background="Footer.png">
<tr>
<td><table width="950" border="0" align="center">
<tr>
<td width="256" align="left"><img src="AC Delco Logo.png" width="245" height="47" alt="AC Delco" /></td>
<td width="265" align="center"><img src="ASA Logo.png" width="248" height="115" alt="ASA" /></td>
<td width="141" align="center"><img src="ASE Logo.png" width="112" height="115" alt="ASE" /></td>
<td width="270"><img src="Jasper Logo.png" width="252" height="81" alt="Jasper" /></td>
</tr>
</table></td>
</tr>
</table>
<p> </p>
</body>
</html>
and this is the source code for getuser.php
<?PHP
// Connects to your Database
mysql_connect('localhost', 'root') or die(mysql_error());
mysql_select_db("ServiceHistoryDB") or die(mysql_error());
$q=$_GET["q"];
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM invoices") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 10;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM invoices WHERE CarNum = '".$q."' $max") or die(mysql_error());
//This is where you display your query results
echo "<table border='1'>
<tr>
<th>Date</th>
<th> Service </th>
</tr>";
while($info = mysql_fetch_array( $data_p ))
{ echo "<tr>";
echo "<td>" .date('M d Y', strtotime($info['Date'])) . "</td>";
echo "<td>" . $info['BriefDescription'] . "</td>";
echo "<br>";
echo "</tr>";
}
echo "</table>";
// This shows the user what page they are on, and the total number of pages
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
Try out this useful Jquery Plugin.
Jquery Plugin for data Table
Related
I have a dropdown that is populated by a column in my database. On selection, I want it to display any table results where the column is equal to the value selected in the dropdown. I can get the table headers to display whenever I select a value, but there is no other data that is displayed.
I am doing an echo $q and it is returning the correct value. So it seems to be getting the selected value and passing it to test1.php correctly, so I am guessing there has to be something wrong somewhere in my test1.php script.
How can I fix this so that the database rows that have a column, Product Report Code that are equal to the selection, are displayed?
HTML/PHP:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","test1.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<section id="rep_dropdown">
<select onchange="showUser(this.value)" name="users">
<option value="">Product Report Code</option>
<?php foreach($repcode->fetchAll() as $reportcode) { ?>
<option value="<?php echo $reportcode['Product Report Code'];?>"><?php echo $reportcode['Product Report Code'];?></option>
<?php } ?>
</select>
</section>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
test1.php:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<?php
$q = intval($_GET['q']);
echo $q;
$host="xxxxxxxxx";
$dbName="xxxxxxxxx";
$dbUser="xxxxxxxxxxxxxx";
$dbPass="xxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$sql="SELECT * FROM vProducts WHERE [Product Report Code] = '".$q."'";
$result = sqlsrv_query($dbh,$sql);
?>
<table id="skuTable" cellspacing="5" class="sortable">
<tr class="ui-widget-header">
<th style="display: none">Product ID</th>
<th class="skuRow">Major Category</th>
<th class="skuRow">Minor Category</th>
<th class="skuRow">Report Code</th>
<th class="skuRow">SKU</th>
<th class="skuRow">SKU Description</th>
<th class="skuRow">SKU Status</th>
<th class="skuRow">Create Date</th>
<th class="skuRow">Group ID</th>
<th class="sorttable_nosort">Edit</th>
</tr>
<?php while($row = sqlsrv_fetch_array($result)) { ?>
<tr class="Row" data-code="<?php echo $row['Product Report Code']?>">
<td style="display: none" class="prod_id" id="product_id-<?php echo intval ($row['Product_ID'])?>"><?php echo $row['Product_ID']?></td>
<td class="major_cat" id="major_cat-<?php echo intval ($row['Major Category'])?>"><?php echo $row['Major Category']?></td>
<td class="minor_cat" id="minor_cat-<?php echo intval ($row['Minor Category'])?>"><?php echo $row['Minor Category']?></td>
<td class="rep_code" id="rep_code-<?php echo intval ($row['Product Report Code'])?>" align="center"><?php echo $row['Product Report Code']?></td>
<td class="sku" id="sku-<?php echo intval ($row['SKU'])?>" align="center"><?php echo $row['SKU']?></td>
<td class="sku_desc" id="sku_desc-<?php echo intval ($row['SKU Description'])?>"><?php echo $row['SKU Description']?></td>
<td class="sku_status" id="sku_status-<?php echo intval ($row['SKU Status'])?>" align="center"><?php echo $row['SKU Status']?></td>
<td class="create_date" id="create_date-<?php echo intval ($row['Date'])?>" align="center"><?php echo $row['Date']?></td>
<td class="group_id" id="group_id-<?php echo intval ($row['Group_ID'])?>" align="center"><?php echo $row['Group_ID']?></td>
<td><input type="button" class="edit" name="edit" value="Edit" onclick="enable_value(this)"></td>
</tr>
<?php } ?>
</table>
</body>
</html>
i'm not sure if sql server accepts table columns names like this Product Report Code
if true , then there are a problem in your connection here ,
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$sql="SELECT * FROM vProducts WHERE [Product Report Code] = '".$q."'";
$result = sqlsrv_query($dbh,$sql);
you are using PDO extension with sqlsrv Extension , which are totally different .
you have to chose one way to connect to your database .
this is a full PDO example :
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$sql="SELECT * FROM vProducts WHERE [Product Report Code] = :placeholder";
$stm = $dbh->prepare($sql);
$result = $stm->execute(array("placeholder" => $q);
EDIT
you will also need to update this line :
<?php while($row = sqlsrv_fetch_array($result)) { ?>
to :
<?php while($row = $stm->fetch()) { ?>
i am getting Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at error
If i submit form data to a different file for processing, it works. But if i submit form data to the same page, it gives this error.
please suggst
<!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" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li>Catalog
<ul><li>Products</li>
<li>Bulk Upload</li>
</ul>
<div class="clear"></div>
</li>
<li>Purchase
</li>
<li>Customer Service
<ul>
<li>Contact Us</li>
<li>CS Panel</li>
</ul>
<div class="clear"></div>
</li>
<li>All Reports</li>
<li>Configuration
<ul> <li>Look and Feel </li>
<li>Business Details</li>
<li>CS Details</li>
<li>Emaqil Template</li>
<li>Domain and Analytics</li>
<li>Courier</li>
</ul>
<div class="clear"></div>
</li>
<li>Accounts
<ul><li>Ledgers</li>
<li>Account Details</li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
Here is the code for Display
<?php
require("includes/conn.php");
$sql = "select CategoryID, CategoryName, FileName, Status from Categories";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<table border='0' cellpadding='10'>";
echo "<tr><td> </td><td>Category ID</td><td>Category Name</td><td>Status</td><td>Edit</td><td>Delete</td></tr>";
echo "<tr><td> <img src=\"images/" . $row['FileName'] . "\" alt=\"\" /> </td>";
echo "<td>". $row['CategoryID'] . "</td>";
echo "<td>". $row['CategoryName'] . "</td>";
echo "<td>". $row['Status']. "</td>";
echo "<td> <a href= 'edit.php?CategoryID=" .$row['id']. "'> Edit </a></td>";
echo "<td> <a href= 'delete.php?CategoryID=" .$row['id']. "'> Edit </a></td>";
echo "</tr> </table>";
}
?>
Nothing is happening here. Please suggest
You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.
<?php
session_start();
?>
<!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" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li>Catalog
<ul><li>Products</li>
<li>Bulk Upload</li>
</ul>
<div class="clear"></div>
</li>
<li>Purchase
</li>
<li>Customer Service
<ul>
<li>Contact Us</li>
<li>CS Panel</li>
</ul>
<div class="clear"></div>
</li>
<li>All Reports</li>
<li>Configuration
<ul> <li>Look and Feel </li>
<li>Business Details</li>
<li>CS Details</li>
<li>Emaqil Template</li>
<li>Domain and Analytics</li>
<li>Courier</li>
</ul>
<div class="clear"></div>
</li>
<li>Accounts
<ul><li>Ledgers</li>
<li>Account Details</li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
I had the same issue, but my solution wasn't as obvious as the suggested ones. It turned out that my php-file was written in UTF-8, which caused issues. I copy/pasted the content of the entire file into a new php-file (Notepad++ tells me this is written in ANSI rather than UTF-8), and now it work flawlessly.
The answer is above by Ross.
Firstly, putting session_start() as the first line of code will mean that you cannot deserialise any objects correctly into session variables.
The reason for getting this issue is 99% likely to be trailing spaces at the end of your include files (yes - I know it sounds unlikely but just try it). The offending file is in the error message. I wanted to back up Ross answer which worked for me but this site is counter intuitive.
IGNORE the nonsense answers. Remove the trailing spaces, newlines etc... and all will be well. ROSS knows what he is talking about.
Putting session_start() at the top of your file DOES work but it isnt the correct solution.
replace session_start(); with #session_start(); in your code
This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.
To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).
The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:
include "header.php";
This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.
<?php
session_start();
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
use ob_start(); before session_start(); at top of your page like this
<?php
ob_start();
session_start();
For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:
<?php
require_once('mylib.php');
session_start();
?>
In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.
HTH
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session().
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line
Just replace session_start with this.
if (!session_id() && !headers_sent()) {
session_start();
}
You can put it anywhere, even at the end :)
Works fine for me. $_SESSION is accessible as well.
use session_start() at the top of the page.
for more details please read the link session_start
I was able to solve similar Warning: session_start(): Cannot send session cache limiter - headers already sent by just removing a space in front of the <?php tag.
It worked.
I had a website transferring from one host to another, it seemed to work fine on the old host but a few pages on the new host threw the error Warning: session_start(): Cannot send session cache limiter - headers already sent
while I always kept the
<?php
session_start();
at the top of the page no spaces and nothing inserted before
it really bugged me that I stared every page with the session opening, and it worked on some pages and run through a bug on others
I picked the pages that had the problems, backed them up, created new blank pages and simply copied and pasted the code as is, saved and uploaded and boom, problem gone!
this is something you guys may need to consider, it may have been the encoding of the page, or something, not sure the exact source of the problem, but here is a fix to look at in case you guys run into a similar problem
cheers!
In my case I had to set the file encoding without BOM.
This started for me when I redirected my site to https:// (for SSL Certificate). From my experience with this issue, the session_start() had to be before the browser saw any HTML code. For my example, I was using session_start() in nav.php to determine the options of the navigation bar. I ended up placing session_start() right after the php comments in the index.php file and every page which called nav.php. I was able to keep the php comments before session_start() but could not keep the HTML comments above the php.
Check any extra space before php tag.
I'm trying to use php with mysql. basically i've an index page where user fills a form and another page where all rows are displayed. i've checkboxes for each row for deleting the selected row/rows. i'm trying to create a new page (namely details) where it shows only the selected row.
I'm trying to use $_GET but i could not do it. maybe the syntax is wrong. any help is welcome.
here are the relative code parts:
display.php:
<?
require_once('auth.php');?>
<html>
<head>
<title>Goruntule</title>
<meta name="GENERATOR" content="Arachnophilia 4.0">
<meta name="FORMATTER" content="Arachnophilia 4.0">
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="checkboxForm">
<?
require "config.php"; // All database details will be included here
$page_name="display.php";
$start=$_GET['start']; // To take care global variable if OFF
if(!($start > 0)) { // This variable is set to zero for the first page
$start = 0;
}
$eu = ($start -0);
$limit = 10; // No of records to be shown per page.
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
// WE have to find out the number of records in our table. We will use this to break the pages
$query2=" SELECT * FROM table1 ";
$result2=mysql_query($query2);
echo mysql_error();
$nume=mysql_num_rows($result2);
/////// The variable nume above will store the total number of records in the table////
/////////// Now let us print the table headers ////////////////
$bgcolor="#f1f1f1";
echo "<TABLE width=80% align=center cellpadding=5 cellspacing=0> <tr>";
echo "<td bgcolor='dfdfdf' > <font face='arial,verdana,helvetica' color='#000000' size='2'>#</font></td>";
echo "<td bgcolor='dfdfdf' > <font face='arial,verdana,helvetica' color='#000000' size='2'>ID</font></td>";
echo "<td bgcolor='dfdfdf' > <font face='arial,verdana,helvetica' color='#000000' size='2'>Time</font></td>";
echo "</tr>";
////////////// Now let us start executing the query with variables $eu and $limit set at the top of the page///////////
$query=" SELECT * FROM table1 ORDER BY id DESC limit $eu, $limit ";
$result=mysql_query($query);
echo mysql_error();
//////////////// Now we will display the returned records in side the rows of the table/////////
while($rows = mysql_fetch_array($result))
{
if($bgcolor=='#f1f1f1'){$bgcolor='#ffffff';}
else{$bgcolor='#f1f1f1';}
echo "<tr>";
echo "<td><input name='checkbox[]' type='checkbox' value='" . $rows[id] . "'></td>";
echo "<td align=left bgcolor=$bgcolor id='title'> <font face='Verdana' size='1'>$rows[id]</font></td>";
echo "<td align=left bgcolor=$bgcolor id='title'> <font face='Verdana' size='1'>$rows[DateTime]</font></td>";
echo "<td>Details</td>";
//here is the problematic line i guess
echo "</tr>";
}
echo "</table>";
////////////////////////////// End of displaying the table with records ////////////////////////
///// Variables set for advance paging///////////
$p_limit=100; // This should be more than $limit and set to a value for whick links to be breaked
$p_f=$_GET['p_f']; // To take care global variable if OFF
if(!($p_f > 0)) { // This variable is set to zero for the first page
$p_f = 0;
}
$p_fwd=$p_f+$p_limit;
$p_back=$p_f-$p_limit;
//////////// End of variables for advance paging ///////////////
/////////////// Start the buttom links with Prev and next link with page numbers /////////////////
echo "<table align = 'center' width='50%'><tr><td align='left' width='20%'>";
if($p_f<>0){print "<a href='$page_name?start=$p_back&p_f=$p_back'><font face='Verdana' size='2'>PREV $p_limit</font></a>"; }
echo "</td><td align='left' width='10%'>";
//// if our variable $back is equal to 0 or more then only we will display the link to move back ////////
if($back >=0 and ($back >=$p_f)) {
print "<a href='$page_name?start=$back&p_f=$p_f'><font face='Verdana' size='2'>PREV</font></a>";
}
//////////////// Let us display the page links at center. We will not display the current page as a link ///////////
echo "</td><td align=center width='30%'>";
for($i=$p_f;$i < $nume and $i<($p_f+$p_limit);$i=$i+$limit){
if($i <> $eu){
$i2=$i+$p_f;
echo " <a href='$page_name?start=$i&p_f=$p_f'><font face='Verdana' size='2'>$i</font></a> ";
}
else { echo "<font face='Verdana' size='4' color=red>$i</font>";} /// Current page is not displayed as link and given font color red
}
echo "</td><td align='right' width='10%'>";
///////////// If we are not in the last page then Next link will be displayed. Here we check that /////
if($this1 < $nume and $this1 <($p_f+$p_limit)) {
print "<a href='$page_name?start=$next&p_f=$p_f'><font face='Verdana' size='2'>NEXT</font></a>";}
echo "</td><td align='right' width='20%'>";
if($p_fwd < $nume){
print "<a href='$page_name?start=$p_fwd&p_f=$p_fwd'><font face='Verdana' size='2'>NEXT $p_limit</font></a>";
}
echo "</td></tr></table>";
?>
<tr>
<td colspan="14" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete">
<form>
<INPUT TYPE="BUTTON" VALUE="Previous" ONCLICK="window.location.href='http://......../util'">
</FORM></td>
</tr>
<?php
$checkbox=$_POST['checkbox'];
if($_REQUEST['delete']=='Delete'){
foreach($checkbox as $id => $value)
{$sql="DELETE FROM table1 WHERE id='$value'";
$result = mysql_query($sql);
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=display.php\">";
}
}
?>
details
<?
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
detail.php
<?php
require_once('auth.php');
$host="localhost";
$username="";
$password="";
$db_name="";
$tbl_name="table1";
mysql_connect("$host", "$username", "$password")or die("Cannot connect ". mysql_error());
mysql_select_db("$db_name")or die("Cannot select DB ". mysql_error());
$num=$_GET['var1'];
$query = "SELECT * FROM table1 where id='$num'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result) or die(mysql_error());
?>
<table border="0" align="center" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="13" align="center" bgcolor="#FFFFFF"><strong>Bölge</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Time</strong></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF" align="center"><? echo $row['13']; ?></td>
<td bgcolor="#FFFFFF" align="center"><? echo $row['0']; ?></td>
</tr>
<tr>
<td colspan="14" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete">
<form>
<input type=button value="Close" onClick="javascript:window.close();">
</form>
</tr>
<?php
$checkbox=$_POST['checkbox'];
if($_REQUEST['delete']=='Delete'){
foreach($checkbox as $key=>$value)
{$sql="DELETE FROM $tbl_name WHERE id='$value'";
$result = mysql_query($sql);
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=display.php\">";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
<html><head><link href="loginmodule.css" rel="stylesheet" type="text/css" /></head></html>
As I've said, the only problem i'm guessing is with the syntax, or something small as i can echo the row when i gave the var1 a specific id.
I'm sorry if i'm reposting but i couldn't find an answer. Thanks!
Edit: I'm thinking of deleting checkbox parts and adding gif links in the while loop where users can delete, edit or detailed view of the corresponding row. seems easier i guess.
Make sure that the details link is within the while block.
<?php
while($rows = mysql_fetch_array($result)) {
echo 'Details';
}
?>
Looks like you should not be using double quotes.
<? echo "$rows[id]" ?>
Should be
<?php echo $rows[id]; ?>
I also suggest you use 'id' as the name of the get rather than 'var1'. 'var1' does not mean anything whereas 'id' makes more sense.
Details
It's because you are using $rows outside your while-loop. You have to put the
Details
inside the while loop.
//EDIT:
Alright, I've stripped your code to the very neccessary according to your problem. So don't just copy/paste the code, it probably won't work. But read it carefully, and I hope you get the idea and see what may be wrong with your code ;)
display.php
<?php
require_once('auth.php');
require "config.php";
$page_name="display.php";
$start = (isset($_GET['start']) && $_GET['start'] < 1) ? 0 : $_GET['start'];
$eu = ($start-0);
$limit = 10;
$query="SELECT * FROM table1 ORDER BY id DESC limit $eu, $limit";
$result=mysql_query($query);
echo mysql_error();
$i = 0; //counter for the bg-color
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="checkboxForm">
<table width="80%" align="center" cellpadding="5" cellspacing="0">
<?php while($rows = mysql_fetch_array($result)) :
$bgcolor = $i%2 == 0 ? '#ffffff' : '#f1f1f1';
?>
<tr>
<td>
<input name="checkbox[]" type="checkbox" value="<?php echo $rows['id']; ?>">
</td>
<td style="align: left; font-family: Verdana; font-size: 10px; background-color: <?php echo $bgcolor; ?>;" id="title">
<?php echo $rows['id']; ?>
</td>
<td style="align: left; font-family: Verdana; font-size: 10px; background-color: <?php echo $bgcolor; ?>;" id="date">
<?php echo $rows['DateTime']; ?>
</td>";
<td>
Details
</td>
</tr>
<?php endwhile; ?>
</table>
</form>
detail.php
<?php
require_once('auth.php');
$num= isset($_GET['var1']) ? $_GET['var1'] : '';
$query = "SELECT * FROM table1 where id='$num'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
?>
<form name="form1" method="post" action="">
<table border="0" align="center" cellspacing="1" cellpadding="0">
<input name="checkbox[]" type="checkbox" value="<? echo $rows['id']; ?>">
<? echo $row['13']; ?>
<? echo $row['0']; ?>
<input name="delete" type="submit" id="delete" value="Delete">
<button onClick="javascript:window.close();">Close</button>
</table>
</form>
And not only for security's sake, you should get more familiar with PHP and some design patterns before publishing your website.
I am making a database, which will interact with a SQL table.
What I have achieved so far:
Add rows to the table.
Delete rows from the table.
Search rows from the table.
Paginate the results.
What I need to achieve:
A log in prompt when a guest tries to
access the page.
In fact, I have successfully installed a log in script for it, but it seems to not work properly, here is the error:
Fatal error: Allowed memory size of
25165824 bytes exhausted (tried to
allocate 77824 bytes) in
/home/vol3/byethost12.com/b12_3598660/htdocs/coordbase/database.php on line 238
Now that I do not have permission to allow more memory from my host, I would need a way around this.
I have already tried separating the file into multiple pages, but it seems that it still tried to allocate the same amount of bytes.
Here is the file:
<?php
require_once('db.php'); // for database details
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require('../include/session.php');
if (!$session->isMember())
{
header("../resources.php");
}
else
{
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
$connect = mysql_connect($host,$username,$password) or die('<p class="error">Unable to connect to the database server at this time.</p>');
mysql_select_db($database,$connect) or die('<p class="error">Unable to connect to the database at this time.</p>');
require('../include/header.php');//Page Header
if($_GET['cmd'] == "delete")
{
echo "<center><h1>Delete</h1></center>";
if(isset($_POST['delete'])) {
$time = date("Y-m-d H:i:s");
$queryc = "DELETE FROM coords WHERE id=".$_GET['id'].";";
$resultc = mysql_unbuffered_query("$queryc") or die("Could not delete the selected base from the database at this time, please try again later.");
$sqls = "INSERT INTO reports SET ip='$ipaddress', date='$time';";
//run the query. if it fails, display error
$report = mysql_unbuffered_query("$sqls") or die("Could not add report to the database, but the base has been deleted successfully.");
echo "<center>The selected base has been deleted from the database successfully!<br>
<a href=http://www.teamdelta.byethost12.com/coordbase/database.php>Back to Main</a><br><br>
<font color=\"red\"><b>YOUR IP HAS BEEN LOGGED. ABUSE OF THIS SYSTEM WILL RESULT IN AN IP BAN!</b></font></center>";
}
else
{
$queryd = "SELECT * FROM coords WHERE id=".$_GET['id'].";";
$resultf = mysql_unbuffered_query("$queryd") or die('<p class="error">There was an unexpected error grabbing the base from the database.</p>');
?>
<center>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
</tr>
<?php
while ($rowa = mysql_fetch_array($resultf)) {
$id = stripslashes($rowa['id']);
$tag = stripslashes($rowa['tag']);
$guild = stripslashes($rowa['guild']);
$name = stripslashes($rowa['name']);
$base = stripslashes($rowa['base']);
$location = stripslashes($rowa['location']);
$comment = stripslashes($rowa['comment']);
$id = stripslashes($rowa['id']);
$econ = stripslashes($rowa['econ']);
$maxecon = stripslashes($rowa['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td></center></tr>');
}
?>
</table>
</table>
<b>Are you sure you wish to delete the selected base?</b>
<br>
<input type="button" value="Cancel" id="button1" name="button1"onclick="window.location.href='database.php';">
<form action="<?php $self ?>" name="deletefrm" method="post" align="right" valign="bottom" onsubmit="return validate();">
Confirm Delete<input type=checkbox name="confirm"><input type="submit" name="delete" value="Delete" />
</form>
</center>
<br>
<center><font color="red"><b>YOUR IP WILL BE LOGGED. ABUSE OF THIS SYSTEM WILL RESULT IN AN IP BAN!</b></font></center>
<?php
}
}
else
{
if(isset($_POST['add'])) {
?>
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Info«</font></b></center>
</td>
</tr>
<tr><!--info content-->
<td style="background: #222222;">
<?php
//fetch data
$data = strip_tags(mysql_real_escape_string($_POST['list']));
$comment = strip_tags(mysql_real_escape_string($_POST['comment']));
$data_lines = explode( "\\r\\n", $data );
$comment_lines = explode("\\r\\n", $comment);
for($i=0;$i<count($data_lines);$i++)
{
$data_fields = explode( ",", $data_lines[$i]);
$time = time();
$queryb = "INSERT INTO coords SET
tag='{$data_fields[0]}',
guild='{$data_fields[1]}',
name='{$data_fields[2]}',
base='{$data_fields[3]}',
econ='{$data_fields[5]}',
maxecon='{$data_fields[6]}',
location='{$data_fields[4]}',
comment='{$comment_lines[$i]}',
ipaddress='$ipaddress' ,
date='$time';";
// if it succeeds, display message
if (mysql_unbuffered_query($queryb))
{
echo('<p class="success">Successful posting of ['.$data_fields[3].']!</p>');
}
else
{
echo('<p class="error">Error could not post ['.$data_fields[3].'] to database!</p>');
}
}//end for loop
}//end if $_POST['add'] statement
?>
<?php
if (isset($_GET['cmd']) == "add"){
?>
<!--start inputbox-->
<center><table width="100%">
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Add«</font></b></center>
</td>
</tr>
<tr>
<td style="background: #222222;"><!-- at the bottom of the page, we display our comment form -->
<form action="<?php $self ?>" method="post" onsubmit="return valid(this)">
<table width="100%" border ="0" valign="top">
<tr>
<td>
List:
</td>
<td align="left">
<textarea name="list" rows="10" cols="70"></textarea>
</td>
<td valign="top">
<font color="red"><b>[Post list arranged like so!]</b></font><br>
<br>
E.G:<br>
<br>
(tag),(guild),(player,(base),(coordinates),(econ),(maxecon)<br>
~TD~,~Team Delta~,DarkLink,Base1,D03:56:21:11,101,101<br>
FARM,Guild896,player 5,Base #3,D69:62:89:10,98,135<br>
</td>
</tr>
</tr>
<td>
Comment:
</td>
<td>
<textarea name="comment" rows="10" cols="70"></textarea>
</td>
<td>
<font color="red"><b>[Post comments on a new line for each base!]</b></font><br>
E.G "PS 10/10 PR 10/10"<br>
"PR 5/5 DT 10/10"
</td>
<td>
<td>
</td>
<td valign="bottom" align="right">
<p>
<input type="submit" name="add" value="Add" />
</p>
</td>
</tr>
</table>
</form>
Back to Main
</td>
</tr>
</table></center>
<!--end input box-->
<?php
}
else
{
if (isset($_GET['search']) == "do"){
$title = "<center><h1>Results</h1>";
$search = stripslashes($_GET['searchterm']);
$asearch = trim($search);
$bsearch = strip_tags($asearch);
$csearch = mysql_real_escape_string($bsearch);
$types = "types of search";
switch ($_GET['type']){
case 'name':
$types = "name";
break;
case 'tag':
$types = "tag";
break;
case 'guild':
$types = "guild";
break;
default:
$types = "";
echo "<center><b>Please select a search type before continuing! You are being redirected, please wait.<br>
Click here, if you do not wish to wait.</b></center>";
header("Refresh: 5; url=http://www.teamdelta.byethost12.com/coordbase/database.php");
exit;
break;
}
$querya = "SELECT * FROM coords WHERE `{$types}` LIKE '%{$csearch}%' ORDER BY `{$types}`;";
$result = mysql_unbuffered_query("$querya") or die("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$querya}");
if (mysql_num_rows($result) < 1) {
echo $title;
echo "<b><center>We are sorry to announce that the search term provided: \"{$search}\", yielded no results. <br>"
."<hr>"
."New Search</center></b>";
exit;
}else {
echo $title;
?>
<b>for "<?php echo $search;?>".</b>
<hr>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
<td ><b>Delete</b></td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
$id = stripslashes($row['id']);
$tag = stripslashes($row['tag']);
$guild = stripslashes($row['guild']);
$name = stripslashes($row['name']);
$base = stripslashes($row['base']);
$location = stripslashes($row['location']);
$comment = stripslashes($row['comment']);
$id = stripslashes($row['id']);
$econ = stripslashes($row['econ']);
$maxecon = stripslashes($row['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td><td><a href=database.php?id='.$id.'&cmd=delete>Delete</a></td></center></tr>');
}
echo "New Search";
?>
</table>
</table>
<?php
}
}
else{
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM coords";
$result = mysql_unbuffered_query($sql, $connect) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
?>
</center>
<!--start inputbox-->
<center>
<table width="83%">
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Search«</font></b></center>
</td>
</tr>
<tr>
<td style="background: #222222;"><!-- at the bottom of the page, we display our comment form -->
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm" onsubmit="return valid(this)">
<table border ="0" width="100%">
<tr>
<td><center>
Search For: <input type="text" name="searchterm">
Player <input type="radio" name="type" value="name" checked> |
Guild Tag <input type="radio" name="type" value="tag"> |
Guild Name <input type="radio" name="type" value="guild">
<input type="hidden" name="search" value="do">
<input type="submit" value="Search">
Add new bases
</tr>
</center>
</td>
</tr>
</form>
</td>
</tr>
</table>
</center>
<!--end input box-->
<hr>
<center>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
<td ><b>Delete</b></td>
</tr>
<?php
$query = "SELECT * FROM coords ORDER BY `tag` ASC LIMIT $offset, $rowsperpage;";
$result = mysql_unbuffered_query("$query") or die('<p class="error">There was an unexpected error grabbing routes from the database.</p>');
// while we still have rows from the db, display them
while ($row = mysql_fetch_array($result)) {
$id = stripslashes($row['id']);
$tag = stripslashes($row['tag']);
$guild = stripslashes($row['guild']);
$name = stripslashes($row['name']);
$base = stripslashes($row['base']);
$location = stripslashes($row['location']);
$comment = stripslashes($row['comment']);
$id = stripslashes($row['id']);
$econ = stripslashes($row['econ']);
$maxecon = stripslashes($row['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td><td><a href=database.php?id='.$id.'&cmd=delete>Delete</a></td></center></tr>');
}
?>
</table>
</table>
<?php
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
}//end else of search
}//end else of add
}//end else of delete
?>
</center>
<?php
require('../include/footer.php');//Page footer
}
?>
This would be around line 238:
<?php
//fetch data
$data = strip_tags(mysql_real_escape_string($_POST['list']));
$comment = strip_tags(mysql_real_escape_string($_POST['comment']));
$data_lines = explode( "\\r\\n", $data );
$comment_lines = explode("\\r\\n", $comment);
for($i=0;$i<count($data_lines);$i++)
{
$data_fields = explode( ",", $data_lines[$i]);
$time = time();
$queryb = "INSERT INTO coords SET
tag='{$data_fields[0]}',
guild='{$data_fields[1]}',
name='{$data_fields[2]}',
base='{$data_fields[3]}',
econ='{$data_fields[5]}',
maxecon='{$data_fields[6]}',
location='{$data_fields[4]}',
comment='{$comment_lines[$i]}',
ipaddress='$ipaddress' ,
date='$time';";
// if it succeeds, display message
if (mysql_unbuffered_query($queryb))
{
echo('<p class="success">Successful posting of ['.$data_fields[3].']!</p>');
}
else
{
echo('<p class="error">Error could not post ['.$data_fields[3].'] to database!</p>');
}
}//end for loop
}//end if $_POST['add'] statement
?>
I have noticed that the memory exceeds the limit when I include session.php to my file.
The problem is that I need that file for my log in prompt to work.
Check for recursions, this code cannot possibly exhaust memory. Try adding echo's around the code.
I am new to php.
I made a member registration on login page and adm too. So inside admin I wanted to get the list of the members and delete the members I dont want. So I took the a code from a sample code for phone book from http://localhost/xamp and editted it to my requirement I am able to retrieve the members but unable to delete the members. See the code below:
<?php
require_once('auth.php');
require_once('../config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
?>
<html>
<head>
<meta name="author" content="Kai Oswald Seidler">
<link href="../loginmodule.css" rel="stylesheet" type="text/css">
<title></title>
</head>
<body>
<p>
<h2><?php echo "User list"; ?></h2>
<table border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#f87820">
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib1']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib2']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib3']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="50" height="6"><br><b><?php echo $TEXT['phonebook-attrib4']; ?></b></td>
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
</tr>
<?php
$firstname=$_REQUEST['firstname'];
$lastname=$_REQUEST['lastname'];
$phone=$_REQUEST['phone'];
if($_REQUEST['action']=="del")
{
$result=mysql_query("DELETE FROM members WHERE member_id={$_REQUEST['member_id']}");
}
$result=mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname");
$i = 0;
while($row = mysql_fetch_array($result)) {
if ($i > 0) {
echo "<tr valign='bottom'>";
echo "<td bgcolor='#ffffff' height='1' style='background-image:url(img/strichel.gif)' colspan='6'></td>";
echo "</tr>";
}
echo "<tr valign='middle'>";
echo "<td class='tabval'><img src='img/blank.gif' alt='' width='10' height='20'></td>";
echo "<td class='tabval'><b>".$row['lastname']."</b></td>";
echo "<td class='tabval'>".$row['firstname']." </td>";
echo "<td class='tabval'>".$row['member_id']." </td>";
echo "<td class='tabval'><a onclick=\"return confirm('".$TEXT['userlist-sure']."');\" href='userlist.php?action=del&member_1d=".$row['member_id']."'><span class='red'>[".$TEXT['userlist-button1']."]</span></a></td>";
echo "<td class='tabval'></td>";
echo "</tr>";
$i++;
}
echo "<tr valign='bottom'>";
echo "<td bgcolor='#fb7922' colspan='6'><img src='img/blank.gif' alt='' width='1' height='8'></td>";
echo "</tr>";
?>
</table>
</body>
</html>
I haven't editted it that properly and the looks in all.
Please help me in making it able to delete the members also.
I didn't understand what .$TEXT['userlist-button1'].,'".$TEXT['userlist-sure']. variables are?
I also want to include an approved and disapproved radio button in table for each members.
How can I do that?
Please if you can help me.
This should be a POST via a FORM not a href link (GET).
$TEXT is obviously an array holding the text you want printed.
You need to replace &member_1d in the href with a real & and a real i as &member_id.
$TEXT is an array contaning all the language strings for the selected language.
You find the strings defined unter /lang/yourlanguage.php
In general this is not a very good example to start coding with IMO.
But I think your app may start working, if you make sure, the language files and other include files are available and you change this &member_1d with &member_id
An example of a list of members with delete links:
$query = mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname");
if(mysql_num_row($query)!= 0){ //only continue if there are members in the database
while($row = mysql_fetch_assoc($query)){ //loop through each row in the database
$member_id = $row['member_id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo '<p>' . $firstname . ' - ' delete '</p>';
}
}
A simple script on delete_member.php to delete the member from the database.
if(isset($_GET['id'])){
$member_id = $_GET['id'];
$query = mysql_query("DELETE FROM members WHERE member_id='$member_id'");
echo '<p>This user was deleted from database</p>';
}
This code is only basic to give an example.
I would however prefer to use a simple form and $_POST for something like this instead of using $_GET which is very vulnerable in this kind of instance.
After getting the list of members use a form with input field to type the id you want to delete.