I'm trying to populate a MySQL table with some data, but, mysqli won't let me insert every 10th stat
- by Tunji Gbadamosi
I want to initialise a 'ticket' table with some ticket IDs. To do this, I want to insert 120 ticket IDs into the table. However, at every 10th statement, MySQL tells me that the ID already exists and thus won't let me insert it. Here's my code:
//make a query
$insert_ticket_query = "INSERT INTO ticket (id) VALUES (?)";
$insert_ticket_stmt = $mysqli->stmt_init();
$insert_ticket_stmt->prepare($insert_ticket_query);
$insert_ticket_stmt->bind_param('s', $ticket_id);
$mysqli->autocommit(FALSE); //start transaction
for($i=0;$i<NO_GUESTS;$i++){
$id = generate_id($i);
$ticket_id = format_id($id, $prefix['ticket'], $suffix['ticket']);
$t_id = $ticket_id;
//echo '<p>'.$ticket_id.'</p>';
//$result = $mysqli->query("SELECT * FROM ticket WHERE id='".$ticket_id."'");
//$row_count = $result->num_rows;
if(($result = $mysqli->query("SELECT * FROM ticket WHERE id='".$t_id."'")) == FALSE){
$result->close();
if($insert_ticket_stmt->execute()){
$mysqli->commit();
echo "<p>".$t_id."added to the ticket table!</p>";
}
else{
$mysqli->rollback();
echo "problem inserting'".$t_id."' to the ticket table";
}
}
else{
echo "<p>".$t_id."already exists, so not adding it!</p>";
$result->close();
}
}
$mysqli->autocommit(TRUE);
$insert_ticket_stmt->close();
?>