从一个表到另一个表并添加PHP MYSQL的命令

时间:2012-06-18 10:40:37

标签: php mysql database

我正在尝试从customer表到ordertracking表获取customerid。 - 但是 - 添加订单还需要从订单中获取的产品信息。我尝试了几种方法,但无法让它发挥作用。 还有一件奇怪的事情:

//connect to database
$connection = mysql_connect("localhost","root","") or die ("Can't connect");
mysql_select_db("shoppingcart", $connection) or die ("Can't connect");  

//check if already customer
$result = mysql_query("SELECT * FROM customer WHERE email='$email'");
$rows = mysql_num_rows($result);

    if ($rows) 
    {
      echo '<br>Welcome back ' . $name .' '. $surname. '<br>';
    }
    else
    {
        //if new customer, add to database
        $customer = "INSERT INTO customer (customerid, name, surname, email, city, GETalcode, phonenumber) VALUES ('', '$name', '$surname', '$email', '$city', '$postalcode', '$phonenumber')";
        if (!mysql_query($customer,$connection))
        {
            die('Error: ' . mysql_error());
            echo "Sorry, there was an error";
        }
        echo "New customer added" . "<br />";
        echo '<br>Welcome as our new customer ' . $name . ' '. $surname;

        mysql_close($connection);   
    }

//connect to database
$connection = mysql_connect("localhost","root","") or die ("Can't connect");
mysql_select_db("shoppingcart", $connection) or die ("Can't connect");

//get customer id
????????????????????
    //add new order
    $ordertracking = "INSERT INTO ordertracking (orderid, customerid, productid, brand, model, price, amount, totalcost) VALUES ('', '$customerid', '$productid', '$brand', 'model', 'price', 'amount', 'totalcost')";
    if (!mysql_query($ordertracking,$connection))
        {
            die('Error: ' . mysql_error());
            echo "Sorry, there was an error";
        }
        echo "New order added" . "<br />";

        mysql_close($connection);

4 个答案:

答案 0 :(得分:1)

就像您首先获得客户数据一样:

$customerid = mysql_fetch_row(mysql_query("SELECT customerid FROM customer WHERE email='$email'")); 
echo $customerid[0];

答案 1 :(得分:1)

在插入后使用mysql_insert_id()或在选择后使用$rows['customerid']

答案 2 :(得分:1)

$res = mysql_query("SELECT customerid FROM customer WHERE email='$email'");
while($row=mysql_fetch_array($res))
{
 $customerid=$row['customerid'];
}

在插入ordertracking表时使用此$ customerid

答案 3 :(得分:1)

$customer = "INSERT INTO customer (customerid, name, surname, email, city,
             GETalcode, phonenumber) VALUES 
            ('', '$name', '$surname', '$email', '$city',
             '$postalcode', '$phonenumber')";
        if (!mysql_query($customer,$connection))
        {
            die('Error: ' . mysql_error());
            echo "Sorry, there was an error";
        }
        else
        {
            $customer_id =mysql_insert_id();
        }   

//然后插入订单表