class user{
protected $permissions;
public function can( $permission )
{
if (!isset($this->permissions)) {
/*
fetch permissions for this user from the database, and set the
User::permissions property, to allow caching.
*/
$cnx = $this->connexion();
$stmt = $cnx->prepare('SELECT permissions.permission_name FROM permissions, users_permissions WHERE users_permissions.user_id = ? AND users_permissions.permission_id = permissions.permission_id');
$stmt->bind_param('s', $_SESSION["user_id"]);
$stmt->execute();
$result = $stmt->get_result();
$people = array("Peter", "Joe", "Glenn", "Cleveland");
var_dump($people);
$this->permissions= $result->fetch_all(MYSQLI_ASSOC);
var_dump($this->permissions);
}
return in_array($permission, $this->permissions);
}
}
(scheme 1) the result of the array looks like this :
array (size=8)
0 =>
array (size=1)
'permission_name' => string 'Peut créer une permission' (length=26)
1 =>
array (size=1)
'permission_name' => string 'Peut modifier une permission' (length=28)
2 =>
array (size=1)
'permission_name' => string 'Peut voir des comptes utilisateurs' (length=34)
i tried fetch_array instead of fetch_all but it returns only one row
(scheme 2) is there anyway to make that array look like this one because if it does it will work :
array (size=4)
0 => string 'Peter' (length=5)
1 => string 'Joe' (length=3)
2 => string 'Glenn' (length=5)
instantiate a user
$that_guy = new user();
if ( $that_guy->can('Peut créer une permission')) {
echo"yay";
}else {
echo"you can't";
}
is there any possible way to change the array of scheme 1 and make it look like array of scheme 2 ?
With mysqli it's impossible, and this is a very good reason why you should use PDO instead
$cnx = $this->connexion();
$stmt = $cnx->prepare('SELECT permissions.permission_name FROM permissions, users_permissions WHERE users_permissions.user_id = ? AND users_permissions.permission_id = permissions.permission_id');
$stmt->execute([$_SESSION["user_id"]]);
$this->permissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
That's all.
Not only this code is two times shorter, but also it is giving you the exact result you want.
Loop through the array
public function can( $permission )
{
if (!isset($this->permissions)) {
$cnx = $this->connexion();
$stmt = $cnx->prepare('SELECT permissions.permission_name FROM permissions, users_permissions WHERE users_permissions.user_id = ? AND users_permissions.permission_id = permissions.permission_id');
$stmt->bind_param('s', $_SESSION["user_id"]);
$stmt->execute();
$result = $stmt->get_result();
$stmt->bind_result($permission_name);
$stmt->store_result();
$this->permissions = array();
while(($row = $result->fetch_assoc())) {
$this->permissions[] = $row['permission_name'];
}
}
return in_array($permission, $this->permissions);
}
the result will look like what you want in (scheme 2)
On PHP side you can use array_column:
$this->permissions = array_column($this->permissions, 'permission_name');
Also, I would use array_flip additionally:
$this->permissions = array_flip(
array_column($this->permissions, 'permission_name')
);
This way you can use isset($this->permissions[$permission]) instead of in_array($permission, $this->permissions); as it is faster.
Related
I can't seem to get the array to return from the function correctly, every time I run the script it just echoes out 0, even though I have checked that the MySQL query returned at least 1 row. I've also tried using $_GLOBALS["FORUM_ANSWERS"][] = ..., however it still did not work.
public function getAnswers() {
$dbh = $this->dbh;
$id = $this->question_id;
$q = $dbh->prepare("SELECT * FROM answers WHERE question_id = :id");
$q->bindParam(":id", $id);
$q->execute();
$nr = $q->rowCount();
if ($nr == 0) {
echo "No Questions";
}
$_GLOBALS["FORUM_ANSWERS"] = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
array_push($_GLOBALS["FORUM_ANSWERS"], array(
"num_id" => $row["num_id"],
"question_id" => $row["question_id"],
"answer" => $row["answer"],
"name" => $row["name"],
"username" => $row["username"],
"ip" => $row["ip"],
"date" => $row["date"],
));
}
return $GLOBALS["FORUM_ANSWERS"];
}
SEPERATE FILE:
$answers = $forum->getAnswers();
echo count($answers);
You are assigning to $_GLOBALS and returning $GLOBAL.
You actually don't need to use a global array by the look of it - I would just assign the array to a variable (that you initialise in the function) and return that.
I have a function
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
return $results;
}
and this is called via
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
However the results of $returnedUser['(field name']Althought, are always coming up NULL. avatar, userSelectedTheme are some of the fields from the dbase. I have confirmed in the database the infomation is there
I suspect I am missing a key line from my function which involves =array() somewhere and manflu is preventing me seeing it.
Any advice greatly appreicated
First of all stop using mysql_(Why shouldn't I use mysql_* functions in PHP?) is deprecated.
mysql_query from getUser function returns a resource. you must
return an array. so have a look at mysql_fetch_array or mysql_fetch_assoc functions
basically you must return mysql_fetch_array($results) assuming that is only one result comming from db. otherwise you'll have to loop through them.
Thanks to all those who answered, and extra plaudits to those who spotted the use of the depreciated mysql commands.
Had a shot of espresso and got the answer working (albeit unsafe and unsecure and..)
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
$arr = array();
while($row= mysql_fetch_assoc($results)){
$arr['avatar'] = $row['avatar'];
$arr['userSelectedIndustry'] = $row['userSelectedIndustry'];
}
return $arr;
}
and the call
$returnedUser = array();
$linkedInID = filter_var($_REQUEST['linkedInID'], FILTER_SANITIZE_STRING);
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userLinkedInIndustry' => $userLinkedInIndustry,
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'userSelectedIndustry' => $returnedUser['userSelectedIndustry'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
many thanks for all time spent, and apologies for not just getting my head down and figuring it out
$data=array();
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
data[]=$row;
}
return $row;
I want to create an array using recursion in Codeigniter. my function make_tree() in controller is :
function make_tree($customer_id,$arr = array()){
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v):
echo $customer_id = $v['customer_id'];
array_push($arr, $customer_id);
$this->make_tree($customer_id);
endforeach;
var_dump($arr);
}
But the var_dump($arr) and echo results output like:
1013
array
empty
array
0 => string '13' (length=2)
11
array
empty
array
0 => string '10' (length=2)
1 => string '11' (length=2)
How can I make a single array of all the three outputs, ie an array with elements 13,10,11
you need to send the array with the parameters otherwise a new array is created.
function make_tree($customer_id,$arr = array()){
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v):
echo $customer_id = $v['customer_id'];
array_push($arr, $customer_id);
$this->make_tree($customer_id, $arr);
endforeach;
var_dump($arr);
}
PS: I don't know what you are trying to do exactly, but you probably need to add a stopping condition that is going to return the final array, unless you want to pass it by reference.
UPDATE
Here is one way to do it:
function make_tree($customer_id, &$arr)
{
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v):
$customer_id = $v['customer_id'];
array_push($arr, $customer_id);
$this->make_tree($customer_id, $arr);
endforeach;
}
and this is how you'd use it:
$final_array = array();
make_tree($some_customer_id, $final_array);
// now the $final_array is populated with the tree data
You can use class scope.
class TheController {
private $arr = array();
function make_tree($customer_id){
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v) {
$customer_id = $v['customer_id'];
array_push($this->arr, $customer_id);
$this->make_tree($customer_id);
}
}
}
I would like to get all IDs with recursion from 1 table. I managed to echo those variables but when I tried to put it into array I failed. Here is the string version:
public function get_numProducts($cid)
{
$this->db->select('cat_id');
$this->db->from('ci_categories');
$this->db->where('cat_child',$cid);
$q = $this->db->get();
$result = $q->result();
$i=0;
$a="";
foreach($result as $mainCategory)
{
$a .= $mainCategory->cat_id;
$a .= $this->get_numProducts($mainCategory->cat_id);
}
return $a;
}
When calling this function with param "4" I get string output: 89. Which is good. But I would like to have output an array(4,8,9). Thanks for help
EDIT:
2nd version
public function get_numProducts($cid)
{
$this->db->select('cat_id');
$this->db->from('ci_categories');
$this->db->where('cat_child',$cid);
$q = $this->db->get();
$result = $q->row();
$n = $q->num_rows();
if ($n > 0)
{
$array[] = $result->cat_id." ";
$array[] = $this->get_numProducts($result->cat_id);
}
return $array;
}
This version returns array however multidimensional:
array (size=2)
0 => string '8 ' (length=2)
1 =>
array (size=2)
0 => string '9 ' (length=2)
1 => null
You will have to pass the array be reference to each iteration of the function ..
public function get_numProducts($cid, &$array)
..
$array[] = $cid;
if ($n > 0) $this->get_numProducts($result->cat_id, $array);
I have the following code.
public function fetch_questions($count=null)
{
$stmt = $this->mysqli->prepare("SELECT question,question_title FROM questions order by id");
$stmt->execute();
$stmt->bind_result($question,$question_title);
$arr = array();
while ($stmt->fetch()) {
$arr = array('question_title'=>$question_title,'question'=>$question);
}
$stmt->close();
return $arr;
}
The output only contents one row, the last row. how can retrieve all records?
$questions = $db->fetch_questions();
var_dump($questions);
Output of var_dump:
array
'question_title' => string 'aaaaaa' (length=6)
'question' => string 'aaaaaaaaaaaaaaaaaaaa' (length=20)
You need to append onto $arr via [], not assign its value directly. Otherwise you are overwriting it on each loop iteration.
while ($stmt->fetch()) {
$arr[] = array('question_title'=>$question_title,'question'=>$question);
//-^^^^
}