0

我正在尝试将一行从一个表移动到另一个表,但它不起作用。它的第一行很好,但没有什么我可以让其余的回声好,只是不要进入我的数据库。

$result = mysql_query("SELECT * FROM coffees WHERE id='$id'");

while($row = mysql_fetch_array($result)) {
  mysql_query("INSERT INTO coffeeorder(coffeetype,topping,shots,milk,size,price) VALUES ('coffeetype', 'topping', 'shots', 'milk', 'Size', 'price')");

  echo $row['coffeetype'] . " " . $row['topping']." " . $row['shots']." " . $row['milk']." " . $row['size']." $" . $row['price']."<br />";

  $totalPrice = $totalPrice + $row['price'];
}

任何想法为什么这不起作用?

完整代码:

<?php 
session_start();
if(isset($_SESSION["id"])){

$id = $_SESSION["id"];
$name = $_SESSION["name"];


}else {header('Location: index.php');}

 include_once "dbcon.php";
    $totalPrice = 0;
    $result = mysql_query("SELECT * FROM coffees WHERE id='$id'");
while($row = mysql_fetch_array($result))
  {

      mysql_query("INSERT INTO `coffeeorder`(`coffeetype`,`topping`,`shots`,`milk`,`size`,`price`) VALUES ('".$row['coffeetype']."', '".$row['topping']."', '".$row['shots']."', '".$row['milk']."', '".$row['size']."', '".$row['price']."')");




  echo $row['coffeetype'] . " " . $row['topping']." " . $row['shots']." " . $row['milk']." " . $row['size']." $" . $row['price']."<br />";

  $totalPrice = $totalPrice + $row['price'];

  }
    echo "Total Price $".$totalPrice;


?>
4

2 回答 2

3

请尝试移至 PDO:

<?php
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    $stmt = $db->query("SELECT * FROM coffees WHERE id=:id");
    $stmt->execute(array(':id' => $id));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $db->query("INSERT INTO coffeeorder(coffeetype,topping,shots,milk,size,price) VALUES (:coffeetype, :topping, :shots, :milk, :size, :price)");
    $stmt->execute(array(':coffeetype' => $row['coffeetype'], ':topping' => $row['topping'],':shots' => $row['shots'],':milk' => $row['milk'],':size' => $row['size'],':price' => $row['price']));
    echo $row['coffeetype'] . " " . $row['topping']." " . $row['shots']." " . $row['milk']." " . $row['size']." $" . $row['price']."<br />";

    $totalPrice = $totalPrice + $row['price'];

?>
于 2012-09-01T02:46:57.047 回答
3

您还可以在一个查询中同时执行插入和选择:

INSERT INTO `coffeeorder` (
    `coffeetype`,
    `topping`,
    `shots`,
    `milk`,
    `size`,
    `price`
)
SELECT
    `coffeetype`,
    `topping`,
    `shots`,
    `milk`,
    `size`,
    `price`
FROM `coffees`
WHERE `id`='$id'

但是,这会导致多个表中的重复数据。你真正应该做的是把你的表设置得有点不同,在 coffeeorder 表中,而不是存储关于咖啡的所有信息,只存储咖啡的 id。然后在查询出订单的时候,就可以加入咖啡桌,获取咖啡信息。

SELECT
   `coffee`.`coffeetype`,
   `coffee`.`topping`,
   `coffee`.`shots`,
   `coffee`.`milk`,
   `coffee`.`size`,
   `coffee`.`price`
FROM `coffeeorder`
    JOIN `coffee`
        ON `coffee`.`id`=`coffeeorder`.`coffee_id`

这是数据库最擅长的(我猜除了存储数据)。

于 2012-09-01T02:54:05.160 回答