如何遍历页面上的表单字段并将其发送到数据库?

时间:2010-11-21 00:55:21

标签: php javascript mysql html forms

以下是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 &#44; 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"><a href="index.php"><img src="images/logo.png" border="0" alt="logo" /></a></div>
      <div class="menu">
        <ul>
<li><a href="index.php">Home</a></li>
<li><a href="products.php">Order Online</a></li>
<li><a href="products.php" class="active">Products</a></li>
<li><a href="about.php">About us</a></li>
<li><a href="contact.php">Contact us</a></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><a href="mildsteel_allthread.php" style="font-size:x-small; color:white;">Allthread</a></li>
          <li><a href="mildsteel_hexnuts.php" style="font-size:x-small; color:white;">Hex Nuts</a></li>
          <li><a href="mildsteel_washers.php" style="font-size:x-small; color:white;">Washers</a></li>
          <li><a href="mildsteel_hnbkss.php" style="font-size:x-small; color:white;">Hex Bolt &amp; Nut Kits, Setscrews</a></li>
          <li><a href="mildsteel_screws.php" style="font-size:x-small; color:white;">Screws</a></li>
          <li><a href="mildsteel_last.php" style="font-size:x-small; color:white;">Cup Head Bolts &amp; Nuts</a></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>&nbsp;</p></div>
     <div class="clr"></div>
  </div>
</div>
<div class="footer">
  <div class="footer_resize">
    <ul>
      <li><a href="index.php">home</a></li>
      <li><a href="products.php">order online</a></li>
      <li><a href="products.php">products</a></li>
      <li><a href="about.php">about</a></li>
      <li><a href="contact.php">contact</a></li>
    </ul>
            <div class="clr"></div>
  </div>
</div>
</body>
</html>

我正在尝试在我的网页上提交表单。事实证明这是一项非常困难和令人沮丧的任务。

问题在于无法确定需要提交多少“字段”。用户可能会向购物车添加50个产品,并对数量进行30次更改,或者他们可能会向购物车添加600个产品并对数量进行599次更改(您永远不会知道),并且通过此网站,客户期望值很高销售量所以我需要为这样的案件做好准备。

我有一个Table(我买的一个脚本),它有自己的表格内部数据的表格标签,但它使用GET而不是POST。我正在使用:

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.
}

我搜索了所有ovver php.net,谷歌和我的想法,并非常感谢任何人的建议或帮助。

如何将所有表单字段更新到数据库?

由于

编辑:

print_r的结果($ _ GET);是:

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 ) ) 

编辑:

在我的情况下还有什么用?有没有人有任何链接/教程/文章?我什么都找不到。是否有其他方法可以将所有字段提交到数据库?

1 个答案:

答案 0 :(得分:1)

萤光,

你说你买了一个脚本,为什么不最初联系你买的人来解决你的问题?

我担心的是你列出的代码很少,所以我们无法帮助你,因为你只是说“它不起作用!请帮我解决!”,帮助我们帮助你。向我们展示FORM代码和处理代码。

您确定表单提交为$_GET吗?您确定变量在表单中被称为$items[]吗?


如果我正在解决这个问题,或者至少要求帮助,我会列出以上所有代码,并添加大量调试,例如:

  1. 添加/* comment */标记以注释掉SQL inser部分(因为您不希望每次测试时都清除所有内容)。
  2. 添加var_dump标记以输出尽可能多的变量。
  3. 如果有任何javascript处理程序处理初始表单,则使用Firefox Firebug进行调试。

  4. <强>更新 11/23/2010 /checkout.php

    我已经快速审核了您的设置,您正在使用AJAX表来管理搜索/显示您的产品。您可以尝试几种方法。

    1. 使用jQuery serialize()来序列化(需要研究这个,如果你想使用这条路线)你的数据并将其作为POST请求提交给你的后端(不管是什么?同样checkout.php?)。
    2. 你需要修改checkout.php页面以获得一个实际的提交按钮,目前它都是通过AJAX(javascript submit)处理的,这是为GET设置的,而不是POST。您还必须将FORM更新为action="POST"。在结帐表单中添加实际的提交按钮,您只需Update按钮即可更新数量。

    3. 如果没有为你做一些咨询,就没有办法“快速”告诉你要改变什么,在哪里,这需要一些时间来修改,但是如果你愿意,我已经概述了你可以解决的两个选项。 / p>