我的两个数据库阵列:
订购 - > (id,customer_id)
CUSTOMER - > (id,name)
他们有外键(order.customer_id和customer.id)。
我有一个带有文本字段和提交按钮的html表单,该用户提供了客户的名称,我想从查询中获取所选客户的订单。 这是我的代码,我在SELECT语句中有错误。 如果有人可以提供帮助......
<?php
$connect = mysql_connect("localhost", "root", "") or die("Unable to connect to MySQL");
$selected = mysql_select_db("eshop", $connect) or die("Could not select examples");
if (isset($_POST['name'])) {
$customerName = $_POST['name'];
}
$result = mysql_query("SELECT order.id
FROM order, customer
WHERE order.customer_id = customer.id
AND customer.name = $customerName
");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['order.id'];
}
mysql_close($connect);
?>
答案 0 :(得分:2)
order
是reserved word,因此请使用反引号将其换行。即:`order`
$result = mysql_query("SELECT `order`.id
FROM `order`, customer
WHERE `order`.customer_id = customer.id
AND customer.name = '$customerName'
");
您的密码:
if (isset($_POST['name'])) {
$customerName = trim($_POST['name']);
$result = mysql_query("SELECT `order`.id as OrderId
FROM `order`, customer
WHERE `order`.customer_id = customer.id
AND customer.name = '$customerName'
") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['OrderId'];
}
}
注意:使用mysqli_ *函数或PDO而不是mysql_ *函数(不建议使用)
答案 1 :(得分:0)
如果您的最终用户非常可靠,则为最小查询更改(添加变量字符串的引号)
$result = mysql_query("SELECT order.id
FROM order, customer
WHERE order.customer_id = customer.id
AND customer.name = '$customerName'
");
无论如何,逃避是非常重要的。
答案 2 :(得分:0)
试
$result = mysql_query("SELECT order.id
FROM order, customer
WHERE order.customer_id = '$customer.id'
AND customer.name = '$customerName'
");
并尝试为客户ID声明变量,然后插入双引号
答案 3 :(得分:0)
感谢您的回答。我有点失望,因为我在大学的老师使用错误的SQL方法,就像我发布的那样。这是学期课程。不管怎样,谢谢!