我有一个像这样的SQL表:
栏:userid right1 right2 right3 right4 rightX
值:1 1 0 0 1 x
value2:2 0 1 1 1 x
我应该如何将权限及其值放入数组中?
答案 0 :(得分:3)
正如评论中所述,一点点database normalization可能派上用场。在我的头顶:
users (id, nick, ...)
rights (id, name, desc, ...)
users_rights (user_id, right_id, issue_date, expiry_date, ...)
然后你可以通过JOIN
表格选择:
SELECT
ur.user_id,
r.name
FROM
rights AS r
LEFT JOIN
users_rights AS ur
ON
ur.right_id = r.id
(未测试的)
答案 1 :(得分:0)
对于通用插入解决方案,创建一个带有哈希数组的函数, E.g。
$my_array = ('userid' => value1, 'right1' => value 2, etc...);
然后将其传递给像<; p>这样的函数
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
}
答案 2 :(得分:0)
如上所述,数据规范化是您的朋友,但如果您真的需要:
$res = mysql_query ( "SELECT * FROM ..." );
$rights = array();
while ( $r = mysql_fetch_assoc ( $res ) ) {
$rights[$r['usersid']] = $r;
}
您现在可以通过$rights[<userid>]['rightsX']