Need form to use multiple submit buttons - php

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!

Related

How to order mysql data in php by cloumn?

I got a simple php page displaying my data from mysql table. I can edit it and it works perfect. But I want to be able to order the data by clicking on the headers of the column (ASC and DESC).
I know I have to add hyperlink to the headers, but the informations I found didn't help me.
<?php
include_once("config.php");
$result = mysqli_query($mysqli, "SELECT * FROM material ORDER BY date ASC");
?>
<html>
<head>
<title>Material</title>
</head>
<body>
<h2>Material</h2>
<input type="button" value="Home" onclick="document.location='../index.html';">
<input type="button" value="Add data" onclick="document.location='add.html';">
</br>
</br>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td><b>Count</b></td>
<td><b>Name</b></td>
<td><b>Place</b></td>
<td><b>Serialnumber</b></td>
<td><b>Last Check</b></td>
<td><b>Next Check</b></td>
<td><b>End of life Date</b></td>
<td><b>Update</b></td>
</tr>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['count']."</td>";
echo "<td>".$res['name']."</td>";
echo "<td>".$res['place']."</td>";
echo "<td>".$res['serialnumber']."</td>";
echo "<td>".$res['last_check']."</td>";
echo "<td>".$res['next_check']."</td>";
echo "<td>".$res['date']."</td>";
echo "<td><button>Edit</button></td>";
}
?>
</table>
</body>
</html>
Please save yourself the trouble of using datatables. It's good but I don't personally enjoy using it because the tables are non-responsive. I rather use vanilla JavaScript and bootstrap for maximum responsiveness. I have not added Bootstrap in my response but it can be added easily.
You can achieve a sorting table easily client-side. Sort the data by clicking on table headers :
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.rows;
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
/*check if the two rows should switch place,
based on the direction, asc or desc:*/
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a switch is done, increase this count by 1:
switchcount ++;
} else {
/*If no switching has been done AND the direction is "asc",
set the direction to "desc" and run the while loop again.*/
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
table {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th {
cursor: pointer;
}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
<table id="myTable">
<tr>
<!--When a header is clicked, run the sortTable function, with a parameter, 0 for sorting by names, 1 for sorting by country:-->
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Country</th>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
</table>

display value from php table when clicking on a button on another page

Following is the table i created for displaying the Restaurant Name, Location and Menu for table owners.
Now each of the row for the column Menu have Button as values.
My table is ready with perfect values.
NOW MY PROBLEM IS HOW TO DO:-
Upon clicking the button corresponding to the each Restaurant, a new File(openmenu.php) will open and will echo the Restaurant Name, Mobile Number of that Restaurant and the menu.
But so far, on clicking every Button ,I can only display above entries of the Last row of the table. Help Me Out. I am new to php.
table.php
<?php
include 'nav.php';
$sql = 'SELECT * FROM owners';
$query = mysqli_query($con, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($con));
}
?>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "css/style.css">
<style>
.data-table{
width: 1024px;
margin-left: 150px;
text-align:center;
border: 1px solid firebrick;
background-color: white;
}
td,th{
border: 1px solid firebrick; padding: 3px 2px 1px 1px;
}
</style>
</head>
<body>
<div class="container">
<article>
<table class="data-table">
<thead>
<tr>
<th>Restuarant Name</th>
<th>Location</th>
<th>Menu</th>
</tr>
<tr>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($query)){
$_SESSION['resphone'] = $row['resphone'];
$_SESSION['restaur'] = $row['restaur'];
echo '<tr>
<td>'.$row['restaur'].'</td>
<td>'.$row['loc'].'</td>
<td style="background-color:firebrick;"><form method="post" action="openmenu.php?id=$row[restaur]"><input value="<?php echo $restaur;?>" type="hidden">
<input type="submit" value="View"></form></td>
</tr>';
}
?>
</tbody>
</table>
</form>
</article>
</div>
</body>
</html>
openmenu.php
<?php
include('nav.php');
?>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<style>
table, td {
border: none;
text-align: center;
text-align-last: center;
}
</style>
</head>
<body>
<div class="container">
<article>
<form method="get" align="center" action="" class="formwrap" enctype='multipart/form-data'>
<h1><?php $restaur = $_SESSION['restaur'];
echo $restaur ;?></h1>
<h1>Call to Order:</h1>
<?php $resphone = $_SESSION['resphone'];
echo $resphone;
?>
<br>
<br>
<?php
$sql = "select img from owners where restaur ='$restaur'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image_src2 = "upload/".$row['img'];
?>
<img src='<?php echo $image_src2; ?>' >
</form>
</article>
</div>
</body>
</html>
Issue 1
In this snippet you are setting the session variables resphone and restaur to the values of the store you are currently iterating over. Over and over again. That's why you're only ever getting the last store's information - it's the last things you set those variables to.
while ($row = mysqli_fetch_array($query)){
$_SESSION['resphone'] = $row['resphone'];
$_SESSION['restaur'] = $row['restaur'];
Issue 2
You should probably change the form method to get and discard the unused hidden input like so:
<form method="post" action="openmenu.php?id=<?=$row['restaur']?>">
<input type="submit" value="View">
</form>
Or more likely just change it a plain old a link:
View
Issue 3
You're completely ignoring store id requested in openmenu.php. You are using $_SESSION where you should be using $_REQUEST or $_GET. I'm not going to give an example of how you should do that. Instead, please refer to this answer before moving any further.
first you getting data from database & then use view button for openmenu.php but why u use this way
<form method="post" action="openmenu.php?id=$row[restaur]"><input value="<?php echo $restaur;?>" type="hidden"><input type="submit" value="View"></form>

How can I get $_POST to work with my PDO statement?

I can't seem to get $_POST to work with my sql query. I have tried both mysql_query and PDO.
$newartist = $_POST['newartist']; // This doesn't work with PDO statement
//$newartist = 'Hubert De Lartigue'; // This works with PDO statement!
//$query = $DBH->prepare("SELECT * FROM artist WHERE artist =?"); // Original Method
//$query->bindValue(1, $newartist, PDO::PARAM_STR); // Original Method
$query = $DBH->prepare("SELECT * FROM artist WHERE artist = :newartist"); // Suggested Method
//$query->bindParam(':newartist', $newartist); // Suggested method, tested
$query->bindParam(':newartist', $newartist, PDO::PARAM_STR); // Suggested method
$query->execute();
//foreach ($query as $row) { // Switched to while loop so it can "fetch"
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$selectedartist = '<option value="'.$row['artist_id'].'" selected="selected">'.$row['artist'].'</option>';
}
I can however echo $_POST['newartist']; and it will correctly output the artist's name!
The form per request (NOTE: you have to click the + to submit an artist and newartist echos properly after submitting a new artist):
<div style="background: #270126; padding: 0 20px;" id="artist" >
<form method="post" style="width: 100%">
Artist: <select name="artist" style="width: 200px; background: black;" class="required">
<?php
if(!empty($_POST['newartist'])) {
echo $selectedartist;
} else {
echo '<option value="2" selected="selected">Unknown-Artist</option>
'.$theartist.'';
}
?></select> +</div>
<div style="background: #270126; padding: 0 20px;" id="addnewartist" >
<fieldset style="display: none;height: 35px;" id="artistnew">
Artist Name:
<input name="newartist" id="newartist" style="width: 200px; display:inline;" /> Artist URL:<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" style="display:inline;" />
</fieldset>
</div>
<fieldset id="artworknew" style="width: 100%;">
<div style="background: #270126; padding: 0 20px;">
Artwork Name: <input name="name" id="name" style="width: 300px;" />
</div>
<div style="background: #270126; padding: 0 20px;">
File Name: <input name="file" id="file" style="width: 300px" value=".jpg" /><br />
</div>
<div style="background: #270126; padding: 0 20px; height: 35px;">
Folder: <select name="folder" style="width: 200px; background: black;">
<option value="16">digitalart2</option>
<?=$thefolder;?></select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div></fieldset>
</form>
</div>
<?php
if ($_POST['addartist']) {
mysql_query("INSERT INTO `artist` ( `artist_id` , `artist`, `artist_url`)
VALUES (NULL , '".$_POST['newartist']. "', '".$_POST['artist_url']. "');") or die(mysql_error());
//echo '<meta http-equiv="refresh" content="0;url=?form=addart">';
}
if ($_POST['addartwork']) {
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
mysql_query("INSERT INTO `artwork` (`id`, `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($_POST['name'])."',
'".sql_inj_str($_POST['artist'])."',
'".sql_inj_str(htmlentities($_POST['file']))."',
'".sql_inj_str($_POST['folder'])."',
'".sql_inj_str($_POST['dt1'])."',
'1',
'".sql_inj_str($_POST['disabled'])."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}
include ('footer.php');
?>
I went through all the code you gave me. You have many bad html, css and javascript practices. It make your code hard to debug. I have improved your code and maybe if you can follow my logic and comments, you will figure out what's wrong with you code.
Basically, the code you showed me first is perfectly fine. The problem is with your design. You are entering null values for the id column instead of letting the database do it for you. You have a column for an artist_id and inserting in the artist there. Look at your database definitions to make sure that they have the correct structure and are getting the expected variables. Here is you code but made with good practices. If you can follow my code, you will find it easier to debug the problem.
<?php
/** I have re-wrote your code to give you a better way of writing code that makes it easier to debug**/
/**Store input fields as variables so I don't have to repeat certain things**/
$newartist = isset($_POST['newartist']) ? ($_POST['newartist']) : "Unkown Artist"; // either has a value or the value is Unknown Artist. Only has a value if the $_POST is set
$addartist = isset($_POST['addartist']) ? true : false; // the addartist has been posted or not
$addartwork = isset($_POST['addartwork']) ? true : false; // the addartwork has been posted or not
//This is for add new artist
if($addartist){
$newartist = isset($_POST['newartist']) ? $_POST['newartist'] :null;
$newartist = isset($_POST['artist_url']) ? $_POST['artist_url'] :null;
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
mysql_query("INSERT INTO `artist` ( `artist`, `artist_url`)
VALUES ('". $newartist . "', '". $artist_url . "');") or die(mysql_error());
}else{
$newartist = null;
$artist_url = null;
}
/// this is for adding artwork
if($addartwork){
$name = isset($_POST['name']) ? $_POST['name'] :null;
$artist = isset($_POST['artist']) ? $_POST['artist'] :null;
$file = isset($_POST['file']) ? htmlentities($_POST['file']) :null;
$folder = isset($_POST['folder']) ? $_POST['folder'] :null;
$dt1 = isset($_POST['dt1']) ? $_POST['dt1'] :null;
$disabled = isset($_POST['disabled']) ? 1 : 0;
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
//There is a problem with you artist_id column. The artist has a string value, and you have an id column in the database
//Also you have a sql_inj_str() function. I am guessing that you have difined this function somewhere.
mysql_query("INSERT INTO `artwork` ( `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($name)."',
'".sql_inj_str($artist)."',
'".sql_inj_str(htmlentities($file))."',
'".sql_inj_str($folder)."',
'".sql_inj_str($dt1)."',
'1',
'".sql_inj_str($disabled)."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}else{
$name = null;
$artist = null;
$file = null;
$folder = null;
$dt1 = null;
$disabled = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Query PDO</title>
<!-- Put the styles (CSS) seperate from the html, easier to maintain. You can just copy these styles into an external file and just link it-->
<style>
#artist {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
form {
width: 100%;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
select {
width: 200px;
/**background: black;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
a {
width: 15px;
font-size: 1.5em;
display:inline;
/**added a myself**/
text-decoration: none;
}
#addnewartist{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
fieldset#artistnew{
display: none;
height: 35px;
}
form #newartist {
width: 200px;
display:inline;
}
form .secondaryAction{
display:inline;
}
#artworknew{
width: 100%;
}
/** I now had no choice but to add in a few class names here**/
.ArtworkName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='name'] {
width: 300px;
}
.FileName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='file'] {
width: 300px;
}
.Folder {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
height: 35px;
}
select[name='folder'] {
width: 200px;
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
</style>
</head>
<body>
<form method="post">
<!-- move the div inside the form-->
<div id="artist" >
Artist:
<select name="artist" class="required">
<?php echo '<option value="' . $newartist . '" selected="selected">' . $newartist . '</option>'; ?>
</select>
<!--When the link is clicked it runs the doStyles function-->
+
<!-- get all the javascript out of the anchor tag. You can use jquery or external javscript but doing it this way is really really bad practice-->
<script>
// You can store this code in an external javscript file and embed it here
function doStyles(){
document.getElementById('artistnew').style.display='block';
document.getElementById('artworknew').style.display='none';
document.getElementById('artist').style.display='none';
}
</script>
</div>
<div id="addnewartist" >
<fieldset id="artistnew">
Artist Name:
<input name="newartist" id="newartist" />
Artist URL:
<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" />
</fieldset>
</div>
<fieldset id="artworknew" >
<div class="ArtworkName">
Artwork Name:
<input name="name" id="name" />
</div>
<div class="FileName">
File Name:
<input name="file" id="file" value=".jpg" /><br />
</div>
<div class="Folder">
Folder:
<select name="folder" >
<option value="16">digitalart2</option>
<?=$thefolder;?>
</select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div>
</fieldset>
</form>
</div>
</body>
</html>
Everything looks OK. Check you form again, and make sure the name attribute is correct. Also, if you are typing in the name on the search form, make sure you are taking care of the case sensitive. The name should match the name in the database.
Use bindParam
Try taking out the PDO::PARAM_STR for now.
Lastly try this:
$result = $query->execute();
and then use $result in the for each loop

Typeahead, cascade, mysql

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.

keeping track of pages and mysql_num_rows

Working off my previous question I'm trying to figure out how to achieve what I'm after.
I have an order that gets made. When the time comes to print that order, if the order has more than 25 lines/rows i need to put up from line 26 and create a new page. My question is how would I write that? I was thinking with mysql_num_rows but how can I track that?
How would I break it down, say put rows 0-24 into array1 then put rows 25-49 into array2 and so on? Then put the different arrays into while loops?
Maybe put everything into an array, then split it up?
Here's what I have right now
<?php
if (isset($_POST['CheckBox'])){
$CB = $_POST['CheckBox'];
} else {echo 'Nothing Marked'; die;}
/////////////////////////////////////////
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#media print{ #page{margin: 5%;} }
body{
background-color: #CCC;
margin:0;
padding:0;
}
#MainWrapper{
margin:0 auto;
width:675px;
height:900px;
background-color:#3CF;
position:relative;
}
#OrderInfo{
width:200px;
height:50px;
background-color:#6C6;
float:left;
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
}
#OrderInfoNotes{
width:475px;
height:50px;
background-color:#6C6;
float:right;
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
}
#LineHeader{
width:675px;
background-color:#C90;
float:left;
}
.OrderLines{
font-family:Verdana, Geneva, sans-serif;
font-size:9px;
padding:0px;
}
.PBA{page-break-after: auto;}
.bigbold{ font-weight:bold; font-size:14px;}
.bigger{font-size:14px;}
</style>
</head>
<body>
<?php
///////////////////////////////////////////
foreach ( $CB as $thekey => $Order_ID )
{
$queryOrderHead = "SELECT * FROM Orders WHERE Order_ID = ".mysql_real_escape_string($Order_ID)."";
$queryOrderLines = "SELECT * FROM Order_LineDetails WHERE Order_LineDetails.Order_ID = ".mysql_real_escape_string($Order_ID)."";
//////////////////////////////////////////
if ($queryRunHead = mysql_query($queryOrderHead)){
//////////////////////////////////////////
// THIS IS THE HEADER OF THE ORDER ///////
//////////////////////////////////////////
while ($info_HEAD = mysql_fetch_array($queryRunHead))
{
$OrderDate_HEAD = $info_HEAD['OrderDate'];
$shippingservice_HEAD = $info_HEAD['shippingservice'];
$OrderNotes_HEAD = $info_HEAD['OrderNotes'];
?>
<div id="MainWrapper">
<!--START ORDERINFO INTO -->
<div id="OrderInfo">
Order ID:<span class="bigbold"><?php echo ' '.$Order_ID; ?></span><br>
<?php echo 'SHIPPER: <span class="bigbold">'.$shippingservice_HEAD.'</span>'; ?><br>
<?php echo 'ORDER DATE: '.$OrderDate_HEAD; ?>
</div>
<div id="OrderInfoNotes">
<?php echo 'NOTES: '.$OrderNotes_HEAD; ?></div>
<!--END ORDERINFO INTO -->
<hr><br>
<div id="LineHeader">
<table class="OrderLines">
<tr class="bigbold">
<td width="300"><u>Product Name:</u></td>
<td width="90"><u>UPC Code:</u></td>
<td width="50" align="right"><u>PID:</u></td>
<td width="75" align="right"><u>QTY:</u></td>
<td width="160" align="right"><u>Packer:</u></td>
</tr>
<?php
}
/////////////////////////////////////////
// THIS IS THE ORDER LINES //////////////
/////////////////////////////////////////
$queryRunLines = mysql_query($queryOrderLines);
while ($info = mysql_fetch_array($queryRunLines))
{
$ProductName_LINE = $info['ProductName'];
$qty_LINE = $info['qty'];
$Product_ID_LINE = $info['Product_ID'];
$UPC_LINE = $info['UPC'];
?>
<tr class="bigger">
<td><?php echo $ProductName_LINE; ?></td>
<td><?php echo $UPC_LINE; ?></td>
<td align="right"><?php echo $Product_ID_LINE; ?></td>
<td align="right"><?php echo $qty_LINE; ?></td>
<td></td>
</tr><tr>
<td colspan="5"><hr></td></tr>
<?php
}
///////////////////////////////////////////////////////////
// END OF ORDER LINES /////////////////////////////////////
///////////////////////////////////////////////////////////
$numRows = 0;
$numRows = mysql_num_rows($queryRunLines);
echo 'Total Rows ('.$numRows.')'
///////////////////////////////////////////////////////////
?><tr>
<td colspan="5" class="center">--- :END: ---</td>
</tr>
</table>
</div>
</div>
<p class="PBA"/>
<?php
} else {
echo mysql_error();
}
}
mysql_close($conn);
?>
</body>
</html>
From looking at your previous question, it appears you want to print the HTML page, not use pagination. Just use a counter variable:
$i = 0;
while ($info = mysql_fetch_array($queryRunLines))
{
$ProductName_LINE = $info['ProductName'];
$qty_LINE = $info['qty'];
$Product_ID_LINE = $info['Product_ID'];
$UPC_LINE = $info['UPC'];
if (!($i % 25)) {
// echo page break every 25 lines
}
// output
$i++;
}
Also take a look at CSS attributes page-break-before/page-break-after. I would also suggest using an HTML to PDF converter. They are easy to use and will make your printed documents consistent across different systems.
What you need is called pagination.
One of the way to do it is, use LIMIT clause in your query.
I would have put up here but there are hundreds of tutorials for pagination in google with good explanation. It would be better if you search by "php pagination" and learn step by step.
you can limit the number of rows returned by your query,
add LIMIT 0, 24 at the end of your query, you will get the first 25 rows.
you can have more details here
Use a variable to store how many rows you want to display and another one to store the current rows being retrieved.
Look up pagination which will give you a better idea. It may not be exactly what you what but will teach you how to limit sql results they way you want.

Categories