我有这个SQL语句从orders表中提取一个值(OrderID
)。
"SELECT DISTINCT (MAX(OrderID)) FROM orders WHERE Username = 'hello@hello.com';
我通过PHPMyAdmin运行它,它为该用户返回一个订单ID,这完全是我想要的。但是,我试图在PHP中运行它...
"SELECT DISTINCT (MAX(OrderID)) FROM orders WHERE Username = '". $_SESSION['Username'] ."'";
我想要提取订单ID,然后我可以设置$OrderID = (the result from the select statement)
,然后运行更新语句,如下所示。
$sql = "UPDATE orders SET Status = 'Failed' WHERE Status = 'Success' and OrderID = ". $OrderID ."";
如果我硬代码$OrderID = 90;
它完美无缺,但我需要OrderID通过登录的人的会话来完成。
完整代码:
<?php
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if (strpos($url,'order-failed') !== false) {
$servername = "NULL";
$username = "NULL";
$password = "NULL";
$dbname = "NULL";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check Connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT DISTINCT (MAX(OrderID)) FROM orders WHERE Username = '". $_SESSION['Username'] ."'";
echo $query . "<br />";
$OrderID = 93;
echo $OrderID;
echo "<br />";
$sql = "UPDATE orders SET Status = 'Failed' WHERE Status = 'Success' and OrderID = ". $OrderID ."";
echo $sql;
if ($conn->query($sql) === TRUE) {
echo "<br />Record updated successfully";
}
else {
echo "<br />Error updating record: " . $conn->error;
}
$conn->close();
}
else {
session_destroy();
}
?>
答案 0 :(得分:3)
看起来这会产生同样的效果......
$sql = "
UPDATE orders
SET Status = 'Failed'
WHERE Status = 'Success'
AND Username = '{$_SESSION['Username']}'
ORDER
BY OrderID DESC
LIMIT 1;
";
...虽然明显重写它以使用预准备语句语法
答案 1 :(得分:0)
在顶部添加会话开始
<?php
session_start();
// your code here
答案 2 :(得分:0)
替换
echo $query . "<br />";
$OrderID = 93;
echo $OrderID;
echo "<br />";
与
$result = $conn->query($query);
$row = $result->fetch_row();
$OrderID = $row[0];
并做其他所有人说的话
http://php.net/manual/en/mysqli-result.fetch-row.php
答案 3 :(得分:-1)
首先,测试会话变量是否存在以及在select语句中为max()函数指定别名可能是明智的。
> library(curl)
> h <- new_handle()
> l2<-"http://rediff.com"
> curl_download(l2,"b.txt",handle=h)
> system("lsof | grep rediff")
> l3<-"http://materialresourcing.com/tags/diy"
> curl_download(l3,"c.txt",handle=h)
> system("lsof | grep materialresourcing")
R 17936 xxxx 7u IPv4 3559514 0t0 TCP ip-10-0-xx:40844->vps.materialresourcing.com:http (CLOSE_WAIT)
sh 18257 xxxx 7u IPv4 3559514 0t0 TCP ip-10-0-xx:40844->vps.materialresourcing.com:http (CLOSE_WAIT)
grep 18259 xxxx 7u IPv4 3559514 0t0 TCP ip-10-0-xx:40844->vps.materialresourcing.com:http (CLOSE_WAIT)
>