我正在尝试从下表中的codes
列返回5个未使用的值,然后将相关行中的used
设置为1.
|--- codes ---| | used |
| FIomQVu71l | | 0 |
| 4TW0lwLWNK | | 0 |
| SjzLB2Shzr | | 0 |
| uTWJrtCgh4 | | 0 |
| tLwOwYGz5R | | 0 |
| byEhzYMWJG | | 0 |
| XFBmGzDGIR | | 0 |
我设法让代码工作从codes
输出5个随机值,其中使用了= 0
<?php
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
?>
但是现在我很遗憾如何更新每个输出used
的{{1}}值。我的所有尝试都将codes
的每个实例更新为1,而不仅仅是与5 used
相关联的实例
答案 0 :(得分:0)
您可以将行存储在临时表中。请注意,这并不完全是并发安全的。如果insert
和update
之间存在其他查询,则可能会获取相同的行。
CREATE TEMPORARY TABLE IF NOT EXISTS tmp_codes (codes varchar(50));
-- Get five new rows
INSERT INTO tmp_codes
(codes)
SELECT codes
FROM code_table
WHERE used = 0
ORDER BY
rand()
LIMIT 5;
-- Update the five rows
UPDATE code_table
SET used = 1
WHERE codes in
(
SELECT codes
FROM tmp_codes
);
-- Return to application
SELECT codes
FROM tmp_codes;
DROP TABLE tmp_codes;
答案 1 :(得分:0)
您应该执行更新查询:
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
$codes = array();
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
$codes[] = "'" . $rows['codes'] . "'";
}
$updateSql = "UPDATE code_table SET used = 1 WHERE codes in(" . implode (',' , $codes ) . ")";
$res = mysql_query($updateSql, $connection);