I am having trouble setting up a query, it seems very simple but I cannot seem to determine if my database logic is incorrect or whether the query is incorrect.
There is one database with 3 tables, clients, orders and package.
The clients table has 3 fields, ID{primary key auto increment), email (varchar) and organisation (varchar).
The orders table has 10 fields, ID(from above), OderID (PRimary, autoincrement), WorkID (from package table), and othr fields relating to file paths, comments, feedback and date.
The package table has 2 fields, WorkID (primary Key autoincrem), name(varchar)
This is what I want the query to do:
The query must get all the rows from orders table where WorkID= 1 and must get the organisation field from clients based on each order. I am then going to order the rows by date.
Am I meant to be suing a join to get this query to work or is there a flaw in the database logic? Now yes I already know there is an error below as i am not comparing an ID from the two tables, but what I want to happen is for it to first get all the rows from orders where WorkID = 1 then add the clients.organisation field to each row found from WorkId = 1 where ID from clients corresponds to the ID assigned to that row.
Thanks for any help
$query = "SELECT *
FROM orders INNER JOIN clients ON orders.ID = clients.ID
WHERE WorkID = 1
ORDER BY Date DESC";
WORKING NOW__________________________------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>
Ok guys ive got the query working but for some odd reason the number of rows being echoed in while loop i have set up is always 1 less than num_rows. Anyone have any idea as to why? This is my echo
<?php
include "../includes/connect.php";
$query = "SELECT *
FROM orders INNER JOIN clients ON orders.ID = clients.ID
WHERE WorkID = 1
ORDER BY Date DESC";
$result = mysqli_query( $link , $query );
?>
<!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></title>
<meta name="google-site-verification" content="qH5HloAtcJbjEVuEx3vDy_Rmj7Zjw8Mtsuuqdrd1c3Y" />
<link href="../styles/dark-main.css" rel="stylesheet" type="text/css" />
<link href="../styles/nivo-slider.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../styles/jquery.galleryview-3.0.css" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="../scripts/jquery.nivo.slider.pack.js"></script>
<script type="text/javascript" src="../scripts/page-scripts.js"></script>
<script type="text/javascript" src="../scripts/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="../scripts/jquery.galleryview-3.0.js"></script>
<script type="text/javascript" src="../scripts/jquery.timers-1.2.js"></script>
<script type="text/javascript" src="../scripts/validator.js"></script>
</head>
<body class="portfolio">
<!--TOPBAR STARTS HERE-->
<?php include"../includes/topbar.php"; ?>
<!--TOPBAR ENDS HERE-->
<!--HEADER STARTS HERE-->
<?php include"../includes/header.php"; ?>
<!--HEADER ENDS HERE-->
<!--SLIDER STARTS HERE-->
<?php include"../includes/slider.php"; ?>
<!--SLIDER ENDS HERE-->
<!--MIANCONTENT STARTS HERE-->
<div class="contentcontainer">
<div class="contentcontainercenter">
<div class="portfoliowrapper">
<h2>Portfolio</h2>
<div class="box">
<div id="conversionworks" class="conversionwork">
<h3>Heading</h3>
<span class="message"> message </span>
<div class="blockwrapper">
<?php
while( $row = mysqli_fetch_array( $result ) ){
echo '
<div class="itembox">
<div class="imagewrapper">
<a class="thumbnail" href=""><img src='. $row['ThumbPath'].' /><span><img src='. $row['FilePath'].' /></span></a>
</div>
<div class="detailsbox">
Company:<span class="details"> '.$row['Organisation'].' </span><br />
Theme:<span class="details"> '.$row['Theme'].' </span><br />
Uses:<span class="details"> '.$row['Tech Used'].' </span>
</div>
</div>'
;}
?>
Also i have a question i regards to safety of a database. I have file paths stored in the database which get echoed according to each record fetch no user interaction all done via the server on page load, is it insecure to do so?
2nd question i have mutiple queries on the 1 page, what would be the best way to include each query where it is required? (Would putting it in a separate file and calling it before the echo be best?)
You probably need something like that:
SELECT *
FROM orders o
INNER JOIN clients c ON (c.id = o.id)
WHERE o.WorkID = 1
ORDER BY `Date` DESC
Some side notices : you should change your column naming convention to something more descriptive (I'm talking about orders.id which is in your case is a reference to clients.id). Personally, I prefer to use id as a primary key in each table. Some people like to name it as [TABLE_NAME]_id, in your case order_id, client_id. Secondly, don't use *; list all required fields. Also, I'd recommend to use a newer sql syntax for joining table (use JOIN keyword instead of listing all tables in FROM clause).
Yes using a join would be what you want to do (a left join actually). You can read about them here, or put your tables into a readable state; and I can give you an example.
Related
I'm creating a web app which displays datas contained in a database.
I wrote the code and the app works, at least whith basic functions.
I'm already thinking about the future and that's why I'm asking for your help.
In case I will change the name of database's columns or maybe adding some new columns I will have to modify every single page of my code, if I want them to be shown in my web app.
For this reason I'd like to ask you if it is possible to write the columns name I want to import in a text file and then call this file to define which database's columns should be displayed on the net.
I'm attaching you the code I have write now so that you can understand better the part I want to change (which is the one of the 'while loop').
<html>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div id="holder">
<h1><?php echo "<font face=verdana size=30 color=#036>CAMBIO AMINOACIDICO</font>";?></h1></div>
<br>
<div id="sidebar" style="width:90%" class="sidebar">
NUOVA RICERCA
  |
RICERCA PER PAZIENTE
  |
RICERCA PER GENE
  |
RICERCA PER VARIANTE
  |
HOME
<P> </P>
</div>
<div class="container">
<?php
$conn= mysql_connect("loc", "db", "pss");
if (!$conn)
{
die("Connessione non riuscita <br>" . mysql_error());
//}else{
//echo "Connessione al database stabilita con successo<br><br>";
}
mysql_select_db("variant_db", $conn);
if(isset($_POST["vai"])){
$aa=$_POST["aa"];
}
echo "Verranno visualizzate le varianti per il seguente cambio di aminoacido:'<b>$aa</b>'.";?>
<br /><br />
<?php
$sql="SELECT A.AAchange, V.dnaCode, V.Chr, A.Start, A.End, A.Alt, A.Ref, V.zygosity, A.gene FROM annotazioni as A JOIN variante as V ON V.Start = A.Start AND V.Alt=A.Alt AND V.Ref=A.Ref WHERE A.AAchange='$aa'";
$result_dna = mysql_query($sql, $conn) or die(mysql_error());
if(mysql_num_rows($result_dna) == 0)
{
echo "<br>La ricerca non ha prodotto alcun risultato!<br>";
echo"<b>Effettuare una nuova ricerca.</b><br><br>";
}else
{?>
<div class="row">
<div class="col-mid-8 col-mid-offset-2">
<table id="table_var" "width=100%" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>AAchange</th>
<th>dnaCode</th>
<th>Chr</th>
<th>Start</th>
<th>End</th>
<th>Alt</th>
<th>Ref</th>
<th>Zigosity</th>
<th>Gene</th>
</tr>
</thead>
<tbody>
<?PHP
while ($record_dna=mysql_fetch_array($result_dna)){
echo '
<tr>
<td>'.$record_dna['AAchange'].'</td>
<td>'.$record_dna['dnaCode'].'</td>
<td>'.$record_dna['Chr'].'</td>
<td>'.$record_dna['Start'].'</td>
<td>'.$record_dna['End'].'</td>
<td>'.$record_dna['Alt'].'</td>
<td>'.$record_dna['Ref'].'</td>
<td>'.$record_dna['zygosity'].'</td>
<td>'.$record_dna['gene'].'</td>
</tr>
';
}
};?>
</tbody>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script>
<script type="text/javascript" src="js/ddtf.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" >
$('#table_var').ddTableFilter();
</script>
</body>
</html>
Keeping table names in txt or xml doesn't really solve anything and brings too much extra code.
For Examle say you have a table Z that has colums A, B C. And you have a piece of code that looks like SELECT A, B, C FROM Z. And you have some php logic after that.
FIRST EXAMPLE
You decided that you need to add column D to your table Z.
FIRST QUESTION
Will you need to select the data from the column D?
FIRST PROBLEM
If you need to select and process the data from column D, changing SELECT A, B, C FROM Z to SELECT A, B, C, D FROM Z probably won't be enough because you did not have any php logic that processed D before that, and you have to add it now. - Lots of extra code of controlling execution logic.
SECOND EXAMPLE
You decided that you don't need data column C in your table Z and you want do delete the whole column.
SECOCD PROBLEM
Here, changing SELECT A, B, C FROM Z to SELECT A, B FROM Z is 100% not enough.
You had some php code that proccesed data from C column, but now you have no C column, and the code must be removed. Also lots of extra code of controlling execution logic.
THIRD EXAMPLE
Your boss suddenly told you to add colunm N and you had no prior knolwedge that this will happen.
THIRD PROBLEM
You could'n have forseen it in any way, so in no way you could make all the needed extra code earlier. You still have to do everything manually.
All the examples above a ment to show, that you even if you add the code for controlling execution logic, in general you cannot predict what changes the structure might get.
All the extra code looses it's value, because you made a change that you did not forsee, and besides re-writing original logic, you also have to re-write the whole code for extra logic now.
Combining everything above, developing the code comes with the risk of having to re-write it, if and when some major structure changes occur.
I hope it was somewhat informative.
Hi I am working on some sort of a CMS page and I want to show on the /index.php page a list of all articles availble like /index.php?p=Art1.
And I have no clue on how to do that.
Any help is appreciated.
This is my index.php code:
<html>
<head>
<link rel="stylesheet" href="css/login-layout.css">
</head>
<body>
<div class="dialog-box">
<h2 style="font-size: 200%;margin-bottom: 0;">Pagini Noi</h2>
<h3 style="text-align: right; font-size:100%;margin-top: 0;">Logheazate pentru a edita paginile</h3>
<div class="pages">
<!-- Pagini \/ -->
<?php
include('config.php');
?>
</div>
</div>
</body>
</html>
Config.php contains the connection to the database $db is the variable name that i use.
The /index.php?p=Art1 method is actually a $_GET that you need to fetch. In your current example you would do:
$p = $_GET['p'];
Which if you would later echo:
echo $p;
you would get
Art1
but even before that, you should provide us with some database query example that you wish to do so we could show you how variable $p is passed on to a query that then selects the wanted rows from the table in your database. For simple mysql query you can check here: https://www.w3schools.com/php/func_mysqli_query.asp
WARNING: be sure to use mysqli_real_escape_string($p) in order to get a minimum protection from SQL injections.
On my site when a user is logged in, they can give a 1-5 rating on a movie.
What I want to do is make it so that database knows which user gave the rating and to update there rating if they click it again rather than creating a new entry, so each user can not have more than one rating per movie.
Tables:
login - id, user, password
movies - id, movie_name, movie_year
user_movie_ratings - id, user_id, movie_id, rating
At the moment when you login, you're taken to a members page the session is checked to ensure you're logged in, and then the list of all the movies is displayed and then when you click the move name you get take to a rating page where you can give it a rating of 1-5, then you are taken back to the movie page and the avg total rating is displayed beside the move name.
The user can just keep doing this over and incorrectly changing the avg rating.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<?php
require_once 'sessionCheck.php';
require_once 'init.php';
$query = $con ->query
("
SELECT movies.id, movies.movie_name, AVG(user_movie_ratings.rating) AS rating
FROM movies
LEFT JOIN user_movie_ratings
ON movies.id = user_movie_ratings.movie_id
GROUP BY movies.id
");
$movieTitle = array();
while($row = $query->fetch_object()) {
$movieTitle[] = $row;
}
?>
<head>
<title>Members</title>
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="login">
<?php include 'loginCheck.php';?>
</div>
</div>
<div class="content">
<?php foreach($movieTitle as $movie):?>
<div class = "movies">
<h3>
<a href="movie.php?id=<?php echo $movie->id; ?>">
<?php echo $movie->movie_name; ?></a>
</h3>
<div class="movie-rating">
Rating: <?php echo round($movie->rating); ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<div id="footer"> This is the Footer</div>
</div>
</body>
</html>
I would make a separate table with both user_id and movie_id.
Table - users
id
username
...
Table - movies
id
title
...
Table - ratings
id (auto)
movie_id
user_id
[edit]
If you make an unique index of both movie_id and user_id, the database will only accept each user to vote once/movie. If the same user tries to vote on the same movie more than once, a SQL-error will be created, unless you use INSERT IGNORE or ON DUPLICATE KEY UPDATE (if you want to accept that the user changes the rating).
[edit again - IMPORTANT]
You need to make both id:s in the same unique-index, if you create one index/id, each user ID will only be accepted once, and the same thing goes for the movies. (you don't want that)
(correct me if I'm wrong anyone?)
I've managed to get one stock table to display in the cart page when the user selects an item to purchase but I can't figure out how to get more than one table from different pages to display.
Any help would be appreciated!
<?php
session_start();
$cart=$_SESSION["cart"];
extract($_POST);
if (IsSet($productid)||IsSet($_SESSION["notempty"])) $empty=false;
else $empty=true;
if (!$empty)
{
if (IsSet($cart[$productid])) $cart[$productid]+=$quantity;
else $cart[$productid]=$quantity;
$_SESSION["notempty"]=true;
}
$_SESSION["cart"]=$cart;
$conn=mysql_connect("","");
mysql_select_db("webent",$conn);
mysql_query("CREATE TABLE Stock (stock_ID INT(3) NOT NULL PRIMARY KEY AUTO_INCREMENT,
itemName VARCHAR(50),itemDesc VARCHAR(100),
itemImage VARCHAR(10),itemStock VARCHAR(3),
itemPrice VARCHAR(5))");
?>
<!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" dir="ltr">
<head>
<title>Jus' Books</title>
<link href="style2.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="masthead">
</div>
<div id="navigation">
<p>Home
Fiction
Travel
Sport
Arts & Design
Shopping Cart
Manage Account</p>
</div>
<div id="content">
<?php
if ($empty) echo "<h4>Your shopping cart is empty</h4>";
else
{
echo "<h4>Your shopping cart contains:</h4>";
$total="";
foreach ($cart as $id=>$no)
{
if ($id!="")
{
$result=mysql_query("SELECT * FROM Stock WHERE stock_ID= $id");
$row=mysql_fetch_array($result);
extract($row);
if ($itemStock<$no) $no=$itemStock;
echo "<p>$no units of item $itemName at $itemPrice each</p>";
}
$total+=$no*$itemPrice;
}
echo "<p>Total to pay: £$total</p>";
}
?>
Continue Shopping
Proceed to Checkout
<p></p>
</div>
<div id="footer">
<p>Home |
Fiction |
Travel |
Sport |
Arts & Design |
Shopping Cart |
Manage Account</p>
</div>
</div>
</body>
</html>
The other tables have the exact same fields but have the name Stock_Travel
Stock_Sport
Stock_Arts
I can't figure out how to get more than one table from different pages to display
What do you mean by that? If you want to select from different tables, alter the query:
$result=mysql_query("SELECT * FROM Stock_Travel WHERE stock_ID= $id");
$result=mysql_query("SELECT * FROM Stock_Sport WHERE stock_ID= $id");
$result=mysql_query("SELECT * FROM Stock_Arts WHERE stock_ID= $id");
I hope this is some kind of homework assignment, since it's full of tiny flaws that wouldn't be nice in a production environment.
As you see, the database layout is far from optimal. Why isn't Travel/Sport/Arts stored in a Category field in the Stock table? That way you don't have to alter your query based on the kind of product page you're on.
Furthermore, I wouldn't rely on extract(), but that's personal. You definitely will want to escape your queries, or rather use prepared statements.
Here is the code for Checkout.php:
<?php
//Include SimpleSanitize.
include 'simplesanitize.php';
// First attempt at PHP Sessions. Wish me luck.
// Start the session.
session_start();
$product = $_REQUEST["product"];
$qty = $_REQUEST["qty"];
$price = $_REQUEST["price"];
//var_export($product);
//var_export($qty);
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 71200 )
$_SESSION['last_access'] = time();
// If post is not null, then add selected data to corresponding sessionid in database.
if($_SESSION['last_access'] != null && $qty != null)
{
// Sanitize information.
$info = new SimpleSanitize('request', 'both');
//$product = $info->get('product');
//$quantity = $info->get('qty');
//$price = $info->get('price');
$connection =
mysql_connect("..com","","");
if($connection)
{
mysql_select_db("__dbase", $connection);
foreach($arr as $key => $value){ echo "$key: $value ";}
print_r($val);
$query = "UPDATE sessions SET qty='".$val."' WHERE sessionid='".session_id()."' AND product='".$item."'";
mysql_query($query)
or die(mysql_error());
// Assume items added successfully.
$ItemAddedMessage = "Item added to cart.";
// Close connection to database.
mysql_close($connection);
}
else
$ItemAddedMessage = "Quantities updates";
}
// Open the DB connection and select the DB - creates the function getCreativePagerLyte()
include('configurations.php');
// Gets the data
$id=isset($_POST['id']) ? $_POST['id'] : '';
$search=isset($_POST['search']) ? $_POST['search'] : '';
$multiple_search=isset($_POST['multiple_search']) ? $_POST['multiple_search'] : array();
$items_per_page=isset($_POST['items_per_page']) ? $_POST['items_per_page'] : '';
$sort=isset($_POST['sort']) ? $_POST['sort'] : '';
$page=isset($_POST['page']) ? $_POST['page'] : 1;
$extra_cols=isset($_POST['extra_cols']) ? $_POST['extra_cols'] : array();
// Uses the creativeTable to build the table
include('creativeTable.php');
$ct=new CreativeTable();
// Data Gathering
$params['sql_query'] = 'SELECT product, qty, price FROM sessions WHERE sessionid="'.session_id().'"'; // IMPORTANT: you must specify the fields and not use *
$params['search'] = $search;
$params['multiple_search'] = $multiple_search;
$params['items_per_page'] = $items_per_page;
$params['sort'] = $sort;
$params['page'] = $page;
// Layout Configurations (Most used - the commented lines are the default values)
$params['header'] = 'Product, Quantity, User Action, Price'; // If you need to use the comma use , instead of ,
$params['width'] = ',,,';
//$params['search_init'] = true;
//$params['search_html'] = '<span id="#ID#_search_value">Search...</span><a id="#ID#_advanced_search" href="javascript: ctShowAdvancedSearch(\'#ID#\');" title="Advanced Search"><img src="images/advanced_search.png" /></a><div id="#ID#_loader"></div>';
//$params['multiple_search_init'] = 'hide';
$params['items_per_page_init'] = '10,20,50,100'; // default: '10*$i';
//$params['items_per_page_all'] = '#TOTAL_ITEMS#';
//$params['sort_init'] = true;
//$params['sort_order'] = 'adt';
//$params['ajax_url'] = $_SERVER['PHP_SELF'];
$ct->table($params);
foreach($ct->data as $key => $value){
$ct->data[$key][0]='<input type="text" value="'.$ct->data[$key][0].'" name="product" />';
$ct->data[$key][1]='<input type="text" value='.$ct->data[$key][1].' id="qty" name="qty" />';
$ct->data[$key][2]='<input type="submit" value="Update Item">';
$ct->data[$key][3]='<p name="price">'.$ct->data[$key][3].'</p>';
}
// If its an ajax call
if($_POST['ajax_option']!=''){
if(strpos($_POST['ajax_option'],'items_per_page')!==false)
$out_ajax['items_per_page']=utf8_encode($ct->draw_items_per_page());
if(strpos($_POST['ajax_option'],'body')!==false)
$out_ajax['body']=utf8_encode($ct->draw_body());
if(strpos($_POST['ajax_option'],'pager')!==false)
$out_ajax['pager']=utf8_encode(getCreativePagerLite($page,$ct->total_items,$ct->items_per_page));
echo json_encode($out_ajax);
exit;
}else{
// Insert a Pager into the table (I used this CreativePager Lite version because its very easy to use, but you may use any pager system that you like)
$ct->pager = getCreativePagerLite($page,$ct->total_items,$ct->items_per_page);
}
?>
<!DOCTYPE xhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/creative.css">
<title>Mild Steel Products</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js" ></script>
<script type="text/javascript" src="js/jquery.tools.min.js"></script>
<script type="text/javascript" src="js/cufon.js"></script>
<script src="js/Kozuka_Gothic.js" type="text/javascript"></script>
<!-- Fix for Internet Explorer 9 Beta -->
<!--[if gte IE 9]>
<script type="text/javascript">
Cufon.set('engine', 'canvas');
</script>
<![endif]-->
<script type="text/javascript" charset="utf-8">
// <![CDATA[
$(document).ready(function(){
Cufon.replace('h1,h2,h3', {
});
$(function() {
$("h3.message").delay(3000).fadeOut();
});
});
// ]]>
</script>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/creative_table.min.js"></script>
<script type="text/javascript" src="js/creative_table_ajax.min.js"></script>
</head>
<body>
<div class="main">
<div class="header">
<div class="logo"><img src="images/logo.png" border="0" alt="logo" /></div>
<div class="menu">
<ul>
<li>Home</li>
<li>Order Online</li>
<li>Products</li>
<li>About us</li>
<li>Contact us</li>
</ul>
</div>
<div class="clr"></div>
</div>
<div class="header_text2">
<h2> Checkout</h2>
<p>Adjust your quantities, then click purchase. </p>
<div class="clr"></div>
</div>
<div class="clr"></div>
<div class="top_sup_resize">
<div class="menu2">
<ul>
<!--<li>Allthread</li>
<li>Hex Nuts</li>
<li>Washers</li>
<li>Hex Bolt & Nut Kits, Setscrews</li>
<li>Screws</li>
<li>Cup Head Bolts & Nuts</li>-->
</ul>
</div>
<div class="clr"></div>
</div>
<div class="clr"></div>
<div class="body">
<div class="body_left">
<h2><?php echo $ItemAddedMessage; ?></h2>
<h3 class="message"></h3>
<div id="container">
<?php echo $out=$ct->display(); ?>
</div>
</div>
<p> </p></div>
<div class="clr"></div>
</div>
</div>
<div class="footer">
<div class="footer_resize">
<ul>
<li>home</li>
<li>order online</li>
<li>products</li>
<li>about</li>
<li>contact</li>
</ul>
<div class="clr"></div>
</div>
</div>
</body>
</html>
I am trying to submit a form on my page. It's proving to be a very difficult and frustrating task.
The problem is that there is no way of telling how many 'fields' will need to be submitted. The user might add 50 products to the cart, and make 30 changes to the quantities, or they might add 600 products to the cart and make 599 changes to the quantities (you never know), and with this website, the client is expecting high volume of sales so I need to be prepared for cases such as that.
I have a Table (a script that I bought) which has its own form tag for the data inside the table, however it uses GET not POST. And I am using:
foreach($_GET['items'] as $p=>$q)
{
// Update in database. This sql query has been tested, so I know it works, which means that the problem lies within the foreach loop, since it only stopped working when I added the foreach loop to update all form fields.
}
I have searched all ovver php.net, google and am out of ideas, and would greatly appreciate anyone's advice or help.
How can I update ALL form fields to the database?
Thanks
Edit:
The result of print_r($_GET); is:
Array ( [ct_items_per_page] => 10 [ct_sort] => t_t_t_t [ct_page] => 1 [ct_search] => [ct_items_per_page_change] => all [ct_multiple_search] => Array ( [0] => [1] => [2] => [3] => ) [product] => M5 x 1 MTR Allthread (Grade 304 Unit Price) [items] => Array ( [1] => 45 ) )
Edit:
What else would work in my situation? Does anyone have any links/tutorials/articles? I cannot find anything anywhere. Are there other ways to submit all fields to a database?
Lucifer,
You say you bought a script, why not initially contact who you bought it from for troubleshooting your issue?
What concerns me is that you list very little code, and so we are unable to help you because you simply say "it doesn't work! Please help me solve it!", well help us help you. Show us the FORM code, and the processing code.
Are you sure it is $_GET that the form is submitting as? Are you sure the variables are called $items[] in the form?
If I was solving this, or at least asking for help, I would list all the above code, and add plenty of debugging adding things like:
adding /* comment */ tags to comment out SQL inser sections (as you don't want to clean all that up each time you test).
adding var_dump tags to ouput as many variables as possible.
using Firefox Firebug for debugging if there is any javascript handlers that process the initial form.
UPDATE
11/23/2010
/checkout.php
I've done a quick review of your setup, you are using an AJAX table to manage searching / displaying your products. There are a couple methods you could try.
use jQuery serialize() to serialize (need to research this if you want to use this route) your data and submit it as a POST request to your backend (whatever that is? same checkout.php?).
You need to modify the checkout.php page to have an actual submit button, currently it is all handled via AJAX (javascript submit) which is setup for GET, not POST. You would have to update your FORM to be action="POST" as well. Add an actual submit button to your checkout form, you only have Update buttons which update the quantity.
Short of doing some consulting for you, there is not way to 'quickly' tell you what to change and where, this would take some time to modify, however I have outlined 2 options above you can tackle if you wish.