Can't retrieve data properly from database in php - php

I have two entries in tblStudentDetails having RollNo = 0 and 1
But whenever I try to retrieve the data from the database I always get the first record i.e. RollNo = 0
Here is my code:
<?php
unset($_SESSION['RollNo']);
unset($_SESSION['StudentName']);
unset($_SESSION['Course']);
include_once 'Includes/DBConnection.php';
//echo $_POST['txtRollNo'];
if ($_POST['btnSubmit'] == 'Submit')
{
if ($_POST['txtRollNo'] != '')
{
$query = "SELECT StudentName, Course FROM tblStudentDetails WHERE RollNo = '$_POST[txtRollNo]'";
$result = mysql_query($query);
$rowCount = mysql_num_rows($result);
if ($rowCount == 0)
{
echo "You have entered an incorrect roll No";
//header ('Location: index.php');
}
else
{
while ($row = mysql_fetch_assoc($result))
{
$StudentName = $row['StudentName'];
$Course = $row['Course'];
}
$_SESSION['RollNo'] = $_POST['txtRollNo'];
$_SESSION['StudentName'] = $StudentName;
$_SESSION['Course'] = $Course;
header ('Location: SelectedUserDetails.php');
}
}
else
{
echo "Please Enter Your Roll No.";
//header ('Location: index.php');
}
}
?>
<html>
<head>
<title>Online Exam</title>
<STYLE TYPE = "Text/CSS">
H1
{
Color : DodgerBlue;
Text-Align : Center
}
HR
{
Color : DodgerBlue
}
LABEL
{
Vertical-Align : Bottom;
Font-Size : 20
}
TR
{
Height : 30;
Background : White;
Color : Black;
Font-Size : 20
}
</STYLE>
</head>
<BODY BGCOLOR = "BLACK" TEXT = "WHITE">
<CENTER>
<TABLE ALIGN = "CENTER">
<TR>
<?php include 'Includes/header.html'; ?>
</TR>
<TR>
<TD>
<TABLE>
<TR>
<FORM NAME = "frmMain" METHOD = "POST" ACTION = "<?php echo $PHP_SELF ?>" enctype = "multipart/form-data">
<TD>
Enter your roll no. :
</TD>
<TD>
<INPUT TYPE = "TEXT" NAME = "txtRollNo" />
</TD>
<TD>
<INPUT TYPE = "SUBMIT" NAME = "btnSubmit" VALUE = "Submit" />
</TD>
</FORM>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</CENTER>
</BODY>
</html>
In SelectedUserPage I tried to check the value of $_SESSION['RollNo'] but it is always null.
Can anyone say what is the problem in the above code?

You have not started a session with session_start().

Related

While displaying updated values the $_GET return undefined index error but on normal redirection $_GET method give the correct values

This question may look similar but please understand my problem.In my update page I got confused with $_GET method. In my first page I gave a link to edit the table like this
index.php
<?php
include_once("db.php");
$result1 = mysqli_query($connect, "SELECT * FROM mrinsert WHERE userid='{$_SESSION['user_id']}'");
?>
<?php
while($res = mysqli_fetch_array($result1)) {
echo "<tr>";
echo "<td>".$res['bugta']."</td>";
echo "<td>".$res['releaseta']."</td>";
echo "<td>".$res['ccota']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
my mredit.php page displaying with existing values by using mrinsertid. but when try to update the values it giving error in this place:
<?php
//getting id from url
$mrinsertid = $_GET['mrinsertid']; //ERROR Undefined index
//selecting data associated with this particular id
$result = mysqli_query($connect, "SELECT * FROM mrinsert WHERE mrinsertid=$mrinsertid"); //WARNING in this line
while($res = mysqli_fetch_array($result))
{
$releaseta=$res['releaseta'];
$keyta=$res['keyta'];
$programleadsta=$res['programleadsta'];
$ccota=$res['ccota'];
$nextmilestonesta=$res['nextmilestonesta'];
$bugta=$res['bugta'];
$risksta=$res['risksta'];
$summaryta=$res['summaryta'];
?>
My whole mredit.php:
<?php
// including the database connection file
include_once("db.php");
if(isset($_POST['update']))
{
$mrinsertid = mysqli_real_escape_string($connect,$_POST['mrinsertid']);
$releaseta= mysqli_real_escape_string($connect,$_POST['releaseta']);
$keyta= mysqli_real_escape_string($connect,$_POST['keyta']);
$programleadsta= mysqli_real_escape_string($connect,$_POST['programleadsta']);
$ccota= mysqli_real_escape_string($connect,$_POST['ccota']);
$nextmilestonesta= mysqli_real_escape_string($connect,$_POST['nextmilestonesta']);
$bugta= mysqli_real_escape_string($connect,$_POST['bugta']);
$risksta= mysqli_real_escape_string($connect,$_POST['risksta']);
$summaryta= mysqli_real_escape_string($connect,$_POST['summaryta']);
// checking empty fields
if(empty($releaseta) || empty($keyta) || empty($programleadsta)||empty($ccota) || empty($nextmilestonesta) || empty($bugta)|| empty($riskta) || empty($summaryta)) {
if(empty($releaseta)) {
echo "<font color='red'>release field is empty.</font><br/>";
}
if(empty($keyta)) {
echo "<font color='red'>Akey field is empty.</font><br/>";
}
if(empty($programleadsta)) {
echo "<font color='red'>program field is empty.</font><br/>";
}
if(empty($ccota)) {
echo "<font color='red'>cco field is empty.</font><br/>";
}
if(empty($nextmilestonesta)) {
echo "<font color='red'>nextmilestone field is empty.</font><br/>";
}
if(empty($bugta)) {
echo "<font color='red'>bug field is empty.</font><br/>";
}
if(empty($risksta)) {
echo "<font color='red'>risk field is empty.</font><br/>";
}
if(empty($summaryta)) {
echo "<font color='red'>summary field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($connect, "UPDATE mrinsert SET releaseta='$releaseta',keyta='$keyta',programleadsta='$programleadsta',ccota='$ccota',nextmilestonesta='$nextmilestonesta',bugta='$bugta',risksta='$risksta',summaryta='$summaryta' WHERE mrinsertid='$mrinsertid'");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$mrinsertid = $_GET['mrinsertid'];
//selecting data associated with this particular id
$result = mysqli_query($connect, "SELECT * FROM mrinsert WHERE mrinsertid=$mrinsertid");
while($res = mysqli_fetch_array($result))
{
$releaseta=$res['releaseta'];
$keyta=$res['keyta'];
$programleadsta=$res['programleadsta'];
$ccota=$res['ccota'];
$nextmilestonesta=$res['nextmilestonesta'];
$bugta=$res['bugta'];
$risksta=$res['risksta'];
$summaryta=$res['summaryta'];
?>
<html>
<head>
<title>Edit Data</title>
</head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.wrap {
position:relative;
width:50px;
}
.wrap button {
border:5px solid;
position:absolute;
top:50px;
border-color:black;
border-radius: 50%;
margin-left:20px;
display:block;
height: 50px;
width: 50px;
background-color:green;
}
</style>
<body>
Home
<br/>
<form name="form1" method="post" action="mredit.php">
<input type="text" name="mrinsertid" value=<?php echo $_GET['mrinsertid'];?> >
<input type="submit" name="update" value="update">
<div id="MRtableDIV">
<table border="2">
<tr style="background-color:#80bfff">
<th style="width:8%"><center>Release</center></th>
<th style="width:5%"><center>Status</center></th>
<th style="width:6%"><center>Key</center></th>
<th style="width:15%"><center>Program Leads</center></th>
<th style="width:6%"><center>CCO Dates</center></th>
<th style="width:6%"><center>Next Milestones</center></th>
<th style="width:10%"><center>Bug Projection</center></th>
<th style="width:14%"><center>Risks</center></th>
<th style="width:20%"><center>Summary</center></th>
<tr>
<tr>
<tr>
<td><textarea name="releaseta" id="ReleaseTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff""><?php echo $res['releaseta'];?></textarea></td>
<td>
<div class="wrap">
<button id="button1" value = "button" style= "color:white" onclick="setColor('button1', '#101010')";></button>
</div>
<textarea name="" id="StatusTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"></textarea>
</td>
<td><textarea name="keyta" id="KeyTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"><?php echo $res['keyta'];?></textarea></td>
<td><textarea name="programleadsta" id="ProgramLeadsTA" style="width:100%;height:200px;;resize:none;background-color:#e6f2ff"><?php echo $res['programleadsta'];?></textarea></td>
<td><textarea name="ccota" id="CCOTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"><?php echo $res['ccota'];?></textarea></td>
<td><textarea name="nextmilestonesta" id="NextMilestonesTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"><?php echo $res['nextmilestonesta'];?></textarea></td>
<td><textarea name="bugta" id="BugTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"><?php echo $res['bugta'];?></textarea></td>
<td><textarea name="risksta" id="RisksTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"><?php echo $res['risksta'];?></textarea></td>
<td><textarea name="summaryta" id="SummaryTA" style="width:100%;height:200px;resize:none;background-color:#e6f2ff"><?php echo $res['summaryta'];?></textarea></td>
</tr>
</tr>
</table>
</div>
</form>
</body>
</html>
<?php
}
?>
Try this
I just remove the { } and added directly ".$_SESSION['user_id']; and store the query in the variable which is called as $result1.
$result1 = "SELECT * FROM mrinsert WHERE user_id=".$_SESSION['user_id'];
$result = mysqli_query($conn, $result1);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($res = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>".$res['bugta']."</td>";
echo "<td>".$res['releaseta']."</td>";
echo "<td>".$res['ccota']."</td>";
echo "<td><a href='mredit.php?mrinsertid=".$res['mrinsertid']."'>Edit</a></td>";
}
}
else {
echo "0 results";
}
mysqli_close($conn);
mredit.php
echo $mrinsertid = $_GET['mrinsertid'];
Remove the action part from the form and it will work fine. Between, don't forget to type-cast the value to integer before using it. Also, use prepare statements whenever you can.
The problem is that in the first call of "mredit.php" you are using a GET request since you clicked on a <a href> link. In this case your $_GET['mrinsertid'] will be set to the value set in the URL. In your second call of "myedit.php" you are using a POST request as defined in your form with the method="post" attribute. Therefore the value is not in $_GET[] but in $_POST[] instead.
There are several solutions how to fix this:
Use $_REQUEST instead of $_GET. The $_REQUEST array is a merge of the $_GET, $_POST and $_COOKIE array, so it doesn't matter when the value comes from the URL or from a HTML form (send via a POST request).
Change the method= attribute in your <form> tag to GET to send it as a GET request. However you usually don't do that as HTML forms should be send via a POST request for various reasons.
Add the mrinsertid value to the URL in the action= attribute of your <form> tag. This way the value of mrinsertid is in $_GET, but the form data will still be in $_POST.

How to delete a row of table on click of a button and respective data from database?

I have a table which contains chapters and a button in front of each chapter.
Now I want to delete a row when the delete button is clicked and also I want to fire a delete query to delete the row from database.
I tried 2 3 ways to delete a row from table, but its not getting delete.
<!doctype html>
<html>
<head>
<title>Chapters</title>
</head>
<body>
<style>
td {
text-align: left;
}
</style>
<script>
var par = $(this).parent().parent(); //tr
par.remove();
</script>
<table id="example" style="width:50%">
<tr>
<th><font size="5">Chapters</font></th>
</tr>
<?php
$dbh = new PDO('mysql:host=174.13.54;dbname=handbook', 'airman', 'airman');
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0)
{
foreach($results as $chapter)
{
if($chapter['type'] == 1)
{
$type = "SSgt";
}
elseif($chapter['type'] == 2)
{
$type = "TSgt";
}
elseif($chapter['type'] == 3)
{
$type = "MSgt";
}
?>
<tr>
<td><?php $chapter['id']; echo $chapter['title'];echo " " . "(" .$type.")";?></td>
<td><input type="button" value="Delete"></td>
</tr>
<?Php
}
?>
</table>
</body>
</html>
<?php
}
?>
How can I do this? Can anyone help please?
EDIT :
chapterDelete.php
<!doctype html>
<html>
<head>
<title>Chapters</title>
</head>
<form method="post" action="deleteChapter.php" enctype="multipart/form-data">
<body>
<style>
td {
text-align: left;
}
</style>
<table id="example" style="width:50%">
<tr>
<th><font size="5">Chapters</font></th>
</tr>
<?php
$dbh = new PDO('mysql:host="138.75.54;dbname=handbook', 'airman', 'airman12345');
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0)
{
foreach($results as $chapter)
{
if($chapter['type'] == 1)
{
$type = "SSgt";
}
elseif($chapter['type'] == 2)
{
$type = "TSgt";
}
elseif($chapter['type'] == 3)
{
$type = "MSgt";
}
?>
<tr>
<td><?php echo $chapter['title'];echo " " . "(" .$type.")";?></td>
<td><input type="button" class="removeRowButton" id = "<?php $chapter['id']?>" value="Delete"></td>
</tr>
<?Php
}
?>
</table>
</body>
</form>
</html>
<script
$('.removeRowButton').click(function(){
var rowID= $(this).attr('id');
$.get( "deleteChapter.php?rowID=" + rowID, function( error ) {
if(error == 0){
$('tr#' + rowID).remove();
}
else{
alert('MySQL error!');
}
});
});
</script>
<?php
}
?>
deleteChapter.php
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=138.75.54;dbname=handbook', 'airman', 'airman12345');
$stmt = $dbh->prepare("DELETE FROM `chapters` WHERE `rowID`= '" . $_GET["rowID"]);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($result) > 0)
{
echo 'row deleted';
}
else{
echo 'row could not delete';
}
?>
Nothing is happening on click of delete button.
EDIT 2 :
<!doctype html>
<html>
<head>
<title>Chapters</title>
</head>
<form method="post" action="chapterDelete.php" enctype="multipart/form-data">
<body>
<style>
td {
text-align: left;
}
</style>
<table id="example" style="width:50%">
<tr>
<th><font size="5">Chapters</font></th>
</tr>
<?php
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=1775.54;dbname=handbook', 'airman', 'airman');
$stmt = $dbh->prepare("SELECT * FROM chapters");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0)
{
foreach($results as $chapter)
{
if($chapter['type'] == 1)
{
$type = "SSgt";
}
elseif($chapter['type'] == 2)
{
$type = "TSgt";
}
elseif($chapter['type'] == 3)
{
$type = "MSgt";
}
?>
<tr>
<td><?php echo $chapter['title'];echo " " . "(" .$type.")";?></td>
<td><input type="button" onClick= "this.form.submit()" value="Delete<?php $chapter['id']?>"</input></td>
</tr>
<?Php
}
?>
</table>
</body>
</form>
</html>
<?php
}
function delete($id)
{
$dbh = new PDO('mysql:host=174.138.75.54;dbname=airman_handbook', 'airman', 'airman12345');
$stmt = $dbh->prepare("DELETE FROM `chapters` WHERE `id`= " . $id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($result) > 0)
{
echo 'row deleted';
}
else{
echo 'row could not delete';
}
}
?>
Can I do like this without using ajax? But it is not working .
You'll need to make an asynchronous (AJAX) call to a .php script that deletes the row from your MySQL table.
First, your table rows should have an ID set with a unique row number, and this number should also be an attribute of the button that is supposed to remove the row (so that we know which row to remove when we press the remove button):
<table>
<tr id="number">
<td>Data</td>
<td><button class="removeRowButton" id="number" value="Delete this row"></td>
</tr>
</table>
That way, you can interact with each row separately.
Your PHP file (e.g. "removerow.php") should look something like this:
// Connect to MySQL database
$error= 0;
$deleteRow= mysql_query("DELETE FROM `tablename` WHERE `rowID`= '" . $_GET["rowID"] . "';") or $error= 1;
echo($error);
And when you get a SUCCESS back, you'll remove the row from the visible HTML table using jQuery:
$('.removeRowButton').click(function(){
var rowID= $(this).attr('id');
$.get( "removerow.php?rowID=" + rowID, function( error ) {
if(error == 0){
$('tr#' + rowID).remove();
}
else{
alert('MySQL error!');
}
});
});

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.

how to search date field using php - mysqli

I'm having trouble searching the date field of mysql database.. I have a html form..that allows the user to choose 3 different ways to search the database.. field 1 is student_id, field 2 is lastname, field 3 is date. Well when i run the program and choose student id, I get the proper result back, when i do the same using last name I get the proper result back, but when i use date..I do not get any return. I happen to know what the result should be because i see it in the database..and besides that its the same data record as the student id, and last name. I think it might have something to do with format, but I can't figure it out..
I do not know aJax so please don't suggest ajax code right now.
here is the html code.
[code]
-- start javascript -->
<script type="text/javascript">
/*<![CDATA[ */
function check(){
if(document.lastname.last.value == "" || document.lastname.last.value == null)
{
alert("no last name entered");
return false;
}
}
function checkdate() {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
return false;
}
}
function fieldSwap(image){
var sb = document.getElementById('sb');
if(sb.value == ""){
sb.style.background = "url(images/"+image+") no-repeat";
}
}
function buttonSwap(image){
var sb = document.getElementById('sb');
sb.src = "images/"+image;
}
function validate(){
var x = document.information.search.value;
if (x.length<10 || x.length>10){
alert("student id is incorrect");
return false;
}
}
/*]]> */
</script>
<!-- end javascript -->
</head>
<body>
<div id="form_wrap"><!-- start form wrap -->
<div id="form_header">
</div>
<div id="form_body">
<p>Search for a certification request (Enter one of the following):</p>
<form action="search.php" method="POST" name="information" id="information" onsubmit="return(validate()or return(checkdate())">
<div class="field">
<select name="type">
<option value="student_id">Student ID</option>
<option value="last_name">Last name</option>
<option value="examDate">Exam date</option>
</select>
<input name="typeValue" value="" />
<input type="submit" value="Search" />
</form>
</div>
</div>
</div><!-- end form wrap -->
</body>
</html>
<form action = "" method = "POST">
<div class="field">
<label for = "first_name"> first_name</label>
<input type = "text" name = "first_name" id = "first_name">
</div>
<div class = "field">
<label for = "last_name"> last_name </label>
<input type ="text" name = "last_name" id = "last_name">
</div>
<div class = "field">
<label for = "bio"> bio </label>
<textarea name = "bio" id = "bio"></textarea>
</div>
<input type = "submit" value = "Insert">
</form>
[/code]
Here is the PHP code
[code]
$records = array();
$typeValue = $_REQUEST['typeValue'];
//If they did not enter a search term we give them an error
if ($typeValue == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// We perform a bit of filtering
//$typevalue = strtoupper($search);
$typeValue = strip_tags($typeValue);
$typeValue = trim ($typeValue);
$value = $_POST['typeValue'];
if($_POST['type'] == "student_id")
{
//Query with $value on student_id
if($result = $db->query("SELECT * FROM records WHERE student_id LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
elseif($_POST['type'] == "last_name")
{
//Query with $value on last_name
if($result = $db->query("SELECT * FROM records WHERE last_name LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
elseif($_POST['type'] == "examDate")
{
//Query with $value on date
if($result = $db->query("SELECT * FROM records WHERE examDate LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
//$anymatches=$result;
//if ($anymatches == 0 )
//{
//echo "Sorry, but we can not find an entry to match your query...<br><br>";
//}
//And we remind them what they searched for
//echo "<b>Results For:</b> " .$typeValue;
//}
?>
<!DOCTYPE html>
<html>
<style type="text/css">
th{text-align: left;}
table, th, td{ border: 1px solid black;}
</style>
<head>
<title>Search Result</title>
</head>
<body>
<h3> Results for <?php echo $typeValue ?> </h3>
<?php
if(!count($records)) {
echo 'No records';
} else {
?>
<table style="width:100%">>
<th>
<tr>
<th>student_id</th>
<th>First name</th>
<th>Last name</th>
<th>email</th>
<th>Major</th>
<th>Exam Name</th>
<th>Taken class</th>
<th>Prepare</th>
<th>MeasureUp Key</th>
<th>Exam Date</th>
<th>Request Made On</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r){
?>
<tr>
<td><?php echo $r->student_id; ?></td>
<td><?php echo $r->first_name; ?></td>
<td><?php echo $r->last_name; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->major; ?></td>
<td><?php echo $r->examName?></td>
<td><?php echo $r->taken_class; ?></td>
<td><?php echo $r->prepare; ?></td>
<td><?php echo $r->measureUpKey; ?></td>
<td><?php echo $r->examDate; ?></td>
<td><?php echo $r->request_made; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</html>
<html>
<head></head>
<body>
<br/>
Return to Search
</body>
</html>
[/code]
I Believe you are using like to get the Exam Dates for that session or month so you can use this
Using DATE_FORMAT function
SELECT * FROM records WHERE DATE_FORMAT(examDate, '%Y %m') = DATE_FORMAT('$typeValue', '%Y %m') ORDER BY examDate
or may be you are looking for a specific date than
SELECT * FROM records WHERE examDate = '$typeValue'

SQL database interaction

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.

Categories