I have an sql table like this:
column: usersid right1 right2 right3 right4 rightX
value: 1 1 0 0 1 x
value2: 2 0 1 1 1 x
How should I put the rights and their value into an array?
I have an sql table like this:
column: usersid right1 right2 right3 right4 rightX
value: 1 1 0 0 1 x
value2: 2 0 1 1 1 x
How should I put the rights and their value into an array?
As stated in a comment, a little database normalization might come in handy. Off the top of my head:
users (id, nick, ...)
rights (id, name, desc, ...)
users_rights (user_id, right_id, issue_date, expiry_date, ...)
Then you could select by JOINing the tables:
SELECT
ur.user_id,
r.name
FROM
rights AS r
LEFT JOIN
users_rights AS ur
ON
ur.right_id = r.id
(untested)
For a generic insert solution, create a function that takes a hash array, E.g.
$my_array = ('userid' => value1, 'right1' => value 2, etc...);
then pass it into a function like;
function create($values) {
// get the arguements passed
$elements = func_get_args();
// initialise the array for the paramters
$sql_array = array();
// initialise the bindings array
$bindings = '';
// start the sql
$sql = "INSERT INTO `{$this->db_table}` (";
// loop over the parameters
foreach ($elements[0] as $k => $v) {
// add to sql statement
$sql .= "`$k`,";
// add to bindings string
$bindings .= "?,";
// add to sql parameter array
$sql_array[] = $v;
}
// remove the last ' from the sql statement
$sql = rtrim($sql, ',');
// now add closing bracket, and start of values
$sql .= ") VALUES (";
// remove the last ' from the sql statement
$bindings = rtrim($bindings, ',');
// now add bindings to the sql, and close it off
$sql = $sql . $bindings . ')';
// run the query in your preferred method, remembering to check for errors
}
As suggested above, data normalization is your friend here, but if you really have to:
$res = mysql_query ( "SELECT * FROM ..." );
$rights = array();
while ( $r = mysql_fetch_assoc ( $res ) ) {
$rights[$r['usersid']] = $r;
}
You can now access the users' permissions through $rights[<userid>]['rightsX']