【问题标题】:add rows with loop max value +1添加具有循环最大值 +1 的行
【发布时间】:2015-06-25 09:48:28
【问题描述】:

我正在尝试根据输入值向数据库中添加行。 即如果输入为“5”,查询将向数据库插入 5 行。 (这部分工作正常)

现在,我需要将 bed_number 比现有的 max(bed_number) +1,但我似乎无法让它工作。

如果现有的 max(bed_number) 返回 5,则查询应添加“6、7、8、9、10 等”作为 5 个条目的 bed_number。

如果现有的 max(bed_number) 返回 null,则应添加“1,2,3,4,5 等”

现在,无论最大计数如何,结果总是返回 1,2,3,4,5...。

我现在拥有的是:

global $conn;
if ($values["number_of_bed"])
{

$add1 = $values["number_of_bed"]+1;
$existingBed = "select Max(bed_number) from bed where bed =" '".$i."'" +1;

for ($i=1;$i<$add1;$i++)
{
 $strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$existingBed."')";


 db_exec($strInsert,$conn);
}
header("Location: bed_list.php");

 // Exit and Redirect to the list page after updating database
exit();

【问题讨论】:

  • 对不起,这是 php 5.3.13 / mysql 5.5.24
  • 真的是代码吗?因为,对我来说它看起来像语法错误。
  • 你需要在MAX()上+1 -> SELECT MAX(bed_number)+1 FROM bed WHERE bed = $i
  • 另外,在VALUES 中执行SELECT 时,不要使用VALUES 并用括号括起来()dev.mysql.com/doc/refman/5.1/en/insert-select.html 应该更像INSERT INTO bed (unit_id, bed_number) SELECT '$values["unit_id"]', MAX(bed_number)+1 FROM bed WHERE bed = $1
  • 为什么不让bed_number自动递增然后你就不用担心了?

标签: php mysql loops max


【解决方案1】:
//echo "Number of customers: " . $data["c"];

global $conn;
if ($values["bed_number"])
{

$add1 = $values["bed_number"]+1;


//for ($i=1;$i<$values["bed_number"];$i++)
for ($i=1;$i<$add1;$i++)
{
$sql = "select max(bed_number) as c from bed where unit_id =" . $values["unit_id"];
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$data["c"]."'+1)";
 // add more fields from the add page to be inserted into database

 db_exec($strInsert,$conn);
}
header("Location: bed_list.php");

 // Exit and Redirect to the list page after updating database
exit();

}

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 2014-08-18
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多