how to search date field using php - mysqli - php

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'

Related

PHP how to send and receive multiple choice box

I need suggestion.
I have an list of position from database, displayed in table and in the last table row is an option to select "TAK" - YES and "NIE" - NO, please tell me is it possible and if it, how to send and receive it all selected to "TAK" fields at file wypozyczalnia.php
<form action='wypozyczalnia.php' method='post'>
<table width="1000px" align="center" border="1">
<tr>
<th width="250px">Tytuł</th>
<th width="250px">Autor</th>
<th width="300px">Opis</th>
<th width="200px">Dostępność</th>
</tr>
<?php
//sprawdzanie czy taka zmienna jest ustawiona w sesji, jest to dla nowo wchodzących na stronę
if(isset($_SESSION['blad'])) echo $_SESSION['blad'];
//wyświetlanie wyników gdy zmienna ile zwróciła przynajmniej 1 rząd
if ($ile>=1)
{
//pętle wyświetlająca wszystkie zwrócone z zapytania wpisy
for ($i = 1; $i <= $ile; $i++)
{
//pobranie rzędu jako tablicę asocjacyjną
$row = mysqli_fetch_assoc($rezultat);
//przypisanie każdej kolumny do odpowiedniej zmiennej
$title = $row['title'];
$author = $row['author'];
$description = $row['description'];
$available = $row['available'];
echo
"<tr>
<td> ".$title." </td>
<td> ".$author." </td>
<td> ".$description." </td>
<td>";
if($available==1)
{
echo "TAK";
}
else
{
echo "NIE";
}
"</td>
</tr>";
if(isset($_SESSION['zalogowany']) && ($_SESSION['zalogowany']==true) && $available==1)
{
echo
"<select name='idksiazki[]' >
<option name='NIE'>NIE</option>
<option name='TAK'>TAK</option>
</select>";
}
}
}?>
</table>
<?php
if(isset($_SESSION['zalogowany']) && ($_SESSION['zalogowany']==true))
{
echo "<br /> <input type='submit' name='zapis' value='wypożyczam'></form>";
}
?>
</form>
At the moment you have multiple forms - one per table row, so each <select is inside its own form. You can't submit multiple forms at once from a HTML page. Also your existing forms seem to be missing the </form> tag so they will be invalid anyway.
Therefore, to be able to submit all the <select values at the same time, you need a single form, which has the entire table contained within it.
For example:
<form action='wypozyczalnia.php' method='post'>
<table>
<?php
if ($ile>=1)
{
//pętle wyświetlająca wszystkie zwrócone z zapytania wpisy
for ($i = 1; $i <= $ile; $i++)
{
//pobranie rzędu jako tablicę asocjacyjną
$row = mysqli_fetch_assoc($rezultat);
//przypisanie każdej kolumny do odpowiedniej zmiennej
$title = $row['title'];
$author = $row['author'];
$description = $row['description'];
$available = $row['available'];
echo
"<tr>
<th> ".$title." </th>
<th> ".$author." </th>
<th> ".$description." </th>
<th>";
if($available==1)
{
echo "TAK";
}
else
{
echo "NIE";
}
"</th>";
if(isset($_SESSION['zalogowany']) && ($_SESSION['zalogowany']==true) && $available==1)
{
echo "<th>
<select name='idksiazki[]' >
<option value=$i;>NIE</option>
<option value=$i;>TAK</option>
</select>
</th>";
}
echo "</tr>";
}
}
?>
</table>
</form>
P.S. A note about HTML semantics: <th> is mean to indicate a table heading, e.g. the title of a column, or the main heading within a row. It should not be used for every cell in your table. <td> is for normal table cells. If you wish to make the text bold, use CSS instead.

Delete row data from one table using check box and insert the deleted row data in another table

/*I have two table , 1st table name is bazar and 2nd table name is bazarduepayment having same columne name : sl,date,item,paid,due,remark. 'sl' is auto increment . Delete function is working perfectly . Someone please help me how to insert deleted row data in 2nd table 'bazarduepayment' Here below is code detail i wrote */
<?php
session_start();
include_once("rwdbconnection.php");
error_reporting(0);
if(isset($_POST['save']))
{
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++)
{
$del_id = $checkbox[$i];
mysqli_query($conn,"DELETE FROM bazar WHERE sl='".$del_id."'");
$message = "Data deleted successfully !";
}
}
$result = mysqli_query($conn,"SELECT * FROM bazar");
?>
<!DOCTYPE html>
<html>
<head>
<linkrel="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>
<title>Delete data</title>
</head>
<body>
<div>
<?php if(isset($message)) { echo $message; } ?>
</div>
<form method="post" action="">
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="checkAl"> Select All</th>
<th>Sl</th>
<th>Date</th>
<th>Item</th>
<th>Paid</th>
<th>Due</th>
<th>Remark</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><input type="checkbox" id="checkItem" name="check[]" value="<?php echo $row["sl"]; ?>"></td>
<td><?php echo $row["sl"]; ?></td>
<td><?php echo $row["date"]; ?></td>
<td><?php echo $row["item"]; ?></td>
<td><?php echo $row["paid"]; ?></td>
<td><?php echo $row["due"]; ?></td>
<td><?php echo $row["remark"]; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
<p align="center"><button type="submit" class="btn btn-success" name="save">DELETE</button></p>
</form>
<script>
$("#checkAl").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
</script>
</body>
</html>
First you need to copy the data from one table to another using INSERT ... SELECT syntax and only then you can delete.
You should be using prepared statements for this.
if (isset($_POST['save'])) {
// Prepared INSERT query
$stmt_insert = $conn->prepare('INSERT INTO bazarduepayment(date,item,paid,due,remark)
SELECT date,item,paid,due,remark FROM bazar WHERE sl=?');
// Prepare DELETE query
$stmt_delete = $conn->prepare('DELETE FROM bazar WHERE sl=?');
// Loop on all checkboxes selected
foreach ($_POST['check'] as $del_id) {
$stmt_insert->bind_param('s', $del_id);
$stmt_insert->execute();
$stmt_delete->bind_param('s', $del_id);
$stmt_delete->execute();
}
}
You could even simplify this to get rid of the foreach loop entirely.

HTML Table with inline PHP

I want to create a HTML Table, but the rows should be generated from the values from a mysql database. The problem is that I want to have a boolean box where the user can mark it, and then press a button to update the table in the database. How do I do such a thing ?
Code so far:
<?php
session_start();
require("connectToEvent_log.php");
$connectToEvent = connect2db();
$uid = '2'; // for the filnal version: #$_SESSION['uid'];
$view_event = "SELECT * FROM event_log WHERE uid = $uid";
$view_event_query = mysqli_query($connectToEvent, $view_event);
$row = mysqli_num_rows($view_event_query);
$print = mysqli_fetch_array($view_event_query);
?>
<html>
<head>
<title>Events</title>
</head>
<body>
<form action="viewEvents.php" method="POST">
<table border = '1'>
<tr>
<?php
while($row != 0){
echo "<td>".$print['hours']."</td>";
echo "<td>".$print['date']."</td>";
}
?>
</tr>
</table>
<form/>
</form>
</body>
</html>
You can easily iterate over the result from the mysqli_fetch_array function to create the table rows. Creating a checkbox markup is done easily, i assume that the table has a primary key id and the column, that stores the checkbox value (0 or 1) is called checkbox.
<?php
session_start();
require("connectToEvent_log.php");
$connectToEvent = connect2db();
$uid = '2'; // for the filnal version: #$_SESSION['uid'];
$view_event = "SELECT * FROM event_log WHERE uid = $uid";
$view_event_query = mysqli_query($connectToEvent, $view_event);
$num_rows = mysqli_num_rows($view_event_query);
$rows = mysqli_fetch_array($view_event_query);
?>
<html>
<head>
<title>Events</title>
</head>
<body>
<form action="viewEvents.php" method="POST">
<table border="1">
<thead>
<tr>
<td>Id</td>
<td>Date</td>
<td>Hours</td>
<td>Checkbox</td>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($num_rows); $i++) {
?>
<tr>
<td><?php print $rows[$i]["eid"]; ?></td>
<td><?php print $rows[$i]["date"]; ?></td>
<td><?php print $rows[$i]["hours"]; ?></td>
<td><input type="checkbox" name="row[<?php $rows[$i]["eid"]?>][checkbox]" value="1" <?php if ($rows[$i]["accepted"]) print ' checked="checked"'; ?>/></td>
</tr>
<?php
}
?>
</tbody>
</table>
<input type="submit" />
</form>
</body>
</html>

Queue Table using PHP/MySQL/Ajax

I have database table schedule with id, date, time, cabinet columns.
Also I have table cabinets with id, cabinetNumber, title columns.
I should generate table, but it should look like queue table.
cabinet 8,9,10,11,12,13,14,15,16
102 - - - + - - + - -
103 - + - - - - + - -
if time is busy it will be +, if free -.
I need modify my mysql query. And should be possible to change date (usege datepicker and Ajax) and change table rows values depend of date.
But if date does not exist, query will be empty and table will be without rows. How can i fixed it?
MySQL query :
$q = $_GET['date'];
$query = mysql_query("SELECT date,cabinet,
SUM(IF(ROUND(`time`)=8,1,0)) as h8,
SUM(IF(ROUND(`time`)=9,1,0)) as h9,
SUM(IF(ROUND(`time`)=10,1,0)) as h10,
SUM(IF(ROUND(`time`)=11,1,0)) as h11,
SUM(IF(ROUND(`time`)=12,1,0)) as h12,
SUM(IF(ROUND(`time`)=13,1,0)) as h13,
SUM(IF(ROUND(`time`)=14,1,0)) as h14,
SUM(IF(ROUND(`time`)=15,1,0)) as h15
FROM `schedule` WHERE date = '".$q."'
GROUP BY cabinet") or die(mysql_error());
?>
table :
<table class="table table-hover">
<tr class=".info"><td>Cab</td><td >8:00</td><td >9:00</td><td >10:00</td><td >11:00</td><td >12:00</td><td >13:00</td><td >14:00</td><td >15:00</td></tr>
<!-- -->
<?php while($data=mysql_fetch_array($query)) :?>
<tr>
<?php $cabinet = $data['cabinet']; ?>
<td><?=$cabinet ?></td>
<?php for($j=8; $j<=15; $j++) : ?>
<?php
$busy = $data['h'.$j];
?>
<?php if($busy>0 && $data['date']===$q ): ?>
<td class="busy"></td>
<?php else: ?>
<td class="free">
<form action="1.php" method="post">
<input type="hidden" name="time" value="<?= $j;?>" />
<input type="hidden" name="cabinet" value="<?= $cabinet;?>" />
<input type="submit" style="free" value="" name="sub"/>
</form>
</td>
<?php endif?>
<?php endfor ?>
</tr>
<?php endwhile ?>
</table>
And jQuery / Ajax:
<script>
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
});
$( ".date" ).on('change', function(){
var date = $('#datepicker').val();
$.ajax({
type:'get',
url:'table.php',
data : {
'date' : date
},
success: function(data) {
$('#result').html(data);
}
});
});
</script>
I had solwe my problem. I added new query query2 from cabinets table.
<?php $query2 = mysql_query("select cabinetNum from cabinets") ?>
<table class="table table-hover">
<tr class=".info"><td>Cab</td><td >8:00</td><td >9:00</td><td >10:00</td><td >11:00</td><td >12:00</td><td >13:00</td><td >14:00</td><td >15:00</td></tr>
<!-- -->
<?php while($data2=mysql_fetch_array($query2)): ?>
<?php $data=mysql_fetch_array($query) ?>
<tr>
<?php $cabinet = $data2['cabinetNum']; ?>
<td><?=$cabinet ?></td>
<?php for($j=8; $j<=15; $j++) : ?>
<?php
$busy = $data['h'.$j];
?>
<?php if($busy>0 ): ?>
<td class="busy"></td>
<?php else: ?>
<td class="free">
<form action="1.php" method="post">
<input type="hidden" name="time" value="<?=$j?>" />
<input type="hidden" name="cabinet" value="<?=$cabinet?>" />
<input type="hidden" name="date" value="<?=$q?>" />
<input type="submit" class="free" value="" name="sub"/>
</form>
</td>
<?php endif?>
<?php endfor ?>
</tr>
<?php endwhile ?>
</table>
The key is to keep the queries simple, use PHP to process and display the data. I will not go in to the altering of data with datapicker and ajax as you need to get the displaying correct first. Please take a look at this code and understand what it does and why it solves the problem of when there is no data for a date. You dont seem to have added the cabinet name in your table, so I kept it as an id. You can do a simple join in the query to get the cabinet name.
PHP code
<?php
//Using the object orientated style from this page
//http://php.net/manual/en/mysqli-stmt.bind-param.php
//Connect to database
$link = new mysqli("localhost", "root", "", "scheduler");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Use todays date unless specified
$date = date("Y-m-d");
if (isset($_GET['date'])) {
$date = $_GET['date'];
}
$cabinet_activity = array();
//First do a query to get all distinct cabinets, whether they have activity for the date or not
if ($cabinets = $link->prepare("SELECT DISTINCT cabinet FROM schedule")) {
$cabinets->execute();
$result = $cabinets->get_result();
while ($this_row = $result->fetch_assoc()) {
$cabinet_activity[$this_row['cabinet']] = array(); //Initialise the busy array for the next query
}
}
if ($stmt = $link->prepare("SELECT id, HOUR(time) as hour, cabinet FROM schedule WHERE date = ?")) {
$stmt->bind_param('s', $date);
$stmt->execute();
$result = $stmt->get_result();
while ($this_row = $result->fetch_assoc()) {
$id = $this_row['id'];
$hour = $this_row['hour'];
$cabinet_id = $this_row['cabinet'];
//Add to cabinet to cabinet activity list (should not be necessary now)
/*
if (!array_key_exists($cabinet_id, $cabinet_activity)) {
$cabinet_activity[$cabinet_id] = array();
}
*/
//Add the activity time to the busy hours
if (!in_array($hour, $cabinet_activity[$cabinet_id])) {
$cabinet_activity[$cabinet_id][] = $hour;
}
}
}
$min_hours = 8;
$max_hours = 16;
//Display information:
?>
<table border="1">
<thead>
<tr>
<td>Cabinet</td>
<?php
for($hour = $min_hours; $hour <= $max_hours; $hour++) {
?><td><?php print $hour; ?></td><?php
}
?>
</tr>
</thead>
<tbody>
<?php
//For each cabinet
foreach($cabinet_activity as $cabinet_id => $busy_hours) {
?><tr>
<td><?php print $cabinet_id; ?></td>
<?php
for($hour = $min_hours; $hour <= $max_hours; $hour++) {
if (in_array($hour, $busy_hours)) {
?><td>+</td><?php
} else {
?><td>-</td><?php
}
}
?>
</tr><?php
} ?>
</tbody>
</table>

Can't retrieve data properly from database in 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().

Categories