开发者

php mysql save mysql with for loop

TABLE:

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)" )  
}

I want the data to be saved twice and increment the id_timeslot.

The above code working fine, but when save cliked. it didnt pick up the right id_timeslot?

for example: if user click on id_timeslot:1, so开发者_开发百科on it save to database the id_timeslot starts from 2 instead of id_timeslot 1?


if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?

This is because you're using a pre-increment rather than a post-increment. If $id_timeslot is 1 before entering the loop, the value of ++$id_timeslot is 2, so the first generated query is:

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

If the id_timeslot column is supposed to be an ID for the bookslot record, the best approach is to declare it with the AUTO_INCREMENT attribute and don't insert values for that column:

-- 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)";

When using double quoted strings, you don't need to concatenate variables. Compare the above statement with your own.

If id_timeslot isn't a unique ID, then you can simply switch to post-increment.

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

This may or may not be a correct approach for various other reasons. Without knowing more about the schema, it's impossible to say.

Off Topic

Depending on where the values for $id_member, $b_ref $id_doctor originate, your script could be open to SQL injection. Rather than inserting values directly into the string, use a prepared statement. MySQLi supports them, as does PDO, which is simpler to use. New code should use PDO, and old code should get updated over time.


You have to fetch last id_timeslot from database and then increase it PHP during inserting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜