I'm learning AngularJS and wondered how I could get the PHP database results into an angular model. What I have:
<!DOCTYPE html>
<html data-ng-app="statsApp">
<head>
<title>Student Stats</title>
<script src="angular.min.js"></script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<?PHP
// Include dbcreds.inc for db info.
include('dbcreds.inc');
if(isset($_GET['fname']) && $_GET['fname'] !== "")
{
$lname = $_GET['fname'] . "%";
$sql = $conn->prepare("select * from students where fname like ?");
$sql->execute(array($lname));
$res = $sql->fetchAll();
$rownum = 0;
echo "\n <SCRIPT>";
echo "\n var model = [";
foreach($res as $r)
{
$rownum++;
echo "\n ";
print_r(json_encode(array("ID" => intval($r['id']),"FNAME" => $r['fname'],"LNAME" => $r['lname'],"GPA" => doubleval($r['gpa']))));
// Add a comma, if it's not the last datarow.
if($rownum < count($res))
{
echo ",";
}
}
echo "\n ];";
echo "\n ";
echo "\n var statsApp = angular.module(\"statsApp\",[]);";
echo "\n ";
echo "\n statsApp.controller(\"statsAppCtrl\", function (\$scope) {";
echo "\n \$scope.stats = model;";
echo "\n });";
echo "\n </SCRIPT>\n ";
}
?>
</head>
<body data-ng-controller="statsAppCtrl">
<div class="page-header">
<h2>
<span class="label label-default">{{ stats.length }}</SPAN>
</h2>
</div>
<div class="panel">
<table class="table table-striped">
<thead>
<TR>
<TH>ID</TH>
<TH>First Name</TH>
<TH>Last Name</TH>
<TH>GPA</TH>
</TR>
</thead>
<tbody>
<tr data-ng-repeat="stats_item in stats | orderBy:'ID'">
<td>{{ stats_item.ID }}</td>
<td>{{ stats_item.FNAME }}</td>
<td>{{ stats_item.LNAME }}</td>
<td>{{ stats_item.GPA }}</td>
</tr>
</tbody>
</table>
</div>
</body>
</HTML>
It seems to work ok, but I'm questioning whether I'm on the right track with this method of doing things. Thanks.
Basically you want to make a call to a separate php file, which runs the query and echos a JSON encoded array for the Angular request to use.
Here is an example fiddle of the Angular side: https://jsfiddle.net/cmnv20ps/
function StudentsService($http) {
var service = {
getStudents: getStudents
};
return service;
function getStudents(fname) {
return $http.get('students.php', {
params: {
fname: fname
}
}).then(function(response) {
return response.data;
});
}
}
function Controller(StudentsService) {
var vm = this;
StudentsService.getStudents('Ro').then(function(data) {
vm.students = data.students;
});
}
PHP Example:
$fname = $_GET["fname"];
$sql = $db->prepare("select * from students where fname like :fname");
$sql->execute(array("fname"=>"%" . $fname . "%"));
$res = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array("students"=>$res));
Related
I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>
I have been staring at this for literally two hours trying to fix it. Any help would be appreciated. For some reason the table isn't being loaded when the button is clicked.
Here's the relevant part of my head:
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
</head>
This is my table:
<div class="container">
<div class="midtxt">
<div id = "transactions-sav" style="margin-top: 0;">
<h2>Most Recent Transactions</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Time & Date</th>
<th>Account Type</th>
</tr>
</thead>
<tbody>
<div id="trans-div">
</div>
</tbody>
</table>
<hr />
</div>
</div>
<a class="btn light-blue waves-effect waves-light table-end" id="trans-more" style="margin-top: 35px;">Load More Transactions</a>
</div>
This is my Ajax transmitter:
<script>
$(document).ready(function() {
let transCount = 20;
$('#trans-more').on('click', function() {
transCount += 20;
console.log('click');
console.log(transCount);
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: <?php echo $_SESSION['user_id']; ?>}, function() {
console.log('callback');
});
});
console.log('test1');
});
</script>
This is my PHP script for generating the table. It is worth noting that initialize() starts a session.:
<?php
require_once 'dbc-stu.inc.php';
require_once 'initialize.inc.php';
require_once 'app/transactions/transhist.inc.php';
initialize();
initialize_secure();
//Import the count
$limit = $_POST['transNewCount'];
$userID = $_SESSION['user_id'];
$sql = "SELECT * FROM transactions WHERE trans_targetID ='$userID' ORDER BY trans_time DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $key => $value) {
if ($key === 'trans_time') {
$time = $value;
date_default_timezone_set("America/Los_Angeles");
$time = date("F j, Y, g:i a",$time);
} elseif ($key === 'trans_amount') {
$amnt = $value;
} elseif ($key ==='trans_targetID') {
$username = idToUsername($value);
} elseif ($key === 'trans_accType') {
$accType = $value;
}
}
echo '<td>' . $username . '</td>';
echo '<td>' . $amnt . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $accType . '</td>';
echo '</tr>';
}
Edit, thanks a lot everybody. I'm fairly new to the web development community, so it's cool to see everyone help out!
Remove div tag from tag and add id in tbody attribute as below.
<tbody id="trans-div"></tbody>
Put the php code<?php echo $_SESSION['user_id']; ?> inside a <script> tag into double quote as it's causing the SyntaxError which break` your script code.
That's why you are not able to view XHR into console
Try the following:
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: "<?php echo $_SESSION['user_id']; ?>"}, function() {
console.log('callback');
});
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!');
}
});
});
I want to merge $output and $output1 and then populate a HTML table.
This is my code:
<?php
$link = parse_ini_file(__DIR__ . '/config.ini', true);
include("connect.php");
$output = '';
$cnn = simplexml_load_file($link['cnn']);
$bbc = simplexml_load_file($link['bbc']);
foreach($cnn->channel->item as $item){
$title = $item->title;
$description = $item->description;
$url = $item->link;
$pubDate = $item->pubDate;
$title1 = str_replace("'","\'", $title);
$description1 = str_replace("'","\'", $description);
$output[]['title'] = $title;
$output[]['description'] = $description;
$output[]['url'] = $url;
$output[]['p_date'] = $pubDate;
$sql = mysql_query("INSERT IGNORE INTO tbl_daily_news_headlines (
title,
description,
url,
pub_date,
log_date)
VALUES (
'$title1',
'$description1',
'$url',
'$pubDate',
now())")
or die(mysql_error());
}
foreach ($bbc->channel->item as $bitem){
$bbtitle = $bitem->title;
$bbdescription = $bitem->description;
$bburl = $bitem->link;
$bbpubDate = $bitem->pubDate;
$bbtitle1 = str_replace("'", "\'", $bbtitle);
$bbdescription1 = str_replace("'", "\'", $bbdescription);
$output1[]['title'] = $bbtitle;
$output1[]['description'] = $bbdescription;
$output1[]['url'] = $bburl;
$output1[]['p_date'] = $bbpubDate;
$sql = mysql_query("INSERT IGNORE INTO tbl_daily_news_headlines(
title,
description,
url,
pub_date,
log_date)
VALUES(
'$bbtitle1',
'$bbdescription1',
'$bburl',
'$bbpubDate',now())")
or die(mysql_error());
$final_output = array_merge($output, $output1);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>Feed Example</title>
<link rel="stylesheet" type="text/css" href="media/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="media/css/dataTables.bootstrap.css">
<script type="text/javascript" language="javascript" src="media/js/jquery-1.12.0.min.js">
</script>
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js">
</script>
<script type="text/javascript" language="javascript" src="media/js/dataTables.bootstrap.js">
</script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
</head>
<body class="dt-example dt-example-bootstrap">
<div class="container">
<section>
<h1>FEED Test</h1>
<div class="info">
</div>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Publish Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Publish Date</th>
</tr>
</tfoot>
<tbody>
<? foreach($final_output as $data1)
{
echo '<td>'.$data1['title'].$data1['description'].$data1['url'].$data1['p_date'].'</td>';
}
?>
</tbody>
</table>
</div>
</section>
</body>
</html>
I tried array_merge() but it's not working.
I also tried:
$data = $output + $output1;
Where am I wrong, did I incorrectly place my loops?
EDIT:
So after i try array_merge($output,$output1); its just outputs just last element of array, second method is same
i just try to do some inner foreach like
<? foreach($output as $data)
{
foreach($output1 as $data1)
{
echo '<td>'.$data.$data1'</td>';
}
}
?>
but i got 500 error, so any ideas?
EDIT 2:
Thanks to Patrick i merge these 2 outputs but still cant get printed on table, if you look my updated code right now its print them in horizontally(Everything in 1 lane), how to get fixed?
The reason why you are only getting one element is because you are overwriting the previous value each time through your foreach loops. You need to create a new entry in your $output and $output1 arrays each time.
Instead of
$output['title'] = $title;
$output['description'] = $description;
$output['url'] = $url;
$output['p_date'] = $pubDate;
and
$output1['title'] = $bbtitle;
$output1['description'] = $bbdescription;
$output1['url'] = $bburl;
$output1['p_date'] = $bbpubDate;
You should have
$output[]['title'] = $title;
$output[]['description'] = $description;
$output[]['url'] = $url;
$output[]['p_date'] = $pubDate;
and
$output1[]['title'] = $bbtitle;
$output1[]['description'] = $bbdescription;
$output1[]['url'] = $bburl;
$output1[]['p_date'] = $bbpubDate;
for DataTables you want it in some sort of JSON format. Here's how I'd do it using what you have there, and quickly (untested)
<?php
$final_output = array_merge($output, $output1);
and HTML/Javascript
<script type="text/javascript">
var php_data = <?php echo json_encode($final_output); ?>
$("#example").DataTable({
data: php_data
});
</script>
<table id="example">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Publish Date</th>
<tr>
</thead>
</table>
However, a much nicer way to do this would be via ajax. Check the docs out for DataTables: https://www.datatables.net/examples/ajax/
and an example of how you might format your data if you don't use ajax:
https://www.datatables.net/examples/data_sources/js_array.html
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'