我试图将一行从一个表移到另一个表但它不起作用。它确实把第一条线做好了,但是没有什么我可以得到其余的回声,好吧就是不要进入我的数据库。
$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;
?>
答案 0 :(得分: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'];
?>
答案 1 :(得分: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`
这是数据库最擅长的(我想除了存储数据之外)。