Typeahead, cascade, mysql - php

sorry about my English, but I need some help. I'm trying to make a cascade typeahead based on manufacturers and models of cars. here is the code I have (all this code I used from examples I get from webs, I'm a beginner in web programming.
nuevo_coche.php:
...
.marcas,.modelos {
background-color:#fff;
font:8pt helvetica;
color:#000;
width:250px;
border-color:#696969;
border-style :solid;
border-width :1px;
height:15pt;
}
.tt-dropdown-menu {
font:8pt helvetica;
width: 250px;
margin-top: 5px;
padding: 8px 12px;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
color: #000;
background-color: #e0ffff;
}
</style>
<script language="javascript">
$(document).ready(function() {
$('input.marcas').typeahead({
name: 'marcas',
remote : './marcas.php?query=%QUERY'
});
$('input.modelos').typeahead({
name: 'modelos',
remote : './modelos.php?query=%QUERY&nombremarca=' + $('input.marcas').val()
});
})
function cancelar() {
location.href="index.php";
}
...
<tr>
<td width="15%">Marca</td>
<td width="43%"><input id="marcas" type="text" name="marcas" size="20" class="marcas" placeholder="Introduce marca"></td>
</tr>
<tr>
<td width="15%">Modelo</td>
<td width="43%"><input id="modelos" type="text" name="modelos" size="20" class="modelos" placeholder="Introduce Modelo"></td>
...
marcas.php:
include ("../conectar.php");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT * FROM marcas WHERE nombremarca LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['nombremarca'];
}
echo json_encode ($array); //Return the JSON Array
}
modelos.php
include ("../conectar.php");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$nombremarca = $_REQUEST['nombremarca'];
$sel_marcas="SELECT * FROM marcas WHERE nombremarca='$nombremarca'";
$rs_marcas=mysql_query($sel_marcas);
$codmarca=mysql_result($rs_marcas,0,"codmarca");
$sql = mysql_query ("SELECT * FROM modelos WHERE nombremodelo LIKE '%{$query}%' AND codmarca='$codmarca'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['nombremodelo'];
}
echo json_encode ($array); //Return the JSON Array
}
If I put in the line -- remote : './modelos.php?query=%QUERY&nombremarca=Ford' -- (for example), it works fine, but I dont know how to do it. thanks a lot in advance.

It depends on the type of input.marcas. I think you want something like:
$('input.modelos').typeahead({
name: 'modelos',
remote: './modelos.php?query=%QUERY&nombremarca=' + $('input.marcas').val()
});
If the parameter is evaluated at the start then $('input.marcas').val() will appear to be fixed so you will have to find a way of making it call a function to get the result.
All the documentation is here so there will be something in there to help you.
https://github.com/twitter/typeahead.js

Well I've got a solution, maybe is not de best way to do it but it works:
function lanzarmarca() {
if (document.getElementById("var").value == 0) {
$('input.marcas').typeahead({
name: 'marcas',
remote : './marcas.php?query=%QUERY'
});
document.getElementById("marcas").focus();
}
if (document.getElementById("var").value == 1) {
focus();
}
}
function lanzarmodelo() {
$('input.modelos').typeahead({
name: 'modelos',
remote : './modelos.php?query=%QUERY&nombremarca=' + $('input.marcas').val()
});
document.getElementById("modelos").focus();
document.getElementById("var").value=1;
}
function focus() {
if (document.getElementById("var").value == 1) {
document.getElementById("marcas").value = "";
document.getElementById("var").value=0;
window.location.reload();
}
}
function load() {
with (document.getElementById("marcas")) {
selectionStart = selectionEnd = value.length;
focus();
}
}
</script>
</head>
<body onload="load()">
...
<tr>
<td width="15%">Marca</td>
<td width="43%"><input id="marcas" type="text" class="cajaGrande" name="marcas" size="20" class="marcas" placeholder="Introduce marca" onkeypress="lanzarmarca()"><input id="var" type="hidden" name="var" value="0"></td>
</tr>
<tr>
<td width="15%">Modelo</td>
<td width="43%"><input id="modelos" type="text" name="modelos" size="20" class="modelos" placeholder="Introduce Modelo" onkeypress="lanzarmodelo()"></td>
I've tried to use onfocus instead of onkeypress but the typeahead script breaks, or typeahead.destroy o input.marcas.val() reset with ""... but nothing of this works fine.
Hope it help or someone find a better way to do this.
Thank's a lot for your help David, it really help me.

Related

Calculate total price inside php table

I'm trying to show total price in a table.
I have 2 arrays where one is the names of the cars and second is the prices of each one.
I've managed do display the prices and the names inside the table,
but the thing is that i have a "checkbox" thing that shows if car is sold or not...
I'm trying to make the total calculation that calculate the total price of all checked checkboxes.
That means - when checkbox is on, the variable of total price should add that car's price to it.
here is how it should looks like:
I must mention that I've just started to learn php at collage,
here's the array and the variable:
<?php
$cars = array ("ford","fiat","renault","mazda");
$prices = array(100,80,90,120);
$sold = '<input type="checkbox" name="sold">';
?>
I added up basic style for my table (in the same php file)
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;``
}
</style>
and the php code for the table:
<?php
$cars = array ("ford","fiat","renault","mazda");
$prices = array(100,80,90,120);
$sold = '<input type="checkbox" name="sold">';
?>
<h1>list of cars</h1>
<table>
<th>name</th>
<th>price</th>
<th>sold</th>
<?php
for($i=0;$i<count($cars);$i++){
echo
"<tr>
<td>$cars[$i]</td>.
<td>$prices[$i]$</td>.
<td>$sold</td>.
</tr>";
}
?>
</table>
How can I calculate the amount of all checked checkboxes prices?
imvain2’s answer would be your best choice as it does not require a client-server roundtrip.
However, if you would like to do this in php, you need to associate the checkbox with the car in some way.
One way would be to tweak your for loop like so
for($i = 0; $i < count($cars); $i++) {
echo (
"<tr>
<td>{$cars[$i]}</td>
<td>{$prices[$i]}$</td>
<td><input type=\"checkbox\" name=\"sold[]\" value=\"{$prices[$i]}\"></td>
</tr>"
);
}
So when the form containing the table is submitted to the server you can do the calculation like
$total = 0;
foreach ($_POST['sold'] as $value) {
$total += (int)$value;
}
I would modify the checkbox to include the price as a data-attribute and put it within the for loop not outside of it.
$sold = '<input type="checkbox" data-price="$prices[$i]" name="sold">';
then in javascript just loop through the checkboxes and an event listener that checks for checked.
function showTotal(els) {
total = 0;
els.forEach(function(el) {
if (el.checked) {
total += +el.getAttribute("data-price");
}
});
document.querySelector("#total").innerHTML = "$" + total.toFixed(2)
}
sold = document.querySelectorAll("[name='sold']");
sold.forEach(function(el) {
el.addEventListener("change", function(ev) {
showTotal(sold)
});
});
to show the total you will need a div to hold the total
<div id="total"></div>
**Note: please fix my english if needed.
please notice that the hole code is written in single php file.
after quit a bit of time, i was mange to fix my code.
first, as suggest here before, the JS code that was given was written in jquery, i haven't learned that part of js yet, therefor i wrote the code with the help of my friend in js using dom.
CSS:
<style>
body {
text-align:center;}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 50%;
margin-left: auto;
margin-right: auto;
margin-top:15%;
}
th{
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;
}
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
</style>
JS: (the location of the script tag doesn't matter at this point, but iv'e located it at the top of the php file inside header content.
<script>
function calcTotal() {
let sum = 0;
for (let index = 0; index < 4; index++) {
let priceAsStr = document.getElementById("price" + index).innerHTML;
let price = parseInt(priceAsStr);
let soldOrNot = document.getElementById("soldOrNot" + index).checked;
if (soldOrNot == true)
{
sum = sum + price;
}
}
document.getElementById("sum").innerHTML ="$" + sum;
}
and finally, for the body:
<?php
$cars = array("Ford","Fiat","Renault","Mazda");
$prices = array(100,80,137,453);
?>
<table>
<tr>
<th>Cars</th>
<th>Price</th>
<th>Sold</th>
</tr>
<?php
$sum = 0;
for ($i=0; $i < 4; $i++) {
echo "<tr id='row$i'>
<td>{$cars[$i]}</td>
<td id='price{$i}'> {$prices[$i]}$</td>
<td><input type='checkbox' id='soldOrNot{$i}' name='sold{$i}' onClick='calcTotal()' value=''> </td>
</tr>";
}
?>
</table>
<h1>Total Price: <span id="sum">0</span></h1>

Fill table from input from mysql

I have an input, in which a code is entered and filled the table below with information from mysql optenida, the question is that I want every time a code is entered, the table all the data is added (without deleting the previous ). I got the idea to do with Ajax, but do not know where to start. So you see there is an easier way that I'm not seeing (finding on google). I do not like to add this data to a table, I would like it to be temporarily (until the table is confirmed, will be added to the db).
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table>
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
require ("conectar.php");
$_SESSION["codigo"] = $_POST["input_codigo"];
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
?>
</table>
</body>
</html>
Maybe something like this i write below.
Added jQuery and Ajax request to get the data and then add it to the table.
Changed the PHP a little so that the main HTML is not returned if it is and AJAX request.
Hope it works for you (i didnt test it).
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
$bAjaxRequest = false;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$bAjaxRequest = true;
}
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="post" id="frmQuery" name="frmQuery">
<input type="text" name="input_codigo" id="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table id="tblData" name="tblData">
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
} // end if(!$bAjaxRequest) {
// we are always going to return the TR's or ""
require ("conectar.php");
// ALWAYS, BUT ALWAYS VERIFY/VALIDATE USER INPUT!!!
$_SESSION["codigo"] = mysql_real_escape_string($_POST["input_codigo"]); // for example
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) { ?>
</table>
<script type="text/javascript">
function loadData(codigo) {
$.post( "index.php", { input_codigo: codigo }, function( data ) {
$("#tblData").append(data);
});
}
$(function() {
// jQuery POST are never cached, but if you change to GET you'll need this next line
//$.ajaxSetup ({ cache: false });
$("#frmQuery").submit(function(e) {
e.preventDefault();
loadData($("#input_codigo").val());
});
});
</script>
</body>
</html>
<?php
}
?>

adding multiple rows with date on php form

ive been stuck with this for almost a week,
ive been trying to add multiple rows to a section of my form without reloading the page,
i cloned the fields and put them in an array but the problem is the dates, it can't be placed in an array ... can anybody help me out, it would be much appreciated ... thanks.
here is my code:
index.php
<DIV id="mainContent_pnlEmploymentHistory">
<form id="form1" name="form1" method="post" action="value.php">
<TABLE id="dataTable">
<TBODY>
<TR>
<TD style="width: 310px; height: 20px; text-align: center;">Name of Employer</TD>
<TD style="width: 430px; height: 20px; text-align: center;"> Employer Address</TD>
<TD style="width: 150px; height: 20px; text-align: center;">FROM</TD>
<TD style="width: 150px; height: 20px; text-align: center;">TO</TD></TR>
<TR class="row_to_clone_fw_emp">
<TD style="width: 310px; height: 20px; text-align: center;"><label>
<input type="text" id="fwemployer" name="fwemployer[]" style="width:300px"/>
</label></TD>
<TD style="width: 430px; height: 20px; text-align: center;">
<input type="text" id="fwempaddress" name="fwempaddress[]" style="width:100%"/></TD>
<TD style="width: 150px; height: 20px; text-align: center;">
<?php
include('calendar/classes/tc_calendar.php');
$date3_default = "2013-10-14";
$date4_default = "2013-10-20";
$myCalendar = new tc_calendar("datefrom", true, false);
$myCalendar->setIcon("calendar/images/iconCalendar.gif");
$myCalendar->setDate(date('d', strtotime($date3_default))
, date('m', strtotime($date3_default))
, date('Y', strtotime($date3_default)));
$myCalendar->setPath("calendar/");
$myCalendar->setYearInterval(1970, 2020);
$myCalendar->setAlignment('left', 'bottom');
$myCalendar->setDatePair('datefrom', 'dateto', $date4_default);
$myCalendar->writeScript();
?>
</TD>
<TD style="width: 150px; height: 20px; text-align: center;">
<?php
$date3_default = "2013-10-14";
$date4_default = "2013-10-20";
$myCalendar = new tc_calendar("dateto", true, false);
$myCalendar->setIcon("calendar/images/iconCalendar.gif");
$myCalendar->setDate(date('d', strtotime($date4_default))
, date('m', strtotime($date4_default))
, date('Y', strtotime($date4_default)));
$myCalendar->setPath("calendar/");
$myCalendar->setYearInterval(1970, 2020);
$myCalendar->setAlignment('left', 'bottom');
$myCalendar->setDatePair('datefrom', 'dateto', $date3_default);
$myCalendar->writeScript();
?>
</TD>
</TR>
</TBODY>
</TABLE>
<input type="submit" name="Submit" value="Submit" />
</form>
<INPUT type="button" value="Add Row" onclick="addRowfwemp(); return false;"/>
</DIV>
the function called onclick is this:
function addRowfwemp() {
/* Declare variables */
var elements, templateRow, rowCount, row, className, newRow, element;
var i, s, t;
/* Get and count all "tr" elements with class="row". The last one will
* be serve as a template. */
if (!document.getElementsByTagName)
return false; /* DOM not supported */
elements = document.getElementsByTagName("tr");
templateRow = null;
rowCount = 0;
for (i = 0; i < elements.length; i++) {
row = elements.item(i);
/* Get the "class" attribute of the row. */
className = null;
if (row.getAttribute)
className = row.getAttribute('class')
if (className == null && row.attributes) { // MSIE 5
/* getAttribute('class') always returns null on MSIE 5, and
* row.attributes doesn't work on Firefox 1.0. Go figure. */
className = row.attributes['class'];
if (className && typeof(className) == 'object' && className.value) {
// MSIE 6
className = className.value;
}
}
/* This is not one of the rows we're looking for. Move along. */
if (className != "row_to_clone_fw_emp")
continue;
/* This *is* a row we're looking for. */
templateRow = row;
rowCount++;
}
if (templateRow == null)
return false; /* Couldn't find a template row. */
/* Make a copy of the template row */
newRow = templateRow.cloneNode(true);
/* Change the form variables e.g. price[x] -> price[rowCount] */
elements = newRow.getElementsByTagName("input");
for (i = 0; i < elements.length; i++) {
element = elements.item(i);
s = null;
s = element.getAttribute("name");
if (s == null)
continue;
t = s.split("[");
if (t.length < 2)
continue;
s = t[0] + "[" + rowCount.toString() + "]";
element.setAttribute("name", s);
element.value = "";
}
/* Add the newly-created row to the table */
templateRow.parentNode.appendChild(newRow);
return true;
}
i am using this date picker for my script:
i am using the "Date Pair Example" on belows link.
http://www.triconsole.com/php/calendar_datepicker.php
thank u very much in advance ...

editing CSS of PHP grid

I have an editable grid where I want to edit the CSS such that the textarea to show the maximum width, but somehow I can't increase the width of the text area.
My database has three columns:
ID
Name
Gossip
I'm retrieving everything and displaying it in an editable grid using PHP.
index.php code
<?php
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
die('Check the database connection again!');
}
$userQuery = 'SELECT Id,Name,Gossip FROM bollywood';
$stmt = $db->query($userQuery);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var textBefore = '';
$('#grid').find('td input').hover(function() {
textBefore = $(this).val();
$(this).focus();
}, function() {
var $field = $(this),
text = $field.val();
$(this).blur();
// Set back previous value if empty
if (text.length <= 0) {
$field.html(textBefore);
} else if (textBefore !== text) {
// Text has been changed make query
var value = {
'row': parseInt(getRowData($field)),
'column': parseInt($field.closest('tr').children().find(':input').index(this)),
'text': text
};
$.post('user.php', value)
.error(function() {
$('#message')
.html('Make sure you inserted correct data')
.fadeOut(3000)
.html('&nbsp');
$field.val(textBefore);
})
.success(function() {
$field.val(text);
});
} else {
$field.val(text);
}
});
// Get the id number from row
function getRowData($td) {
return $td.closest('tr').prop('class').match(/\d+/)[0];
}
});
</script>
<title></title>
</head>
<body>
<?php if ($stmt): ?>
<div id="grid">
<p id="message">Click on the field to Edit Data</p>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gossip</th>
</tr>
</thead>
<tbody>
<?php while ($row = $stmt->fetch_assoc()): ?>
<tr class="<?php echo $row['Id']; ?>">
<td><input type="text" value="<?php echo $row['Id']; ?>" /> </td>
<td><input type="text" value="<?php echo $row['Name']; ?>" /></td>
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p>No actors added yet</p>
<?php endif; ?>
</body>
</html>
user.php code
<?php
// Detect if there was XHR request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$fields = array('row', 'column', 'text');
$sqlFields = array('Id', 'Name', 'Gossip');
foreach ($fields as $field) {
if (!isset($_POST[$field]) || strlen($_POST[$field]) <= 0) {
sendError('No correct data');
exit();
}
}
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
sendError('Connect error');
exit();
}
$userQuery = sprintf("UPDATE bollywood SET %s='%s' WHERE Id=%d",
$sqlFields[intval($_POST['column'])],
$db->real_escape_string($_POST['text']),
$db->real_escape_string(intval($_POST['row'])));
$stmt = $db->query($userQuery);
if (!$stmt) {
sendError('Update failed');
exit();
}
}
header('Location: index.php');
function sendError($message) {
header($_SERVER['SERVER_PROTOCOL'] .' 320 '. $message);
}
style.css code
body {
font: normal 14px Comic Sans, Comic Sans MS, cursive;
}
table {
width: 500px;
}
td, th {
border: 1px solid #d8d8bf;
}
th {
padding: 5px;
font: bold 14px Verdana, Arial, sans-serif;
}
td {
padding: 10px;
width: 200px;
}
td input {
margin: 0;
padding: 0;
// width:200px;
font: normal 14px sans-serif;
/** Less flicker when :focus adds the underline **/
border: 1px solid #fff;
}
td input:focus {
outline: 0;
border-bottom: 1px dashed #ddd !important;
}
#grid input {
// width: 200%;
}
You doing it wrong
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
Should be:
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
textarea is html tag name but not input type. so change this.
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
to
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
also add this css.
<style>
textarea {
resize: both;
width:700px;
}
</style>
also are you sure that you can get content using this.
<?php echo $row['Gossip']; ?>

Need form to use multiple submit buttons

I have a form that I would like to have display two versions of the data. I know that I can set two variables for this, but I can't figure out how to get it to insert into the postgres db. I have gotten as far populating the data and having the labels to enter in the new numbers for insertion into the table.
Here's what I have so far ...
<script>
window.onload = function() {
<?
$yesterday = date('Y-m-d', strtotime('-1 day'));
if ($_REQUEST['start'] == '') {
$_REQUEST['stores'] = array(1,2,3,7,8,9,17,18,19,23,16,11,4,5,6);
$_REQUEST['start'] = $yesterday;
} else {
$_REQUEST['stores'] = array(1,2,3,7,8,9,17,18,19,23,16,11,4,5,6);
}
$_REQUEST['submit'] = 'Get Data';
?>
}
</script>
<?
// various arrays and db connections we're going to need later
include('/home/...some_data_goes_here.../db_connect.inc');
$dbx = DB::connect('******');
$dbx->setFetchMode(DB_FETCHMODE_ASSOC);
//get the data based on the date.
$start = $_REQUEST['start'];
//$stores = array(1 => '1,177,18', 2 => '2,277,28', 3 => '3,377,38', 7 => '4,477,48', 8 => '5,577,58', 18 => '338', 19 => '50,51', 9 => '6,677,68', 17 => '8,877,818', 16 => '44,45,47', 11 => '7,770,78', 4 => '11,15,17', 5 => '22,25,27', 6 => '33,35,37');
$formstores = $_REQUEST['stores'];
foreach($stores as $sid => $pcs) {
$store_name = $db->getOne('SELECT store_name FROM stores WHERE store_id = ?', array($sid));
}
foreach($formstores as $k => $sid) {
if(empty($storeDataMain)){ //array is empty so make one
$storeDataMain = array();
}
//get the store names
$store_name = $db->getOne('SELECT store_name FROM stores WHERE store_id = ?', array($sid));
if(DB::isError($store_name)) { echo '<div class="error">Error '.$store_name->getdebuginfo().'</div>'; return; }
$tempups = $db->getOne('SELECT sum(count) FROM traffic WHERE store_id = ? AND tdate = ?', array($sid,$start));
//echo $tempups .' | ';
if(DB::isError($tempups)) { echo '<div class="error">Error '.$tempups->getdebuginfo().'</div>'; return; }
$tups = $tempups/2;
//echo $tups;
//Build array out and return it
$storeDataMain[$store_name] = array('trafficGuests' => number_format(floatval($tups),1,'.',',')); // floatval prevents the numbers from rounding to zero
}
?>
<h3 class="heading">Traffic Updates</h3>
<p>Enter dates in yyyy-mm-dd format.</p>
<script type="text/javascript" src="/css/prototype.js"></script>
<script type="text/javascript" src="/css/scriptaculous.js"></script>
<script type="text/javascript" src="/css/datepicker.js"></script>
<form name="setTraffic" method="get" action="/traffic/updateTraffic.php">
<!-- Build the table where they can input the date to be changed -->
<table>
<tr>
<th>Date</th>
</tr>
<tr>
<td>
<input type="text" name="start" id="start" value="<?=$_REQUEST['start']?>" alt="mm/dd/yyyy" onblur="if(this.value.length){valid=check_date(this.value);if(!valid){this.value='';this.focus();alert('Invalid date input');}else{this.value=valid;}}" onchange="if(this.value.length){valid=check_date(this.value);if(!valid){this.value='';this.focus();alert('Invalid date input');}else{this.value=valid;}}" onfocus="if(this.value == this.defaultValue) this.value = ''" /></td>
<script type="text/javascript">
var start_picker = new DatePicker({
relative : 'start',
language : 'en',
dateFormat : 'yyyy-mm-dd',
showDuration: 0.1,
closeEffectDuraction: 0.1,
disableFutureDate: true,
disablePastDate: false,
keepFieldEmpty : true
});
</script>
</td>
</tr>
</table>
<input class="button" type="submit" name="submit" value="Get Data" id="submit" />
</form>
<form method="post" action="">
<table>
<tr>
<th style="height: 20px; width: 165px; vertical-align: bottom;">Stores</th>
<? //build the list of stores for the headers.
foreach($storeDataMain as $k => $val){
echo '<th style="text-align: center; vertical-align: bottom;">'.$k.'</th>';
}
?>
</tr>
<tr>
<th style="height: 20px; vertical-align: bottom;">Guests for <?=$start?> </th>
<? //format and print out the traffic for each store
foreach($storeDataMain as $k => $val){
echo '<td style="text-align: center; vertical-align: bottom; font-size: 14px;">'.$val["trafficGuests"].'</td>';
}
?>
</tr>
<tr>
<th style="height: 20px; vertical-align: bottom;">Adjustment for <?=$start?></th>
<? //build the input fields identified based on store id.
foreach($formstores as $pcs) {
echo '<td><input class="newTraffic" type="number" style="width: 65px; text-align: right;" name="new_count" id="'.$pcs.'" value="'.$count.'" />'.$count.'</td>';
<script>// get the data ready for inserting into the database
if(isset($count)){
$count = $_POST['']
} else {
$count = '';
}}
if( $_POST ){
$count = $_POST["count"];
$store_id = $sid
$insertCounts = $db->query('INSERT INTO traffic (store_id, thour, tdate, count, door) VALUES ('$sid', )');
}
}
</script>
}
?>
</tr>
</table>
<input class="button" type="submit" name="submit2" value="Submit" id="submit" />
</form>
<h5 style="color: #707070;">New Traffic Counts</h5>
<table style="color: #707070;">
<tr>
<td style="height: 20px; width: 165px; font-weight: bold; vertical-align: bottom;">Stores</td>
<? //display the list of stores for the output of the new counts.
foreach($storeDataMain as $k => $val){
echo '<td style="text-align: center; width: 69px; padding: 4px; font-weight: bold; vertical-align: bottom;">'.$k.'</td>';
}
?>
</tr>
<tr>
<td style="height: 20px; vertical-align: bottom; font-weight: bold;">Guests for <?=$start?></td>
<? //format and display the NEW traffic for each store
foreach($storeDataMain as $k => $val){
$newCount = $val["trafficGuests"] + $count[$pcs];
echo '<td style="text-align: center; vertical-align: bottom; font-size: 14px;">'.$newCount.'</td>';
}
?>
</tr>
</table>
</form>
If you'd like to see what the page looks like you can go [here] (https://picasaweb.google.com/105736785937866961668/January22013#5828892865441021874) and the inputs are designed to take in the adjustment to the number, whether it's positive or negative. From there it is inserted into the DB table and added to the existing sum so that the new total can be reflected in the bottom greyed out table.
I know that this is something that may not be able to be accomplished, but if it can't I need to be able to get to the point where my data will still be entered into the table and then reflected after submit. I just can't seem to get there with my existing knowledge of code.
Please help?!
I can't comment on a question yet, but I think there are a few issues with your php. as #Anubis points out the insert statement needs work. Also, the first few lines of actual php code look like they are wrapped in a javascript event for the window loading. This is not needed as the code doesn't produce any javascript to run. This code will be run on the server during every page load anyway. There are a few other places you have <script> tags that are not needed and probably cause some errors.
I think what you want is to do is add an identifier to your post fields to help get the correct values. So when you are building your input boxes do it like this:
echo '<td><input class="newTraffic" type="number" style="width: 65px; text-align: right;" name="new_count__'.$pcs.'" id="'.$pcs.'" value="'.$count.'" />'.$count.'</td>';
And access the submitted values as follows: $_POST['new_count__' . $pcs]
You are trying to integrate two separate processes which makes your code hard to follow and more error prone. I see what you are trying to do but try putting input processing code at the top and display code towards the bottom. So in rough code/comments:
<?php //check for and process the new data
//if posted values
//process $_POST for values to add/subtract
//if(isset($_POST)) {
//if(!empty($_POST) {
switch ($_POST['submit']) {
case 'submit':
//new date selected
//get new display data
break;
case 'submit2':
//new traffic counts submitted
//for each input submitted
//add/subtract value to current database traffic value
//get new display data
break;
default:
//stuff if no submit
//get default display data
}
?>
<html>
display html data here
</html>
Your insert statement is wrong:
//, thour, tdate, count, door <- are there default values defined for theses? if not set the values
$db->query('INSERT INTO traffic (store_id) VALUES ('.$sid.')');
while programming you should use this error settings:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
this gives you lots of errors and descriptions when something goes wrong and it makes debugging easier.
in a production environment "display_errors" should be 0!

Categories