简体   繁体   English

PHP MySQL购物车未在数据库中更新

[英]PHP MySQL Shopping Cart not updating in database

I am trying to let the user update quantities in the textfields on the page, then update existing items in their cart in the database with the new values of the textfields on the page. 我试图让用户更新页面上文本字段中的数量,然后使用页面上文本字段的新值更新数据库中购物车中的现有项目。

The quantities are not being updated, but no errors are being generated either. 数量未更新,但也未生成错误。

I can't see any problems with my code, and I'm just at a complete loss as to what could be causing this to not work. 我看不到我的代码有任何问题,而对于可能导致此问题不起作用的原因我完全不知所措。

Code: 码:

<?php


     // If post is not null, then add selected data to corresponding sessionid in database.
if($_SESSION['last_access'] != null && $_REQUEST["product"] != null)
{
   // Sanitize information.
   $info = new SimpleSanitize('post', 'both');

   $product = $info->get('product');
   $quantity = $info->get('qty');
   $price = $info->get('price');
foreach($_POST['items'] as $p=>$q)
{
 $connection =
        mysql_connect("my01.tadah.com","blah","passsword");

 if($connection)
 {
  mysql_select_db("mysql_9269_dbase", $connection);

  mysql_query(
          "UPDATE mysql_9269_dbase.sessions SET qty='".$q."' WHERE product='".$p."'")
               or die(mysql_error());
  // Assume items added successfully.
  $ItemAddedMessage = "Quantities changed.";

  // Close connection to database.
  mysql_close($connection);
 }
 else
 $ItemAddedMessage = null;
}}

?>
<?php

//Include SimpleSanitize.
include 'simplesanitize.php';

// First attempt at PHP Sessions. Wish me luck.
$ItemAddedMessage = "Adjust your quantities, then click Purchase.";
// Start the session.
session_start();

if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 71200 )
 $_SESSION['last_access'] = time();



// 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, 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']  = '5000'; // 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);
//$product_id = $ct->data[$key][0];

foreach($ct->data as $key => $value){
   $ct->data[$key][0]='<p name="product">'.$ct->data[$key][0].'</p>';
   $ct->data[$key][1]='<input id="quantity" name="items[' . $ct->data[$key][1] . ']" type="text" value="'.$ct->data[$key][1].'" style="background:#FFFFFF url(qty.png) no-repeat 4px 4px;
                        padding:4px 4px 4px 30px;
                        border:1px solid #CCCCCC;
                        width:220px;
                        height:18px;" />';
   $ct->data[$key][2]='<p name="price">'.$ct->data[$key][2].'</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);

  $out = '<form name="ct_form" action="checkout.php" method="post">' . $out;
  $out=$ct->display();

}

?>

<!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 | One Stop Fasteners</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>
<script language="javascript" type="text/javascript">
        function submit() {
                 document.getElementById('ct_form').submit();
                 }
</script>
<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 '<a href="javascript:submit();">Purchase</a>'; ?></form></h2>
   <h3 class="message"><?php echo $ItemAddedMessage . $_REQUEST["quantity"]; ?></h3>
   <p></p>
   <div id="container">
  <?php echo $out;?>
</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>
    <p>Copyright © 2010, <a href="http://www.onestopfasteners.com.au/">One Stop Fasteners&reg;</a>. All Rights Reserved</p>
    <div class="clr"></div>
  </div>
</div>
</body>
</html>

Can someone please tell me what I am doing wrong? 有人可以告诉我我做错了什么吗?

Any help at all is much appreciated. 任何帮助都非常感谢。

Thanks! 谢谢!

This is not your answer, but you should take a look, really... 这不是你的答案,但你应该看看,真的......

http://en.wikipedia.org/wiki/SQL_injection http://en.wikipedia.org/wiki/SQL_injection

Since you don't get any error messages you have three options here: 由于您没有收到任何错误消息,因此这里有三个选项:

Your $_SESSION["last_action"] or $_REQUEST["product"] is null (please use is_null() to check for null values) 您的$_SESSION["last_action"]$_REQUEST["product"]为空(请使用is_null()检查空值)

Your $_POST["items"] is empty, likely, cause there is no check in your code before this is executed. 您的$_POST["items"]可能是空的,因为在执行此操作之前您的代码中没有检查。

OR 要么

Your $connection is not correct. 您的$connection不正确。

These three options are the most logical ones. 这三个选项是最合乎逻辑的选项。 But it is very difficult to determine with this kind of code. 但是用这种代码很难确定。

Besides these possibilities, I completely understand you can't find out why this is not working. 除了这些可能性之外,我完全理解您无法找出为什么这不起作用。 The code is really unclear and you should consider using any kind of design pattern. 代码真的不清楚,您应该考虑使用任何一种设计模式。 This code will be a nightmare to maintain. 这段代码将成为维护的噩梦。

Just my two cents. 只是我的两分钱。

Good luck! 祝好运!

This code is a procedural spaghetti mess. 此代码是程序上的意大利面乱七八糟。 I have no idea where to begin reading it and I would need to run the code on my machine to debug it. 我不知道从哪里开始阅读它,我需要在我的机器上运行代码来调试它。 I think you need to stick a few var_dump s here and there to work out where the data does not match what you are expecting. 我认为您需要在这里和那里粘贴一些var_dump ,以找出数据与您期望的数据不匹配的地方。

However it looks like the problem could be in the foreach($_POST['items'] as $p=>$q) and I suspect it should be something like: 然而,看起来问题可能在foreach($_POST['items'] as $p=>$q) ,我怀疑它应该是这样的:

foreach($_POST['items'] as $item) {
    $q = $item['q'];
    $p = $item['p'];
}

Stylistic tip: THere is absolutely no need to create/close mysql handles within a loop as you are. 风格提示:绝对不需要在循环中创建/关闭mysql句柄。 A single connection can be used to run multiple queries, and you'll save the overhead of the repeated connect/disconnect. 单个连接可用于运行多个查询,您将节省重复连接/断开连接的开销。 So, instead of 所以,而不是

while(...) {
   $con = msyql_connect(...);
   if (!$con) {
      ...
   }
   ... do stuff
   mysql_close($con);
}

Change to 改成

$con = mysql_connect(...);
if (!$con) {
   ...
}
while(...) {
    ... do stuff
}
mysql_close($con);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM