SQL database interaction - php

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.

Related

How to SELECT / QUERY multiple names from MySQL

Good day folks,
Please I'm trying to implement something simple but I'm not finding the proper solution in PHP. I would like to ask for some advises, please.
I have one list of servers in the Array/Vector called $lines, now I would like to SELECT each server name in a MySQL DB in order to collect additional infos.
Could you please give me ideas regarding how to do a loop from the server names in, to SELECT / QUERY each one ?
Thanks!!
<html>
<head>
</head>
<body>
<form name="form1" method="post">
<textarea rows="10" name="servers[]" cols="50" ></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$con=mysqli_connect("hostxxxx","userxxxx","xxxxxxxx","xxxxxxx");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["submit"]))
{
if(!empty($_POST["servers"]))
{
echo '<h4>You have selected the following Servers:</4><br>';
$submitted_array = array_keys($_POST["servers"]);
$lines = explode(PHP_EOL, $_POST["servers"][$submitted_array[0]]);
foreach($lines as $servers)
{
echo ($servers."<br>");
}
}
else
{
echo 'Please write something';
}
}
?>
</body>
</html>
I've got the result as I needed, I hope it can help:
<body>
<form name="form1" method="post">
<textarea rows="1000" name="servers[]" cols="100" style="width:300px;height:300px;"></textarea>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
$con=mysqli_connect("hostxxxxx:portxx","userx","passxx","msdb");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST["submit"]))
{
if(!empty($_POST["servers"]))
{
echo '<h4>You have selected the following Servers:</4><br>';
$submitted_array = array_keys($_POST["servers"]);
//BREAKING IN AN ARRAY
$lines = explode(PHP_EOL, $_POST["servers"][$submitted_array[0]]);
//foreach($lines as $servers)
//{
//echo ($servers."<br>");
//}
//REMOVING BLANK SPACES:
function trim_value(&$value)
{
$value = trim($value);
}
//ADDING QUOTES BETWEEN THE VALUES
function add_quotes($str) {
return sprintf("'%s'", $str);
}
//REMOVING BLANK LINES
array_walk($lines, 'trim_value');
$VCSAC2 = "VCSAC2";
$LPAR = "LPAR";
$HOSTF = "HOSTF";
$CLASSG = "CLASSG";
$IP = "IP";
$STATUS = "STATUS";
//USING IMPLODE
//$sql=sprintf("SELECT * FROM main WHERE HOSTF IN (".implode(',', $lines).")");
$sql=sprintf("SELECT * FROM main WHERE HOSTF IN (".implode(',', array_map('add_quotes',$lines)).")");
//USED TO CHECK SQL SINTAX
//echo $sql;
$result=mysqli_query($con,$sql);
}
else
{
echo 'Please write something';
}
}
?>
<table id="demo1" cellpadding="0" cellspacing="0" style="width:100%" style="font-size:13px">
<thead>
<tr>
<th align=left>HostName</th>
<th align=left>VCS</th>
<th align=left>LPAR</th>
<th align=left>IP</th>
<th align=left>Class</th>
</tr>
</thead>
<?php while($dado = mysqli_fetch_array($result)) {?>
<tbody>
<tr>
<td align=left style="font-size:14px"><?php echo $dado[$HOSTF]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$VCSAC2]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$LPAR]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$IP]; ?></td>
<td align=left style="font-size:14px"><?php echo $dado[$CLASSG]; ?></td>
</tr>
</tbody>
<?php } ?>
</table> <br><br>
</body>

Problems in displaying mysql data into text field in php

Okay so, on this page, i want to do an update. Supposed the page shows/displays the data from mysql into the text fields after i click edit on the view page. But the data seemed can't be pulled into the text fields. Here's my codes for parcelEdit.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Updating Parcel Details</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<?php
include('db.php');
if(isset($_POST['update']))
{
$parcelID = $_POST['parcelID'];
$owner = $_POST['owner'];
$rcv_date = $_POST['rcv_date'];
$pck_date = $_POST['pck_date'];
$status = $_POST['status'];
// checking empty fields
if (empty($parcelID) || empty($owner) || empty($rcv_date)||
empty($pck_date)|| empty($status)) {
if(empty($parcelID)) {
echo "<font color='red'>Parcel ID field is empty.</font><br/>";
}
if(empty($owner)) {
echo "<font color='red'>Owner Name field is empty.</font><br/>";
}
if(empty($rcv_date)) {
echo "<font color='red'>Received Date field is empty.</font><br/>";
}
if(empty($pck_date)) {
echo "<font color='red'>Picked Up Date field is empty.</font><br/>";
}
if(empty($status)) {
echo "<font color='red'>Parcel Status field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysql_query("UPDATE parcel SET parcelOwner = '$owner',
dateReceived = '$rcv_date', datePickup = '$pck_date', parcelStatus =
'$status' WHERE parcelID='$parcelID'");
//redirectig to the display page. In our case, it is index.php
header("Location: parcelView.php");
}
}
?>
<?php
//getting id from url
if(isset($_GET['parcelID'])){
$parcelID = mysql_real_escape_string($_GET['parcelID']);
//selecting data associated with this particular id
$result = mysql_query("SELECT * FROM parcel WHERE parcelID='$parcelID'");
while($res = mysql_fetch_array($result))
{
//$mem_id= $res['mem_id'];
$parcelID= $res['parcelID'];
$owner= $res['parcelOwner'];
$rcv_date= $res['dateReceived'];
$pck_date= $res['datePickup'];
$status= $res['parcelStatus'];
}
} else {
$parcelID = '';
$owner = '';
$rcv_date = '';
$pck_date = '';
$status = '';
}
?>
<body>
<body style='background: url(mailbox.jpg)'>
<div align="center">
<h1>Update Parcel Details</h1>
<form method="post" enctype="multipart/form-data">
<table>
<tr>
<Td> PARCEL ID : </td>
<td><input name="parcelID" type="text" id="parcelID" value=<?php
echo $parcelID;?>></td>
</tr>
<tr>
<Td> OWNER : </td>
<td><input name="owner" type="text" id="owner" value=<?php echo
$owner;?>></td>
</tr>
<tr>
<Td> DATE RECEIVED : </td>
<td><input name="rcv_date" type="text" id="rcv_date" value=<?php
echo $rcv_date;?>></td>
</tr>
<tr>
<Td> DATE PICKED UP : </td>
<td><input name="pck_date" type="text" id="pck_date" value=<?php
echo $pck_date;?>></td>
</tr>
<tr>
<Td> STATUS : </td>
<td><input name="status" type="text" id="status" value=<?php
echo $status;?>></td>
</tr>
<tr>
<Td colspan="2" align="center">
<input type="submit" value="Update Records" name="update"/>
</Td>
</tr>
</table>
</form>
</div>
</body>
</html>
And this is my parcelView.php codes
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>List of Parcels</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<?php
include('db.php');
include('paginate.php');
$select=mysql_query("SELECT * FROM parcel");
$i=1;
while($userrow=mysql_fetch_array($select))
{
$parcelID=$userrow['parcelID'];
$owner=$userrow['parcelOwner'];
$rcv_date=$userrow['dateReceived'];
$pck_date=$userrow['datePickup'];
$status=$userrow['parcelStatus'];
?>
<body>
<body style='background: url(homebg.jpg)'>
<div class="hdr1">
<h1>List Of Parcels</h1>
<table border="1" align="center" style="margin-top:50px;">
<tr style="background:#CCCCCC" height="30px"><th>ID</th><th>Owner</th
<th>Date Received</th><th>Date Picked Up</th>
<th>Status</th>
<th> </th><th> </th>
</tr>
</div>
<?php
$per_page = 5; // number of results to show per page
$result = mysql_query("SELECT * FROM parcel");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);//total pages we going to
have
//-------------if page is setcheck------------------//
if (isset($_GET['page']))
{
$page = intval($_GET['page']);
$show_page = $_GET['page']; //it will telles the current page
if ($show_page > 0 && $show_page <= $total_pages) {
$start = ($show_page - 1) * $per_page;
$end = $start + $per_page;
} else {
// error - show first set of results
$start = 0;
$end = $per_page;
}
} else {
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
if (isset($_GET['page'])){
$page = intval($_GET['page']);
$tpages=$total_pages;
if ($page <= 0)
$page = 1;
}
//$query=mysql_query("select * from users");
for ($i = $start; $i < $end; $i++)
{
if ($i == $total_results)
{
break;
}
?>
<tr>
<td><?php echo mysql_result($result, $i, 'parcelID');?></td>
<td><?php echo mysql_result($result, $i, 'parcelOwner');?></td>
<td><?php echo mysql_result($result, $i, 'dateReceived');?></td>
<td><?php echo mysql_result($result, $i, 'datePickup');?></td>
<td><?php echo mysql_result($result, $i, 'parcelStatus');?></td>
<td><a href="parcelEdit.php?email=<?php echo mysql_result($result, $i,
'parcelID');?>">Edit</a></td>
<td><a href="parcelDelete.php?email=<?php echo mysql_result($result, $i,
'parcelID');?>">Delete</a></td>
</tr>
<?php } ?>
<tr>
<td colspan="7">
<?php
$tpages=$total_pages;
$reload = "parcelView.php" . "?tpages=" . $tpages;
echo '<div class="pagination"><ul>';
if ($total_pages > 1) {
echo paginate($reload, $show_page, $total_pages);
}
echo "</ul></div>";
?>
</td>
</tr>
</table>
<?php } ?>
</body>
</html>
I don't know what/which to be fixed please help me as php is new to me i'm still adapting to it.
For edit you create link:
Edit
And in edit file you have:
$parcelID = mysql_real_escape_string($_GET['parcelID']);
Don't you really see that once you set email parameter and then you search for parcelID parameter ?
So your edit link should look:
Edit
ps: your view file is one big mess... you have:
<body>
<body style='background: url(homebg.jpg)'>
And you generate it in loop. You really should learn some basic html syntax first.

Create a simple pagination

Here's a screenshot of the page that I want to put a pagination Below is my code and I want to create a simple pagination. I tried some examples available in this site but unfortunately it doesn't work for me or I might have missed something in the code.
<?php
session_start();
$server = 'localhost';
$user = 'root';
$pass = 'root';
$connect = mysql_connect($server,$user,$pass)
or die(mysql_error());
$selectdb = mysql_select_db('des')
or die(mysql_error());
?>
<form method="post" name="action_form" action="admin2.php">
<div id="gallery1" class="lbGallery">
<table class="table" width="100%" cellpadding="10">
<tbody>
<?php
$allRecords = mysql_query('select * from cms ORDER BY id DESC limit 4');
if(is_resource($allRecords))
{
while($row = mysql_fetch_assoc($allRecords))
{
?>
<tr><ul>
<td width="30%"><li style="list-style:none"><a href="uploads/<?php echo $row['image'];?>"/><img src="uploads/<?php echo $row['image'];?>"/></li></td>
<td style="float:left; font-size:16px"><?php echo $row['name']; ?></td>
</ul>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</form>
Try this. What is does is:
create a contant $amount en a variable $offset
Create a link (next) with which sends the value of $offset back to the script
Catch the value in $_GET['offset'];
Add the value of $amount to $offset to create a new offset.
Run MySQL statement again with the new values for LIMIT
I didn't actualy test this code for typo's, but you'll get the general idea. Hope this is of any help.
(Best to use the new mysqli statement by te way).
<?php
$amount = 4;
if (!empty($_GET['offset']))
{
$offset = $_GET['offset'] + $amount;
}
else
{
$offset = 1;
}
$allRecords = mysql_query('select * from cms ORDER BY id DESC limit $amount,$offset');
if(is_resource($allRecords))
{
while($row = mysql_fetch_assoc($allRecords))
{
?>
<tr><ul>
<td width="30%"><li style="list-style:none"><a href="uploads/<?php echo $row['image'];?>"/><img src="uploads/<?php echo $row['image'];?>"/></li></td>
<td style="float:left; font-size:16px"><?php echo $row['name']; ?></td>
</ul>
</tr>
<tr>
<td colspan="2">
Next
</td>
</tr>
<?php
}
}
?>

Infinite scroll data pull

I have an infinite scroll scipt that is pulling data and displaying it just fine. However, I am finding that when you scroll down the data pull starts again at the beginning. Right now I have 8 rows for testing in the database to make it easy. My control to get the next data set does not seem to be working otherwise it would go to the next set of results?
//item per page
$limit = 5;
$page =(int)(!isset($_GET['p']))?1: $_GET['p'];
// sql query
$sqlContent="SELECT make, model, year, carid FROM cars";
//Query start point
$start =($page * $limit)- $limit;
$resContent=$DB_con->query($sqlContent);
$rows_returned= $resContent->rowCount();//->fetchColumn();
// query for page navigation
if( $rows_returned > ($page * $limit)){
$next =++$page;
}
$sqlContent = $sqlContent ." LIMIT $start, $limit";
$finalContent = $DB_con->query($sqlContent);
if($finalContent === false) {
trigger_error('Error: ' . $DB_con->error, E_USER_ERROR);
} else {
$rows_returned= $finalContent->rowCount();//->fetchColumn();
}
?>
then display the results:
<?php while($rowContent = $finalContent->fetch()) {
$year = $rowContent['year'];
$make = $rowContent['make'];
$model = $rowContent['model'];
?>
<div class="row">
<div class="ride"><?php echo "$year $make $model"; ?></div>
</div>
<?php } ?>
</div>
</div>
<!--page navigation-->
<?php if(isset($next)):?>
<div class="nav">
<a href='index.php?p=<?php echo $next?>'>Next</a>
</div>
<?php endif ?>
</div>
This is something that I adapted for PHP from my days as a classic-asp programmer.
It provides a nice counter along with First, Last, Next & Previous links.
First is your sql query with two select statements depending on the number of records you want to show per page AND the total number of records. (in case the number you want to show is actually larger than the number of records in the db).
<?php
require'connections/conn.php';
$maxRows_rsList = 10; // the number of records you want to show per page
$pageNum_rsList = 0;
if (isset($_GET['pageNum_rsList'])) {
$pageNum_rsList = $_GET['pageNum_rsList'];
}
$startRow_rsList = $pageNum_rsList * $maxRows_rsList;
$query_rsList = $conn->prepare("SELECT make, model, year, carid FROM cars");
$query_limit_rsList = $conn->prepare("SELECT make, model, year, carid FROM cars LIMIT $startRow_rsList, $maxRows_rsList");
$query_limit_rsList->execute();
$row_rsList = $query_limit_rsList->fetch(PDO::FETCH_ASSOC);
if (isset($_GET['totalRows_rsList'])) {
$totalRows_rsList = $_GET['totalRows_rsList'];
} else {
$all_rsList = $query_rsList->execute();
$totalRows_rsList = $query_rsList->rowCount();
}
$totalPages_rsList = ceil($totalRows_rsList/$maxRows_rsList)-1;
$queryString_rsList = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_rsList") == false &&
stristr($param, "totalRows_rsList") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_rsList = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_rsList = sprintf("&totalRows_rsList=%d%s", $totalRows_rsList, $queryString_rsList);
$currentPage = $_SERVER["PHP_SELF"]; // so we stay on the same page just changing the recordset data
?>
Then our output
<table cellpadding="5" cellspacing="0" border="0">
<?php if($totalRows_rsList > $maxRows_rsList) { ?>
<tr>
<td colspan="2"><?php echo ($startRow_rsList + 1) ?> to <?php echo min($startRow_rsList + $maxRows_rsList, $totalRows_rsList) ?> of <?php echo $totalRows_rsList ?> cars<br />
<table border="0">
<tr>
<?php if ($pageNum_rsList > 0) { // Show if not first page ?>
<td width="25" nowrap="nowrap">
First
</td>
<?php } // Show if not first page ?>
<?php if ($pageNum_rsList > 0) { // Show if not first page ?>
<td width="25" nowrap="nowrap">
Prev
</td>
<?php } // Show if not first page ?>
<?php if ($pageNum_rsList < $totalPages_rsList) { // Show if not last page ?>
<td width="25" nowrap="nowrap">
Next
</td>
<?php } // Show if not last page ?>
<?php if ($pageNum_rsList < $totalPages_rsList) { // Show if not last page ?>
<td width="25" nowrap="nowrap">
Last
</td>
<?php } // Show if not last page ?>
</tr>
</table></td>
</tr>
<?php } else if(($totalRows_rsList == $maxRows_rsList) || ($totalRows_rsList < $maxRows_rsList)) { ?>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2"><?php echo ($startRow_rsList + 1) ?> to <?php echo min($startRow_rsList + $maxRows_rsList, $totalRows_rsList) ?> of <?php echo $totalRows_rsList ?> cars<br /></td></tr>
<?php } ?>
<tr><td>
<?php do {
$year = $row_rsList['year'];
$make = $row_rsList['make'];
$model = $row_rsList['model'];
?>
<div class="row">
<div class="ride"><?php echo "$year $make $model"; ?></div>
</div>
<?php } while($row_rsList = $query_limit_rsList->fetch(PDO::FETCH_ASSOC)) ?>
</div>
</div>
</td></tr>
</table>
$page =(int)(!isset($_GET['p']))?1: $_GET['p'];
should actually be
$page =(!isset($_GET['p']))?1: (int)$_GET['p'];
what you are doing is casting the boolean result of isset as an integer

Disabling checkout button from shopping cart - php

I am trying to setup a “view shopping cart/basket” page within a site in which logged in users earn points/credits. Once they earn a certain amount of these points they can then go to a shopping cart and pay with these points only. (No money changes hands, so no paypal/checkout/shipping/taxes etc are involved)
So far I have got the login, points total table, add product to cart and change of quantity feature to work.
What I am trying to do on this ‘view_cart.php’ page (code below) is to make the ‘Checkout’ link (submit_cart.php) disappear or be disabled if the user's points total is less than the total shopping cart price. Is there anyway I can do this on this script?
The ‘You don’t have enough points to proceed to checkout’ prompt works if this is the case but if I can this checkout link to disappear that would be great.
My php knowledge is limited as I’m more of a front end designer but please feel free to offer any suggestions or changes of approach.
Thanks!
<?php
$page_title = 'Your Rewards Shopping Cart';
include ('./includes/header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
$rwp = $_SESSION['reward_user_points'];
$problem = FALSE;
if (isset($_POST['submitted']))
{
foreach ($_POST['qty'] as $k => $v) {
$pid = (int) $k;
$qty = (int) $v;
if ( $qty == 0 ) {
unset ($_SESSION['cart'][$pid]);
} elseif ( $qty > 0 ) {
$_SESSION['cart'][$pid] ['quantity'] = $qty;
}
} // End of FOREACH.
} // End of SUBMITTED IF.
$empty = TRUE;
if (isset ($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key =>$value) {
if (isset($value)) {
$empty = FALSE;
break; // Leave the loop.
}
} // End of FOREACH.
} // End of ISSET IF.
if (!$empty) {
require_once ('/MySQL/database.php');
$query = "SELECT users_id, reward_user_points FROM reward_points
WHERE reward_points.users_id = users.users_id";
$result = mysql_query($query);
$query = "SELECT products_id, products_name FROM categories, products
WHERE categories.categories_id = products.categories_id AND products.products_id
IN (";foreach ($_SESSION['cart'] as $pid =>$value) {
$query .= $pid . ',';
}
$query = substr ($query, 0, -1) . ') ORDER BY categories.categories_name ASC';
$result = mysql_query($query);
?>
<h1>Your Shopping Cart</h1>
<div id="sidebar">
<div id="statusbar">
<p><span class="statusbar_highlight">Name:</span><br />
<?php echo " {$_SESSION['users_first_name']} " . " {$_SESSION['users_surname']}<br> ";?></p>
<p><span class="statusbar_highlight">Outlet:</span><br />
<?php echo " {$_SESSION['users_outlet']} ";?></p>
<p><span class="statusbar_highlight">Sales Number:</span><br />
<?php echo " {$_SESSION['users_sales_no']} ";?></p>
<p><span class="statusbar_highlight">My Points:</span><br />
<font size="+1"><?php echo " {$_SESSION['reward_user_points']} ";?></font></p>
</div>
<br /><br /><br /><br /><br /><br /><br /><br />
</div>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php
echo '<table border="0" width="100%" cellspacing="1" cellpadding="5" align="center">
<tr class="top">
<td align="left" width="46%"><b>Reward Product</b></td>
<td align="right" width="18%"><b>Price</b></td>
<td align="center" width="16%"><b>Qty</b></td>
<td align="right" width="20%"><b>Sub Total</b></td>
</tr>
<form action="view_cart.php" method="post">';
$total = 0; // Total cost of the order.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// Total and subtotals.
$subtotal = $_SESSION['cart'][$row
['products_id']]['quantity'] *
$_SESSION['cart'][$row ['products_id']]['price'];
$total += $subtotal;
if ($rwp >= $total) {
}
else {
echo "You do not have enought points to proceed to checkout <br />";
}
// Print the row.
echo " <tr>
<td align=\"left\">{$row['products_name']}</td>
<td align=\"right\">{$_SESSION['cart'][$row['products_id']] ['price']} pts</td>
<td align=\"center\"><input type=\"text\" size=\"3\"
name=\"qty[{$row['products_id']}]\"
value=\"{$_SESSION['cart'][$row['products_id']]['quantity']}\" /></td>
<td align=\"right\">" . number_format ($subtotal) . " pts</td>
</tr>\n";
} // End of the WHILE loop.
mysql_close($dbc); // Close the database connection.
// products the footer, close the table, and the form.
echo ' <tr class="even">
<td colspan="3" align="right"><b> TOTAL:<b></td>
<td align="right"><b>' . number_format ($total) . ' pts </b></td>
</tr>
</table>
<br />
<div align="center"><input type="submit" name="submit"
value="Update" />
<input type="hidden" name="submitted"value="TRUE" />
</form><br /><br /></div>
<p><img src="images/but_continue.png" /></p>
<p><img src="images/but_checkout.png" /></p>';
} else {
echo '<h1>Shopping Cart</h1><p>Your cart is currently empty.</p>
<p><img src="images/but_continue.png" /></p>
<div id="maincontent_inner">
<div id="maincontent_inner2"> ';
}
?>
<br />
<p>
<span class="extras"><strong>Please Note the following:</strong><br />
1. To delete any item off your cart, simply type in '0' and click 'Update'<br />
2. To add in more than one item, simply click the desired amount and click 'Update'<br />
3. Your cart will be emptied upon logging out of your session<br />
</span></p>
</div>
</div>
</div>
</div>
<?php
include ('./includes/footer.html');
?>
It looks to me like you're darn close:
if ($rwp >= $total) {
echo '<button>Checkout</button>'; //Just put the code you want here
}
else {
echo "You do not have enought points to proceed to checkout <br />";
}
In your sample, these lines are in the while which will cause a problem. Just move them out to where you want this to display and you're on your way.
$str = '<tr class="even">
<td colspan="3" align="right"><b> TOTAL:<b></td>
<td align="right"><b>' . number_format ($total) . ' pts </b></td>
</tr>
</table>
<br />
<div align="center"><input type="submit" name="submit" value="Update" />
<input type="hidden" name="submitted"value="TRUE" />
</form><br /><br /></div>
<p><img src="images/but_continue.png" /></p>
<p><img src="images/but_checkout.png" /></p>';
if($rwp >= $total) {
$str .='<img src="images/but_checkout.png" /></p>';
}
else {
$str .='<p>You donnot have enough points to buy</p>';
}
echo $str;
Use the above code instead of the code bellow the following comment in your code
// products the footer, close the table, and the form.

Categories