HREF link calls out php function [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have two files. index.php and cart.php. All my functions, connection to database, etc. are located at file cart.php. There are functions that I want to call out if user clicks on a HREF link.
my index.php:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="wrapper" align="center" style="width:90%; height:auto; margin-left:auto; margin-right:auto;">
<?php cart(); ?>
<br><br>
<div id="sidebar" align="left" style="width:15%; height:auto; background-color:#999999; float:left;">
<ul style="list-style-type:none;">
<li>ALL</li>
<li>SHIRTS</li>
<li>HOODIES</li>
</ul>
</div>
<div id="products" style="width:85%; height:auto; background-color:#888888; float:left;">
<?php
products_all();
?>
</div>
</div>
</body>
</html>
Then, How can I make that a HREF link calls out a specific function(which is located in cart.php) and displays it inside a div tag(in my case, in div id="products")?
It's probably easy, I am just a beginner.
Here's my cart.php just in case.
<?php
session_start();
$page = 'index.php';
// ***
/*
$mysql_host = "***";
$mysql_database = "***";
$mysql_user = "***";
$mysql_password = "***";
*/
// localhost
$mysql_host = "localhost";
$mysql_database = "cartt";
$mysql_user = "root";
$mysql_password = "";
mysql_connect($mysql_host, $mysql_user, $mysql_password) or die(mysql_error());
mysql_select_db($mysql_database) or die(mysql_error());
if (isset($_GET['add'])) {
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while ($quantity_row = mysql_fetch_assoc($quantity)) {
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]) {
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
}
header('Location: '.$page);
}
if (isset($_GET['remove'])) {
$_SESSION['cart_'.(int)$_GET['remove']]--;
header('Location: '.$page);
}
if (isset($_GET['delete'])) {
$_SESSION['cart_'.(int)$_GET['delete']]='0';
header('Location: '.$page);
}
function products_all() {
$get_all = mysql_query('SELECT id, name, description, price FROM products ORDER BY id DESC');
if (mysql_num_rows($get_all)==0) {
echo "There are no products to display!";
}
else {
echo '<table width="900px" allign="center" cellpadding ="5" style="background-color:transparent;">
<tr align="center" valign="middle">';
$i = 0;
while ($get_row = mysql_fetch_assoc($get_all)) {
echo '<td><img src="./cartimages/'.$get_row['id'].'.jpeg" alt=" " height="225px" align="center"><br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound'.number_format($get_row['price'], 2).'<br />Add</td>';
$i++;
if ($i == 4) {
echo '</tr>
<tr align="center" valign="middle">';
$i = 0;
}
}
}
}
function products_shirts() {
$get_shirts = mysql_query('SELECT id, name, description, price FROM products WHERE type = "shirt" ORDER BY id DESC');
if (mysql_num_rows($get_shirts)==0) {
echo "There are no products to display!";
}
else {
echo '<table width="900px" allign="center" cellpadding ="5" style="background-color:transparent;">
<tr align="center" valign="middle">';
$i = 0;
while ($get_row = mysql_fetch_assoc($get_shirts)) {
echo '<td><img src="./cartimages/'.$get_row['id'].'.jpeg" alt=" " height="225px" align="center"><br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound'.number_format($get_row['price'], 2).'<br />Add</td>';
$i++;
if ($i == 4) {
echo '</tr>
<tr align="center" valign="middle">';
$i = 0;
}
}
}
}
function products_hoodies() {
$get_hoodies = mysql_query('SELECT id, name, description, price FROM products where type = "hoodie" ORDER BY id DESC');
if (mysql_num_rows($get_hoodies)==0) {
echo "There are no products to display!";
}
else {
echo '<table width="900px" allign="center" cellpadding ="5" style="background-color:transparent;">
<tr align="center" valign="middle">';
$i = 0;
while ($get_row = mysql_fetch_assoc($get_hoodies)) {
echo '<td><img src="./cartimages/'.$get_row['id'].'.jpeg" alt=" " height="225px" align="center"><br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />&pound'.number_format($get_row['price'], 2).'<br />Add</td>';
$i++;
if ($i == 4) {
echo '</tr>
<tr align="center" valign="middle">';
$i = 0;
}
}
}
}
function paypal_items() {
$num = 0;
foreach($_SESSION as $name => $value) {
if ($value!=0) {
if (substr($name, 0 , 5)=='cart_') {
$id = substr($name, 5, strlen($name)-5);
$get = mysql_query('SELECT id, name, price, shipping FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$num++;
echo '<input type="hidden" name="item_number_'.$num.'" value="'.$id.'">';
echo '<input type="hidden" name="item_name_'.$num.'" value="'.$get_row['name'].'">';
echo '<input type="hidden" name="amount_'.$num.'" value="'.$get_row['price'].'">';
echo '<input type="hidden" name="shipping_'.$num.'" value="'.$get_row['shipping'].'">';
// echo '<input type="hidden" name="shipping2_'.$num.'" value="'.$get_row['shipping'].'">';
echo '<input type="hidden" name="quantity_'.$num.'" value="'.$value.'">';
}
}
}
}
}
function cart() {
$total = 0;
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_array($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' # £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'[-] [+] [Delete]<br />';
}
}
$total += $sub;
}
}
if ($total==0) {
echo "Your cart is empty.";
}
else {
echo '<p>Total: £'.number_format($total, 2).'</p>';
?>
<p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="*************">
<?php paypal_items(); ?>
<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="amount" value="<?php echo $total; ?>">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
</p>
<?php
}
}
?>

If you want a php function to run when you do something on the client, you have to make an AJAX request that calls that function, then you insert the HTML dynamically when your AJAX request returns.
Remember that PHP only generates text that is sent over the wire as HTML,CSS,JavaScript,JSON, XML,... There is no way for PHP to interact directly with your page, it can only generate new content
Here's a basic AJAX example you could use; I'll use jQuery and some simplified PHP code
ajax.php
function doit() { echo "anything"; }
doit();
page.html
Load stuff
<div id="products"></div>
page.js
$("#mylink").click(function() {
$('#products').load("/ajax.php");
})
That code loads the result of doit in ajax.php into the div with id "products" when you click on the link with ID "page.html"
http://api.jquery.com/load/

You need to use client-side javascript AJAX. Look up and read about AJAX requests.
Once you know AJAX works, you could call cart.php?runcommand=xyz on the click button and in cart.php you could check if $_GET['runcommand'] == 'xyz' then do x. You'll find jQuery javascript library has good AJAX support.
Preferably you would not having everything in one php file, then you can just make AJAX request to different files for different purposes. In your case, listproducts.php, for example.

I think you are looking for something like this:
<script type="text/javascript" language="javascript">
function showHide() {
var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
<form method="post" action="">
<p><input type="button" value="Show-Hide" onclick="return showHide();" /></p>
</form>
<div id="showHideDiv" style="display:none;">hello!</div>

Related

How I can do remember text in input

I have two problems with the following code, i.e.
I would like saved values in input to be remembered, because now it returns the value " Notice : Undefined variable: name_check in".
If the domain length is shorter than 5 characters, it returns an error but only at the first input, and I would like the validation error to be at each of the inputs.
<?php
require_once "connect.php";
$connect = #new mysqli($host, $db_user, $db_password, $db_name);
if(isset($_POST['send']))
{
$all_ok=true;
$id = $_POST['id'];
$domain_name = $_POST['domain_name'];
foreach ($domain_name as $value)
{
if (strlen($value)<5)
{
$all_ok=false;
$_SESSION['e_name']="Wpisana domena jest zbyt króka.";
}
}
$_SESSION['fr_name'] = $value;
if ($all_ok==true)
{
$count = count($id);
for($i=0;$i<$count;$i++) {
$connect->query('UPDATE domains SET domain_name="'.$domain_name[$i].'" WHERE id='.(int)$id[$i].'');
}
$_SESSION['well_done']=true;
echo "udana walidacja";
}
}
?>
<style>
.error
{
color:#cc0000;
margin-top: 5px;
margin-bottom: -5px;
font-size:12px;
}
</style>
<form method="POST" action="">
<table>
<?php
$result = $connect->query("SELECT * FROM domains");
$how_nick = $result->num_rows;
if ($how_nick != 0) {
while($data = $result->fetch_assoc())
{
?>
<tr>
<td>Nazwa Domeny:<br> <input type="text" value="<?php
if (isset($_SESSION['fr_name']))
{
echo $_SESSION['fr_name'];
unset($_SESSION['fr_name']);
}
else
{
echo $data['domain_name'];
}
?>" name="domain_name[]"><br /><?php
if (isset($_SESSION['e_name']))
{
echo '<div class="error">'.$_SESSION['e_name'].'</div>';
unset($_SESSION['e_name']);
}
?></td>
<td><input type="hidden" name="id[]" value="<?php echo $data['id'];?>"/></td>
</tr>
<?php
}}
?>
</table>
<br /><center><input class="button" type="submit" name="send" value="Zapisz"></center>
</form>

PHP SQL Insert text value into database

I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...

PHP Update shows previous database entry's

I'm currently just coding around in my free time and follow up some random tutorials that other developers/coder's created in there spare time. Now I'm stuck with something very small. I have been trying to find a answer on the interwebz but I cant seem to find one, so here I'm hoping that someone is willing to read my PHP and HTML and see the error I created.
But before I share my code let me tell you what my problem is and what I try to achieve.
If you go to the following link "removed because problem is solved." and when you click on Home/About/Service/Random, you are able to edit one of these menu's. (title, posistion, visible). Now when I want to change the menu name "Home" to "Welcome" it correctly execute my SQL but for some reason, in the HTML Form it loads it's previous information. What I can do is copy the PHP and save it in a new php file and when clicking on submit it will change both menu/title/html form at the same time, but it wont show my succes and fail message anymore. I hope any of you understand what I'm trying to explain here and try to achieve. Now lets share the code.
PHP
<? find_selected_page(); ?>
<?
if (intval($_GET['info']) == 0){
redirect_to("content.php");
}
if(isset($_POST['submit'])){
$errors = array();
$required_fields = array('menu', 'position', 'visible');
foreach ($required_fields as $fieldname){
if (!isset($POST[$fieldname]) || (empty($_POST[$fieldname]) &&
!is_numeric($_POST[$fieldname]))) {
$errors [] = $fieldname;
}
}
$fields_with_lengths = array('menu' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength) {
if(strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength){
$errors[] = $fieldname;
}
}
$id = mysql_prep($_GET['info']);
$menu = mysql_prep($_POST['menu']); //use post array cuz we used post var to coll val in form
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE information SET menu = '{$menu}', position = {$position}, visible = {$visible} WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
$message = "The information was correctly updated.";
} else {
//failed
}
} else { //errors
}
?>
HTML
<? require_once ("includes/functions.php"); ?>
<? require_once ("includes/connect.php"); ?> //HERE IS MY CONNECTION TO MY DATABASE
///HERE IS MY PHP CODE
<? include ("includes/header.php"); ?>
<div id="content"> <!-- content here -->
<table id="table">
<tr>
<td id="nav">
<? echo navigation($sel_table1, $table2); ?>
</td>
<td id="main">
<h2>Edit Info <? echo $sel_table1['menu']; ?></h2>
<? if (!empty($message)) { echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="edit_info.php?info=<? echo urlencode($sel_table1['id']); ?>" method="post"/>
<p>Menu title
<input type="text" name="menu" value="<? echo ($sel_table1['menu']); ?>" id="menu">
</p>
<p>Position
<select name="position">
<?
$info_set = get_all_info();
$info_count = mysql_num_rows($info_set); //asks how many rows there are should be 3
for($count=1; $count <= $info_count+1; $count++){
echo "<option value='{$count}'";
if($sel_table1['position'] == $count){
echo "selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"
<? if ($sel_table1['visible'] == 0){ echo "checked"; } ?>
/>No
<input type="radio" name="visible" value="1"
<? if ($sel_table1['visible'] == 1){ echo "checked"; } ?>
/>Yes
</p>
<input type="submit" name='submit' value="Edit information" />
</form> <br>
Cancel
</td>
</tr>
</table>
</div>
<? include ("includes/footer.php");?> //HERE I HAVE IF ISSET MYSQL CLOSE
And a more simple short version of the story is, I want to update the menu's with the success and failure message's without getting the old previous data in my HTML FORM
if needed for any reasons I have included the part of my functions.php where $sel_table and $table2 are staying.
function find_selected_page(){
global $sel_table1;
global $table2;
if (isset($_GET['info'])){
$sel_table1 = get_info_by_id($_GET['info']);
$sel_t2 = 0;
$table2 = NULL;
} else if (isset($_GET['page'])){
$table1 = 0;
$sel_table1 = NULL;
$table2 = get_pages_by_id($_GET['page']);
} else {
$table1 = NULL;
$sel_table1 = NULL;
$table2 = 0;
}
}
function navigation($sel_table1, $table2){
$output = "<ul class='info'>";
$info_set = get_all_info();
while ($info = mysql_fetch_array($info_set))
{
$output .= "<li"; if ($info["id"] == $sel_table1 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='edit_info.php?info=" . urlencode($info["id"]) . "'>{$info['menu']}</a></li>";
$page_set = get_pages_for_info($info["id"]);
$output .= "<ul class='pages'>";
while ($page = mysql_fetch_array($page_set))
{
$output .= "<li"; if ($page["id"] == $table2 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='content.php?page=" . urlencode($page["id"]) . "'>{$page['menu']}</a></li>"; }
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}

Keeping Dynamic Table Rows shown after form post errors

I have a dynamic HTML table that allows users to enter receipt items in, and they can add as many rows as necessary.
If they forget to fill out a field upon form POST, I want all those rows with the data to stay shown, instead what happens, is they dynamic rows disappear and no values are saved in the one row that shows on default.
How can I achieve having those dynamic table rows shown with the values they've entered to avoid them having to enter all the data again?
<?php
if(isset($saveAdd))
{
$expenseType = safeDataMySQL($_POST['expenseType']);
//Save page, redirect to same page but increment receipt number.
if(empty($_POST['expenseNumber']))
{
//New expense so no records have been created as of yet. Otherwise, this would be stored in hidden field.
$getRef = mysql_query("SELECT CAST(SUBSTRING(refNumber,4) AS UNSIGNED INTEGER) AS referenceNumber FROM expense_main ORDER BY referenceNumber DESC LIMIT 1") or die("Ref No: " . mysql_error());
if(mysql_num_rows($getRef) > 0)
{
while($refData = mysql_fetch_array($getRef))
{
//Expense Number!
$refNumber = $refData['referenceNumber'];
$refNumber = ($refNumber + 1);
}
$ins = mysql_query("INSERT INTO `expense_main` (`respid`, `refNumber`, `dateCreated`, `draftMode`, `expenseType`) VALUES ('".$respid."', 'USA".$refNumber."', NOW(), '1', '".$expenseType."')") or die("Expense Insert: " . mysql_error());
$expClaimNumber = 'USA'.$refNumber;
}
}
else
{
$expClaimNumber = safeDataMySQL($_POST['expenseNumber']);
}
//Get the next receipt in line as well
$getRec = mysql_query("SELECT receiptNumber FROM expense_details ORDER BY receiptNumber DESC LIMIT 1") or die("Get Receipt: " . mysql_error());
if(mysql_num_rows($getRec) > 0)
{
while($recData = mysql_fetch_array($getRec))
{
$receiptNumber = $recData['receiptNumber'];
$receiptNumber = ($receiptNumber + 1);
}
}
$fields = array('recLineDate_', 'recLineCategory_', 'recLineDescr_', 'recLineAmount_');
foreach ($fields as $field)
{
foreach ($_POST[$field] as $key=>$line)
{
$returnArray[$key][$field] = $line;
}
}
foreach ($returnArray as $lineItem)
{
if(empty($lineItem['recLineDate_']))
{
$Errors[] = 'You forgot to enter the receipt date.';
}
else
{
$recDate = safeDataMySQL($lineItem['recLineDate_']);
}
if(empty($lineItem['recLineCategory_']))
{
$Errors[] = 'You forgot to enter a category.';
}
else
{
$recCategory = safeDataMySQL($lineItem['recLineCategory_']);
}
if(empty($lineItem['recLineDescr_']))
{
$Errors[] = 'You forgot to enter a description.';
}
else
{
$recDescr = safeDataMySQL($lineItem['recLineDescr_']);
}
if(empty($lineItem['recLineAmount_']))
{
$Errors[] = 'You forgot to enter your receipt amount.';
}
else
{
$recAmount = safeDataMySQL($lineItem['recLineAmount_']);
}
if(empty($_POST['alternateBranch']))
{
$alternateBranch = '0';
}
else
{
$alternateBrach = $_POST['alternateBranch'];
}
if(!isset($Errors))
{
$recDate = date("Y-m-d", strtotime($recDate));
$ins = mysql_query("INSERT INTO `expense_details` (`receiptNumber`, `claimId`, `alternateBranch`, `dateAdded`, `expenseDate`, `expenseDescription`, `expenseAmount`, `categoryId`)
VALUES ('".$receiptNumber."', '".$expClaimNumber."', '".$alternateBranch."', NOW(), '".$recDate."', '".$recDescr."', '".$recAmount."', '".$recCategory."')") or die("Could not insert receipt: " . mysql_error());
$nextReceipt = ($receiptNumber + 1);
//Redirect to same page, incrementing the receipt number by 1.
header('Location: createExpense.php?expenseNumber='.$expClaimNumber.'&receiptNum='.$nextReceipt);
}
}
}
$expenseNumber = safeData($_GET['expenseNumber']);
$receiptNumber = safeData($_GET['receiptNum']);
if (isset($Errors))
{
echo "<div align='center'><span class='errormessagered'><ul class='errors'>";
foreach ($Errors as $Error)
{
echo "<li>".$Error."</li>";
echo '<br />';
}
echo "</ul></span></div>";
}
?>
<form name="createNew" method="POST" action="">
<div id="row">
<div id="left">
<strong>Receipt Items:</strong>
</div>
<div id="right">
<i>Only add another line to the receipt below IF you have multiple items on one receipt.</i>
<br /><br />
<table border="0" width="825px" cellspacing="0" cellpadding="5" name="receipts" id = "receipts">
<thead>
<tr>
<th class="colheader" width="120px">Date</th>
<th class="colheader" width="120px">Category</th>
<th class="colheader" width="120px">Description</th>
<th class="colheader" width="120px">Amount</th>
<th class="colheader" width="145px"><span class="boldblacklinks">[Add +]</span></th>
</tr>
</thead>
<tbody class="lineBdy">
<tr id="line_1" class="spacer">
<td><input type="text" class="date fieldclasssm" id="recLineDate[]" name="recLineDate_[]" size="10" value = "<?=date("m/d/Y", strtotime($today))?>"/></td>
<td><select name="recLineCategory_[]" class="fieldclasssm">
<option value = "">Select a Category...</option>
<?php //Get Categories
$getCats = mysql_query("SELECT id, nominalName FROM expense_nominalCodes ORDER BY id") or die("Get Cats: " . mysql_error());
if(mysql_num_rows($getCats) > 0)
{
while($catData = mysql_fetch_array($getCats))
{
echo '<option value = "'.$catData['id'].'"'; if($catData['id'] == $_POST['recLineCategory_']) { echo "Selected = 'SELECTED'"; } echo '>'.$catData['nominalName'] . '</option>';
}
}
?>
</select>
</td>
<td><input type="text" class="lineDescr fieldclasssm" name="recLineDescr_[]" id="recLineDescr[]" value = "<?=$_POST['recLineDescr']?>" size="40" /></td>
<td colspan = "2"><input type="text" class="sum lineAmount fieldclasssm" name="recLineAmount_[]" id="recLineAmount[]" value = "<?=$_POST['recLineAmount']?>" size="12" /></td>
</tr>
</tbody>
</table>
</div>
" />
" />
<script type="text/javascript">
$(document).ready(function () {
$('.date').change(function () {
$('.date').val($('.date:nth-of-type(1)').val());
});
});
//Add new table row & clone date field
$('#add').on('click', function(){
addReceiptItem();
$('.date').focus(function() {
$(this).select();
});
$('.receipt').focus(function() {
$(this).select();
});
});
function addReceiptItem(){
var lastID = $('tr[id*="line_"]').length,
newTds = $('tr[id="line_' + lastID + '"] td').clone(),
newRow = document.createElement('tr');
// add new id and class to row, append cloned tds
$(newRow)
.attr('id', 'line_' + (lastID + 1 ))
.attr('class', 'spacer')
.append(newTds);
$(newRow).find('input').not(':eq(0)').val('');
// $(newRow).find('class').not(':eq(0)').not(':eq(0)').val('');
//add the new row to the table body
$('tbody.lineBdy').append(newRow);
$('.receipt').attr('readonly', true);
$('.date').attr('readonly', true);
};
</script>
Just to get you started. You can add the rows from $_POST["rows"]
foreach ($_POST["rows"] as $rowstring) {
list($date, $cat, $desc, $amt) = explode(",", $rowstring)
?>
<td><?php echo $date; ?></td>
<td><?php echo $cat; ?></td>
<td><?php echo $desc; ?></td>
<td><?php echo $amt; ?></td>
<td> </td>
<?php
}
Assuming you add a hidden input with a comma delimited string each time a dynamic row is added.
FWIW, I would also recommend doing all of the database queries (ie $getCats = ...) prior to rendering anything to the screen so that in case the 'or die()' happens, you wont get a half rendered page.

Using PHP to query db, fetch results via AJAX as variable, query db again using values of initial variable

It's all in the question really :)
It's clearer when I put it in bullet points what I want to do, so here it goes:
I have two forms on a page, a search form, and an 'edit profile' form. Both are in working order, individually.
The edit profile form paginates through the rows of my MySQL tbl, allowing my to edit the values for each column. Currently set up to include all rows (i.e. all stored profiles).
the search form takes any of 17 different search variables and searches that same table to find a profile, or a group of profiles.
I want to be able to enter a search term (e.g. Name: 'Bob'), query the tbl as I am doing, but use AJAX to return the unique ID's of the results as an an array stored within a variable. I then want to be able to asynchronously feed that variable to my edit profile form query (the search form would have a submit button...) so I can now page through all the rows in my table (e.g. where the Name includes 'Bob'), and only those rows.
Is the above possible with the languages in question? Can anyone help me piece them together?
I'm at an intermediate-ish stage with PHP and MySQL, but am an absolute novice with AJAX. I've only ever used it to display a text string in a defined area - as seen in demos everywhere :) Therefore, treating me like a five-year-old is greatly appreciated!
Here are my current search query, and the edit-profile form, if they help at all:
The Edit Profile form:
//pagination base
if (isset($_GET['page'])) { $page = $_GET['page']; }
else { $page = 1; }
$max_results = 1;
$from = (($page * $max_results) - $max_results);
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM profiles"),0);
$total_pages = ceil($total_results / $max_results);
echo '<span id="pagination">' . 'Record ' . $page . ' of ' . $total_results . ' Records Returned. ';
if($total_results > $max_results)
{
if($page > 1)
{ $prev = ($page - 1);
echo "<input type='submit' value='<<' />";
}
if($page == 1)
{ echo "<input type='submit' value='<<' />"; }
if($page < $total_pages)
{ $next = ($page + 1);
echo "<input type='submit' value='>>' />";
}
if($page == $total_pages)
{ echo "<input type='submit' value='>>' />";
}
}
echo '</span></p>';
?>
// the query, currently selecting all but which I would have include a WHERE clause (WHERE ProfileID = $profileid...)
<?php
$sql = ("SELECT * FROM profiles
ORDER BY ProfileID
LIMIT $from, $max_results");
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
$profile = $row['ProfileID'];
?>
<form id="profile-form" action="profile-engine.php" method="post">
<input type="hidden" name="formid" value="edit-profile">
<input type="hidden" name="thisprofile" value="<?php echo $profile; ?>">
<table id="profile-detail" class="profile-form">
<tr>
<td>
<label for="profile-name">Name:</label>
<?php
$nameresult = mysql_query("SELECT ProfileName
FROM profiles
WHERE ProfileID = '$profile'");
$row = mysql_fetch_array($nameresult);
?>
<input type="text" class="text" name="profile-name" id="profile-name" value="<?php echo $row['ProfileName']; ?>" />
</td>
//goes on in this vein for another 16 inputs :)
The Search Query:
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
switch ($param) {
case "name":
$whereClause .= " AND ProfileName LIKE '%".$_POST[$param]."%' ";
break;
case "height":
$whereClause .= " AND ProfileHeight='".$_POST[$param]."' ";
break;
case "gender":
$whereClause .= " AND ProfileGenderID='".$_POST[$param]."' ";
break;
//more cases....
}
}
}
$query .= $whereClause;
$result = mysql_query("$query");
$values = array();
while ($row = mysql_fetch_array($result)) {
$values[] = $row['ProfileID'];
}
/*
//just me checking that it worked...
foreach( $values as $value => $id){
echo "$id <br />";
}
*/
mysql_close($con);
So, there you have it! Thanks in advance for any help!
what about:
search copies search term to local variable, service returns an array of results that you hold, and then pagination uses JS to drop in the values into the appropriate fields. If you change one and save, it submits the edits, including the original search term, which is used to re-query the service, and returns the updated array...repeat as necessary
here's some sample code (here there's just two search fields, I know you need more):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var query = new Object();
var resp;
var i;
function next(on){
i=on+1;
if(i==resp.results.length){i--;}
fillForm(i);
}
function prior(on){
i=on-1;
if(i<0){i++;}
fillForm(i);
}
function fillForm(i){
document.getElementById("paginate").innerHTML='<button onclick="prior('+i+')"><</button>'+(i+1)+' of '+resp.results.length+'<button onclick="next('+i+')">></button>';
document.getElementById("name").value=resp.results[i].name;
document.getElementById("height").value=resp.results[i].height;
document.getElementById("gender").value=resp.results[i].gender;
document.getElementById("class").value=resp.results[i].class;
document.getElementById("death").value=resp.results[i].death;
document.getElementById("appro").value=resp.results[i].appro;
document.getElementById("born").value=resp.results[i].born;
document.getElementById("tobiano").value=resp.results[i].tobiano;
document.getElementById("modifier").value=resp.results[i].modifier;
document.getElementById("adult").value=resp.results[i].adult;
document.getElementById("birth").value=resp.results[i].birth;
document.getElementById("sire").value=resp.results[i].sire;
document.getElementById("dam").value=resp.results[i].dam;
document.getElementById("breeder").value=resp.results[i].breeder;
document.getElementById("owner").value=resp.results[i].owner;
document.getElementById("breed").value=resp.results[i].breed;
document.getElementById("location").value=resp.results[i].location;
document.getElementById("id").value=resp.results[i].id;
document.getElementById("saveButton").innerHTML='<button onclick="save()">Save</button>';
}
function getData(){
query.name=document.getElementById('query_name').value;
query.gender=document.getElementById('query_gender').value;
var variables='';
variables+='name='+query.name;
variables+='&gender='+query.gender;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","searchNav.php?"+variables,true);
xmlhttp.send();
}
function save(){
var saving="";
saving+='?q='+query;
saving+='&name='+document.getElementById('name').value;
saving+='&height='+document.getElementById('height').value;
saving+='&gender='+document.getElementById('gender').value;
saving+='&class='+document.getElementById('class').value;
saving+='&death='+document.getElementById('death').value;
saving+='&appro='+document.getElementById('appro').value;
saving+='&born='+document.getElementById('born').value;
saving+='&tobiano='+document.getElementById('tobiano').value;
saving+='&modifier='+document.getElementById('modifier').value;
saving+='&adult='+document.getElementById('adult').value;
saving+='&birth='+document.getElementById('birth').value;
saving+='&sire='+document.getElementById('sire').value;
saving+='&dam='+document.getElementById('dam').value;
saving+='&owner='+document.getElementById('owner').value;
saving+='&breed='+document.getElementById('breed').value;
saving+='&breeder='+document.getElementById('breeder').value;
saving+='&location='+document.getElementById('location').value;
saving+='&id='+document.getElementById('id').value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","saveEdits.php"+saving,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="search">
<table>
<tr><td>Name:</td><td><input type="text" id="query_name" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="query_gender" /></td></tr></table>
<button onclick="getData()">Search</button>
</div>
<div id="results">
<div id="paginate"></div>
<input type="hidden" id="id" />
<table>
<tr><td>Name:</td><td><input type="text" id="name" /></td></tr>
<tr><td>Height:</td><td><input type="text" id="height" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="gender" /></td></tr>
<tr><td>Class:</td><td><input type="text" id="class" /></td></tr>
<tr><td>Death:</td><td><input type="text" id="death" /></td></tr>
<tr><td>Appro:</td><td><input type="text" id="appro" /></td></tr>
<tr><td>Born:</td><td><input type="text" id="born" /></td></tr>
<tr><td>Tobiano:</td><td><input type="text" id="tobiano" /></td></tr>
<tr><td>Modifier:</td><td><input type="text" id="modifier" /></td></tr>
<tr><td>Adult:</td><td><input type="text" id="adult" /></td></tr>
<tr><td>Birth:</td><td><input type="text" id="birth" /></td></tr>
<tr><td>Sire:</td><td><input type="text" id="sire" /></td></tr>
<tr><td>Dam:</td><td><input type="text" id="dam" /></td></tr>
<tr><td>Breeder:</td><td><input type="text" id="breeder" /></td></tr>
<tr><td>Owner:</td><td><input type="text" id="owner" /></td></tr>
<tr><td>Breed:</td><td><input type="text" id="breed" /></td></tr>
<tr><td>Location:</td><td><input type="text" id="location" /></td></tr>
</table>
<div id="saveButton"></div>
</div>
</body>
</html>
and the search:
<?php
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
$whereClause .= " AND ".$param."='".$_POST[$param]."'";
}
}
$query .= $whereClause;
$result = mysql_query("$query");
echo "{\"results\":";
if($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "[";
echo "{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
else{
echo "\"no\"}";
exit;
}
while($row = mysql_fetch_array($data,MYSQL_ASSOC)){
echo ",{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
echo "]}";
?>

Categories