Queue Table using PHP/MySQL/Ajax - php

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>

Related

How do I get items by category wise

Basically, I have a list of categories that I am iterating form mysqli
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category?>" />;
</div>
<?php }?>
</div>
Now what I want that if I press any category it should fetch data accordingly there is my code for fetching
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
echo $num;
$stmtproducts->close();
I am confused that if there was a specific name of input then I would have gotten it by isset($_POST['name']) but there is no specific name... I cannot think of how to send category to mysql.
<div id="divTransactional" style="width:70%;padding-left:5%; float:left;">
<?php if($num>0) {?>
<table class="table table-responsive table-hover" id="tableProducts">
<h3>Products</h3>
<tbody>
<?php for($i=0;$i<$num;$i++) { $products = $resultproducts->fetch_assoc();//while($products = $resultproducts->fetch_assoc()) {?>
<tr>
<td>Code: <?php echo $products['product_code'];?></td><td>Added On: <?php echo $products['product_date'];?></td>
</tr>
<tr>
<td>Name: <?php echo $products['product_name'];?></td>
</tr>
<tr>
<td>Category: <?php echo $products['category'];?></td>
</tr>
<tr>
<td>Description: <?php echo $products['product_desc'];?></td>
</tr>
<tr>
<td>Price: <?php echo $products['product_price'];?></td><td>Discount: <?php echo $products['product_discount'];?></td>
</tr>
<tr style="width:100px; height:100px;">
<td><img src="../../uploads/store/products/<?php echo $products['product_image1'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image2'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image3'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image4'];?>" style="width:100px; height:100px;"/></td>
</tr>
<?php }?>
</tbody>
<?php if($num >= 10) { ?>
Next
<?php } ?>
<?php $prev = $count - 10;
if ($prev >= 0){?>
Previous
<?php }?>
</table>
<?php if($num >= 10) { ?>
Next
<?php } ?>
<?php $prev = $count - 10;
if ($prev >= 0){?>
Previous
<?php }?>
<?php } ?>
</div>
I would suggest using Ajax to call the server with an Id in parameters.
You need to add a class to your buttons and you do need to link a JS file and JQuery. here's an example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="path/to/your/file.js"></script>
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category']?>" class="btnCategory"/>;
</div>
<?php }?>
And then, using ajax you can call your php file that returns the value you need to fetch from your database.
$(document).ready(function() {
$('.btnCategory').on('click', function(){
var id = $this.attr('name');
$.ajax({
url: 'path/to/your/file.php',
method: "GET",
data: {category_id: id},
success: function(data) {
//This is the data fetch from the server
console.log(data);
},
error: function(err) {
console.error('An error occurred : ' + err);
}
});
});
});
And then, when your PHP file receive the parameter $_GET['category_id'] you call your database.
<?php
if(isset($_GET['category_id'])){
//An id was post in the url.
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
$stmtproducts->close();
$result = array('row_count' => $num, 'result' => $resultproducts);
echo json_encode($result);
}
And then you return a json array of your result. That's what I would do.
Hope it helps !
Nic
You asked for a demo, here it is .
<?php
if(isset($_GET['category_id'])){
//An id was post in the url.
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
$stmtproducts->close();
$result = array('row_count' => $num, 'result' => $resultproducts);
echo json_encode($result);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category']?>" class="btnCategory"/>;
</div>
<?php }?>
</div>
<script>
$(document).ready(function() {
$('.btnCategory').on('click', function(){
var id = $this.attr('name');
$.ajax({
method: "GET",
data: {category_id: id},
success: function(data) {
//This is the data fetch from the server
console.log(data);
},
error: function(err) {
console.error('An error occurred : ' + err);
}
});
});
});
</script>

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

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>

PHP Adding elements with the array to database not working

I have array which get all E-mails which are invited by the user before. I checking which e-mails are selected by checkbox and then I add them to the table 'zaproszenia'. The array saves the records. When i click the button 'Zapisz'(SAVE) I have error:
Notice: Undefined offset: 1 in D:\xampp\xampp\htdocs\inzynierka\inzynierka\zaproszenia.php on line 91
This line is:
$tabMail=$mail_array[$i];
I want save to the table 'zaproszenia' the e-mail which is select by checkbox. I have no idea how do that. I was trying and trying and nothing.Sorry about my english. I hope that I describing the problem clear.
Code fragment with file: zaproszenia.php - List the emails and checkboxes for them:
<form method="post">
<table class="table table-striped">
<thead>
<tr>
<th>Email_goscia</th>
<th>Imię</th>
<th>Nazwisko</th>
<th>Kod_dostepu</th>
<th>Data ważności kwest.</th>
</tr>
</thead>
<tbody>
<?php
$sqlc=mysqli_connect('127.0.0.1','root','');
if($sqlc)
{
$sql_q="USE aplikacja";
mysqli_query($sqlc,$sql_q);
//wyświetlanie listy gości dodanych przez uzytkownika globalnie tzn. to jest lista z ktrej uzytkownik wybiera ktrych gosci chce zaprosić do konkretnego kwestionariusza
$sql_q=mysqli_query($sqlc, "SELECT * FROM goscie g, uzytkownicy_goscie ug WHERE g.Email_goscia=ug.Email_goscia AND ug.Login='$log' ");
$lp=1;
if(mysqli_num_rows($sql_q) != 0)
{
$licznik=0;
while ($recordG=mysqli_fetch_array($sql_q))
{
?><tr>
<td> <?php echo $mail = $recordG['Email_goscia'];
$mail_array=array($licznik => $mail);
$licznik++; //$_SESSION['tablicaMail']=$mail_array; print_r($_SESSION);
print_r($mail_array);
?></td>
<td> <?php echo $recordG['Imie'];?> </td>
<td> <?php echo $recordG['Nazwisko']; ?> </td>
<td> <?php echo $recordG['Kod_dostepu'];?></td>
<td> <?php echo '<input type="date" name="data_waznosci'.$lp.'" id="data_waznosci'.$lp.'">'; ?> </td>
<td> <?php echo '<td><input type="checkbox" name="zaznaczyc'.$lp.'" id="zaznaczyc'.$lp.'" class="ClassZaznacz" onchange = "zaznacz();"/> <br /></td>'; ?> </td>
</tr>
<?php
$lp++;
}
}
else
{
echo "Użytkownik nie dodał jeszcze żadnych gości";
} ?>
</tbody>
</table>
<input type="submit" class="btn btn-primary" name="zapros" id="zapros" value="Zapisz zmiany" />
</form>
Save the selected emails by checkboxes:
<?php
if (isset($_POST['zapros']))
{
$data_zaproszenia = date("Y-m-d");
$liczba = count(preg_grep('/^data_waznosci[\d]*/', array_keys($_POST)));
echo $liczba;
if(mysqli_num_rows($sql_q) != 0)
{
for ($i=1; $i <= $liczba ; $i++)
{
/*while ($recordG=mysqli_fetch_array($sql_q)) {
$mail = $recordG['Email_goscia'];
$mail_array=array($mail);
} print_r($mail_array); //$mail = $recordG['Email_goscia']; //echo $mail; */
if (isset($_POST["zaznaczyc".$i]))
{
$sql_wyniki = mysqli_query($sqlc, "INSERT INTO wyniki (Data_wypelnienia, ID_kwestionariusza) VALUES (NULL, $id)");
$id_wyniku=mysqli_query($sqlc, "SELECT ID_wyniku FROM wyniki WHERE ID_kwestionariusza=$id");
$id_wyniku2 = mysqli_fetch_assoc($id_wyniku);
$data_waznosci = $_POST['data_waznosci'.$i];
//$tablicaMail1 = $_SESSION['tablicaMail'][$i]; //print_r($_SESSION); // echo $tablicaMail1;
$tabMail=$mail_array[$i];
$sql_zaproszenie=mysqli_query($sqlc, "INSERT INTO zaproszenia (Email_goscia, ID_kwestionariusza, ID_wyniku, Data_zaproszenia, Data_waznosci, Wynik, Ocena, Status)
VALUES ('$tabMail', $id, '$id_wyniku2[ID_wyniku]', '$data_zaproszenia', '$data_waznosci', NULL, NULL, 'Status')"); //dodawanie kolejnych odpowiedzi do bazy
echo "<script type='text/javascript'>alert('Zaproszenie wysłano!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Zaproszenia NIE wysłano!');</script>";
}
}
}
mysqli_close($sqlc);
}
}
else
{
echo mysqli_connect_errno();
}
?>
Replace below Line. it was crating new array every time with assignment operator
$mail_array=array($licznik => $mail);
//change this line to
$mail_array[$licznik]=$mail;

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'

Categories