【问题标题】:Insert multiple rows mysql插入多行mysql
【发布时间】:2015-03-19 21:36:54
【问题描述】:

我有以下代码:

<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li><a href="home.php">Home</a></li>
<li><a href="catalogue.php">Catalogue</a></li>
<li><a href="search.php">Search</a></li>
<li><a href= "view_cart.php">Cart</a></li>
<li><a href="#">Orders</a></li>
</ul>
<div id = "welcome" >
Welcome, <?=$_SESSION['login_user']?>! <br> <a href="logout.php">Logout</a>
</div>
</div>
<br><br>
<h1 id = "mainHeader" >View Cart</h1>
<br>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["books"]))
{
$total = 0;
echo '<form method="post" action="">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["books"] as $cart_itm){
$ISBN = $cart_itm["ISBN"];
$results = $mysqli->query("SELECT Title,BookDesc,Price FROM books WHERE ISBN='$ISBN'");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["ISBN"].'&return_url='.$current_url.'">×</a></span>';
echo '<div class="p-Price">'.$currency.$obj->Price.'</div>';
echo '<div class="book-info">';
echo '<h3>'.$obj->Title.' (ISBN :'.$ISBN.')</h3> ';
echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
echo '<div>'.$obj->BookDesc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$ISBN.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->BookDesc.'" />';
echo '<input type="hidden" name="item_quantity['.$cart_items.']" value="'.$cart_itm["quantity"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '<button name="submit_btn" class="save_order">Save Order</button>';
echo '</form>';
if(isset($_POST['submit_btn']) ){
$insquery = "INSERT INTO `pending_orders` (`OrderNo`,`BookName`,`Quantity`,`TotalPrice`,`ISBN`,`StudentID`) VALUES (NULL, '" . $obj->Title . "', '" . $cart_itm['quantity'] . "', '" . $total . "', '" . $ISBN . "', '" . $_SESSION['login_user'] . "');";
$stmt = $mysqli->prepare($insquery);
$stmt->execute();
}
}
?>
</div>
</div>
</body>
</html>

该代码应该将客户的预订订单保存到数据库中,它对一本书非常有效。第 76 到 81 行有插入语句。 但是,如果此人购买了两本书,那么只有最后一本书会被添加到数据库中。添加截图:

这就是我网站上的样子。如您所见,此人已选择要购买的两本书: http://postimg.org/image/3kj1gvytx/ 然而,这是我在我的 phpmyadmin 网站中得到的: http://postimg.org/image/k85hs56xj/ 我们可以看到只有第二本书(生物学)存储在数据库中。以及两本书的总和

关于如何解决问题并存储这两本书的任何想法。

谢谢

【问题讨论】:

  • 在这种情况下,您可以使用 Ajax 异步请求添加项目而无需刷新页面。
  • 我该怎么做?我从来没有真正使用过 Ajax
  • 等一下(我会在这里更新)...

标签: php mysql


【解决方案1】:
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li><a href="home.php">Home</a></li>
<li><a href="catalogue.php">Catalogue</a></li>
<li><a href="search.php">Search</a></li>
<li><a href= "view_cart.php">Cart</a></li>
<li><a href="#">Orders</a></li>
</ul>
<div id = "welcome" >
Welcome, <?=$_SESSION['login_user']?>! <br> <a href="logout.php">Logout</a>
</div>
</div>
<br><br>
<h1 id = "mainHeader" >View Cart</h1>
<br>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["books"]))
{
$total = 0;
echo '<form method="post" action="">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["books"] as $cart_itm){
$ISBN = $cart_itm["ISBN"];
$results = $mysqli->query("SELECT Title,BookDesc,Price FROM books WHERE ISBN='$ISBN'");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["ISBN"].'&return_url='.$current_url.'">×</a></span>';
echo '<div class="p-Price">'.$currency.$obj->Price.'</div>';
echo '<div class="book-info">';
echo '<h3>'.$obj->Title.' (ISBN :'.$ISBN.')</h3> ';
echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
echo '<div>'.$obj->BookDesc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="itemname_['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="itemcode_['.$cart_items.']" value="'.$ISBN.'" />';
echo '<input type="hidden" name="itemdesc_['.$cart_items.']" value="'.$obj->BookDesc.'" />';
echo '<input type="hidden" name="itemquantity_['.$cart_items.']" value="'.$cart_itm["quantity"].'" />';
echo '<input type="hidden" name="total_['.$cart_items.']" value="'.$total.'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '<button name="submit_btn" class="save_order">Save Order</button>';
echo '</form>';
if(isset($_POST['submit_btn']) ){
    $item_array = array();


    foreach($_POST as $key => $value) {
 // echo "POST parameter '$key' has '$value';
        $pieces = explode("_",$key)
        if(strstr($pieces[0] == 'itemname')
        {
            $item_array[$pieces[1]]['BookName'] = $value;

        }
        if(strstr($pieces[0] == 'itemcode')
        {
            $item_array[$pieces[1]]['ISBN'] = $value;
        }

        if(strstr($pieces[0] == 'itemquantity')
        {
            $item_array[$pieces[1]]['Quantity'] = $value;
        }
        if(strstr($pieces[0] == 'total')
        {
            $item_array[$pieces[1]]['TotalPrice'] = $value;
        }
}

$insquery = "INSERT INTO `pending_orders` (`OrderNo`,`BookName`,`Quantity`,`TotalPrice`,`ISBN`,`StudentID`) VALUES ";
foreach($item_array as $row)
{
    $insquery .= "(NULL, '" . $row['BookName'] . "', '" . $row['Quantity'] . "', '" .$row['TotalPrice']. "', '" . $row['ISBN'] . "', '" . $_SESSION['login_user'] . "'),";
}

$insquery = substr($insquery, 0, -1);
$stmt = $mysqli->prepare($insquery);
$stmt->execute();

    foreach($_POST as $row)
$insquery = "INSERT INTO `pending_orders` (`OrderNo`,`BookName`,`Quantity`,`TotalPrice`,`ISBN`,`StudentID`) VALUES (NULL, '" . $obj->Title . "', '" . $cart_itm['quantity'] . "', '" . $total . "', '" . $ISBN . "', '" . $_SESSION['login_user'] . "');";
$stmt = $mysqli->prepare($insquery);
$stmt->execute();
}
}
?>
</div>
</div>
</body>
</html>

你像上面那样形成插入语句

【讨论】:

    【解决方案2】:

    由于您不了解 Ajax,您可以执行以下操作: 1) 重置 $result 数组,以再次选择项目进行 MySQL 查询。 2) 使用 while 循环将每个选定的值插入 DB。

    reset($result);
    while($row=mysqli_fetch_array($result))
    {
        $ins = mysqli_query($con, "Here goes insert statement for each");
    }
    

    编辑

    $ISBN = $cart_itm["ISBN"];
    $con = mysqli_connect("localhost","root","","yourbasename");
    $result = mysqli_query($con, "SELECT Title,BookDesc, Price FROM books    
    WHERE ISBN='$ISBN'");
    while($row=mysqli_fetch_array($result)
    {
        $insert = mysqli_query($con, "INSERT.....");
    }
    

    【讨论】:

    • 我假设 id 将代码放在 if(isset($_POST['submit_btn']) ){ 行之后?
    • 在第 79 行收到一个错误,显示意外 {。
    • while($row=mysqli_fetch_array($result)) -> 我忘了一个“)”。用两个“))”试试这个
    • ( ! ) 警告:reset() 期望参数 1 为数组,在第 77 行的 C:\wamp\www\view_cart.php 中给出 null
    • 忘记reset(),只需再次进行选择查询并插入项目,解决方案是循环遍历您的数组项目而不是仅插入一个。所以你可以拥有自己的解决方案实现,因为你现在不能插入两本书的原因。 :)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 2014-09-25
    • 2015-08-12
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多