【问题标题】:php mysql save mysql with for loopphp mysql 用for循环保存mysql
【发布时间】:2011-02-21 16:54:38
【问题描述】:

表格:

09:00 -- id_timeslot = 1
09.15 -- id_timeslot = 2
09.30 -- id_timeslot = 3
09.45 -- id_timeslot = 4
10.00 -- id_timeslot = 5

PHP MYSQL:

for($i=0; $i<=2; $i++) {  
  $mysqli->query("INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)   
  VALUES  ('" . ++$id_timeslot . "', '" . $id_member . "', '" . $b_ref . "', '" . $id_doctor . "', 1)" )  
}

我希望将数据保存两次并增加 id_timeslot。

上面的代码工作正常,但是当点击保存时。它没有选择正确的 id_timeslot?

例如:如果用户点击 id_timeslot:1,很快就会将 id_timeslot 从 2 开始而不是 id_timeslot 1 保存到数据库?

【问题讨论】:

    标签: php mysql for-loop


    【解决方案1】:

    如果用户点击 id_timeslot:1,很快就会将 id_timeslot 从 2 开始而不是 id_timeslot 1 保存到数据库?

    这是因为您使用的是前increment 而不是后增量。如果进入循环前$id_timeslot为1,则++$id_timeslot的值为2,所以第一个生成的查询为:

    "INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)   
     VALUES  ('2', '$id_member', '$b_ref', '$id_doctor', 1)"
    

    如果 id_timeslot 列应该是书架记录的 ID,最好的方法是使用 AUTO_INCREMENT 属性声明它,并且不要为该列插入值:

    -- run just once in some MySQL client
    ALTER TABLE bookslot MODIFY id_timeslot INT UNSIGNED PRIMARY KEY AUTO_INCREMENT;
    
    // in PHP
    $stmt = "INSERT INTO bookslot(id_member, b_ref, id_doctor, status)   
             VALUES  ('$id_member', '$b_ref', '$id_doctor', 1)";
    

    使用双引号字符串时,不需要连接变量。将上述陈述与您自己的陈述进行比较。

    如果 id_timeslot 不是唯一 ID,那么您可以简单地切换到后增量。

    $stmt = "INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)   
             VALUES  (" . $id_timeslot++ . ", '$id_member', '$b_ref', '$id_doctor', 1)";
    

    由于各种其他原因,这可能是正确的方法,也可能不是正确的方法。如果不了解架构的更多信息,就不可能说出来。

    题外话

    根据 $id_member、$b_ref $id_doctor 的值的来源,您的脚本可能对SQL injection 开放。不要将值直接插入到字符串中,而是使用准备好的语句。 MySQLi 支持它们,PDO 也支持它们,使用起来更简单。新代码应该使用 PDO,而旧代码应该随着时间的推移而更新。

    【讨论】:

      【解决方案2】:

      您必须从数据库中获取最后一个id_timeslot,然后在插入期间增加它的 PHP。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        • 2011-11-30
        相关资源
        最近更新 更多