I have the following PHP function which will list the users from a MySql table and will print the HTML code as you can see:
//List All Users From The Database Table In An Array
public function listUsersInArray() {
$sql = "SELECT username FROM user";
$users = array();
if($stmt = $this->conn->prepare($sql)) {
$stmt->bind_result($usrn);
$stmt->execute();
while ($row = $stmt->fetch()) {
$stmt->bind_result($usrn);
$users[] = $usrn;
}
$stmt->close();
return $users;
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "The Users Could Not Stored In Array";
return json_encode($message);
}
}
//Build A Form In Order To Print Out The Users For Deleting
private function createForm($id) {
$form = array( '<form name="delete-user" id="'.$id.'" class="delete-user" method="post" action="#">',
'<input type="hidden" name="user_id" value="'.$id.'" />',
'<fieldset class="user-wrapper">',
'<label for="user" class="user-label">User</label>',
'<input type="text" name="user" class="user" value="'.$id.'" autocomplete="off" readonly="readonly" />',
'</fieldset>',
'<fieldset class="delete-wrapper">',
'<button type="submit" name="delete" class="delete">Delete</button>',
'</fieldset>',
'</form>'
);
$form = implode("",$form);
return $form;
}
//List All Users From Array As Forms For Deleting
public function listUsersForDelete() {
$users = $this->listUsersInArray();
for ($i = 0; $i < sizeof($users) ; $i++) {
while((sizeof($users) <= ($i % 7 == 0 || $i == 0))) {
echo $this->createForm($users[$i]);
$i++;
}
}
}
And now I just have to figure out how to add a wrap the all the forms in a div if the forms are more than 7 and do that each time I encounter a multiple of 7.
For example, if I have 9 forms, wrap the first 7 in a div but also wrap the rest in another div, and if I have 16 forms, wrap the first 7 in a div, the next 7 in a div and the rest of 2 in another div, and so on …
You suggested code looks fine. The only thing I would suggest is that you store the
<form>code into a variable first instead of just copying and pasting it. Copying and pasting is prone to a lot of errors, especially if you have to update the code later.