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);
//-^^^^
}
Related
I am trying to add data to an array $result where each value is a string $idstring which will contain the employees ids like "999|888|777". The data is fetched from broadcastTbl collection from a MongoDB. I need to fetch each employee's corresponding details in a loop and push to $result. I am successfully fetching the data, but the trouble I am facing is in the below code where only one employees' data is getting pushed to the $result array.
$projection = array("broadcast_id" => 1, "employeeList" => 1);
$query = array("broadcast_id" => $broadcast_id);
$count = $this->collection->find($query)->count();
$cursor = $this->collection->find($query, $projection);
$result = array();
foreach($cursor as $row)
{
$idstring = trim($row["employeeList"]);
$idstring = preg_replace('/\.$/', '', $idstring);
$idarray = explode('|', $idstring);
foreach($idarray as $employeeId)
{
$this->EmployeeCollection = $this->db->EmployeesTbl;
$EmployeeCursor= $this->EmployeeCollection->find(array("EmployeeNumber" => $employeeId));
$EmployeeCursorCount= $this->EmployeeCollection->find(array("EmployeeNumber" => $employeeId))->count();
if($EmployeeCursor->count() > 0)
{
array_push($result,$EmployeeCursorCount);
foreach ($EmployeeCursor as $k => $row) {
array_push($result, $row);
}
}
else
{
array_push($result, array("datanotfound"=>1));
}
return json_encode($result);
}
}
You are returning too early.
Move return json_encode($result);
After the outer-most foreach loop.
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.
Aim is to return array from .php in JSON format. That array to contain another array of data (49 DB rows, each having 4 columns), which is taken form mySQL DB:
.php is below:
$json = array( //this is AJAX response
"status" => null,
"username" => null,
"population" => null,
"food" => null,
"water" => null,
"map" => null //this to be an array of tiles
);
$sql = "SELECT * FROM players_map_test WHERE player_id = :value";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$json["map"]["tile_health"] = $row["tile_health"];
$json["map"]["tile_id"] = $row["tile_id"];
$json["map"]["tile_level"] = $row["tile_level"];
$json["map"]["tile_type"] = $row["tile_type"];
}
echo json_encode($json);
In my AJAX response handler, I expect to access that sub-array as response.map and handle elements in usual manner: response.map[0].
When I console.log(response) I see that map is present there, but it is not an array and it contains "1" as values to all keys:
map:Object
tile_health:"1"
tile_id:"1"
tile_level:"1"
tile_type:"1"
What am I doing wrong?
Update your foreach loop like as below--
foreach ($result as $row) {
$json["map"][] = $row;
}
Also change the below code
#$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Note: fetch() function return only 1 row. And fetchAll() function return multiple rows.
Syntax is next:
foreach ($result as $row) {
$json["map"][] = [
"tile_health" => $row["tile_health"],
"tile_id" => $row["tile_id"],
"tile_level" => $row["tile_level"],
"tile_type" => $row["tile_type"]
];
}
You were overwriting values.
You can simplify your database part like this:
// request only needed columns
$sql = "SELECT tile_health, tile_id, tile_level, tile_type
FROM players_map_test WHERE player_id = :value";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// output was already in the type of array
$json["map"] = $result;
// encode and display
echo json_encode($json);
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 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);
}
}
}