There is probably a very simple solution to this problem but I can’t see it. I have taken some of the code that Kevin used in his PHP series and I have tried to add to it.
I took the code for Users and Roles and copied Roles again and renamed it User_Type so I would have 2 checkbox areas to assign value to a user, but I keep getting error when trying to add new users. The edit and delete functions work fine and update all tables correctly. I even renamed the role id field to rolid so there wouldn’t be any conflicts with roleid in the userrole table.
The code is as follows:
// Build the list of User Types
$sql = “SELECT id, name FROM user_type”;
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = ‘Error fetching list of User Types.’;
include ‘error.html.php’;
exit();
}
while ($row = mysqli_fetch_array($result))
{
$user_types[] = array(
'id' => $row['id'],
'name' => $row['name'],
'selected' => FALSE);
}
// Build the list of User Roles
$sql = "SELECT rolid, name FROM role";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error fetching list of Roles.';
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$roles[] = array(
'rolid' => $row['rolid'],
'name' => $row['name'],
'selected' => FALSE);
}
include 'form.html.php';
exit();
Addform fields are here--------------------
if (isset($_POST[‘user_types’]))
{
foreach ($_POST[‘user_types’] as $user_type)
{
$user_typeid = mysqli_real_escape_string($link, $user_type);
$sql = “INSERT INTO userstype SET
userid=‘$userid’,
user_typeid=‘$user_typeid’”;
if (!mysqli_query($link, $sql))
{
$error = ‘Error assigning selected User Type to User.’;
include ‘error.html.php’;
exit();
}
}
}
if (isset($_POST['roles']))
{
foreach ($_POST['roles'] as $role)
{
$roleid = mysqli_real_escape_string($link, $role);
$sql = "INSERT INTO userrole SET
userid='$userid',
roleid='$roleid'";
if (!mysqli_query($link, $sql))
{
$error = 'Error assigning selected Role to User.';
include 'error.html.php';
exit();
}
}
}
header('Location: .');
exit();
Any thoughts would be appreciated.