I can't put real code here because is very long and will be hard to
explain.
I have users table in database and I have data table in database too.
So, to get the user data I'll pass user_id as parameter. Like this:
public function get_user_data($user_id) {
}
But. I can only get 1 data per "request". (Keep reading)
public function user_data() {
$getUsers = $this->db->get('users');
foreach($getUsers->result_array() as $user)
{
$data = $this->get_user_data($user->ID);
var_dump($data); // Only return 1 data;
}
}
But, I guess that have an way to "bypass" this but I don't know. I'm having trouble thinking.
As I said, I want to "bypass" this, and be able to send multiple user IDs, my real function do not accept that by default and can't be changed.
Thanks in advance!
replace
foreach($getUsers->result_array() as $user)
{
$data = $this->get_user_data($user->ID);
var_dump($data); // Only return 1 data;
}
to this
foreach($getUsers->result_array() as $user)
{
$data[] = $this->get_user_data($user->ID);
}
var_dump($data);
If you are aiming at sending more data to the function, you always need to make signature change of your function as one of the below :
function get_user_data() {
$args = func_get_args();
/** now you can access these as $args[0], $args[1] **/
}
Or
function get_user_data(...$user_ids) {
/** now you can access these as $user_ids[0], $user_ids[1] **/
}
// Only higher version of PHP
But I am not sure how you will handle returning data.
EDIT: Yes, then in the function, you can collect data in array and return an array of data from function.
If you can change in your function from where to where_in I think you will get an easy solution.
public function get_user_data($user_ids)
{
// your db code
$this->db->where_in('ID',$user_ids); //replace where with where_in
}
public function user_data()
{
$getUsers = $this->db->get('users');
foreach($getUsers->result_array() as $user)
{
$user_ids[] = $user->ID;
}
$this->get_user_data($user_ids);
}
Related
There is one function for getting all the data from table with one where clause and one with not wherein clause. I am stuck when I am passing data dynamically but when I am hardcoding the data, it is showing me correct data.
Hard-coded Example :
public function getAllTickets($drawId, $existing)
{
$login = [200263129,200263162,200263735,200263752];
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
Dynamic Example :
public function getAllTickets($drawId, $existing)
{
$login = [$existing];
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
In variable $existing I am same data as 200263129,200263162,200263735,200263752
But result is varying for both data and hard-coded example is showing me correct result.
Please use this it may help you:
public function getAllTickets($drawId, $existing)
{
$login = explode(',',$existing);
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
I want to implement a system in my project that "alerts" users when there is a new comment on one of their posts.
I currently query all comments on the posts from the logged in user and put everything in an array and send it to my view.
Now my goal is to make an alert icon or something when there is a new item in this array. It doesn't have to be live with ajax just on page load is already good :)
So I've made a function in my UsersController where I get the comments here's my code
public function getProfileNotifications()
{
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
if (!empty($comments_collection)) {
$comments = array_collapse($comments_collection);
foreach($comments as $com)
{
if ($com->from_user != Auth::user()->id) {
$ofdate = $com->created_at;
$commentdate = date("d M", strtotime($ofdate));
$comarr[] = array(
'date' => $ofdate,
$commentdate,User::find($com->from_user)->name,
User::find($com->from_user)->email,
Project::find($com->on_projects)->title,
$com->on_projects,
$com->body,
Project::find($com->on_projects)->file_name,
User::find($com->from_user)->file_name
);
}
}
} else {
$comarr = "";
}
}
Is there a way I can check on page load if there are new items in the array? Like keep a count and then do a new count and subtract the previous count from the new one?
Is this even a good way to apprach this?
Many thanks in advance! Any help is appreciated.
EDIT
so I added a field unread to my table and I try to count the number of unreads in my comments array like this:
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
$unreads = $comments_collection->where('unread', 1);
dd($unreads->count());
But i get this error:
Call to a member function where() on array
Anyone any idea how I can fix this?
The "standard" way of doing this is to track whether the comment owner has "read" the comment. You can do that fairly easily by adding a "unread" (or something equivalent) flag.
When you build your models, you should define all their relationships so that stuff like this becomes relatively easy.
If you do not have relationships, you need to define something like the following:
In User
public function projects()
{
return $this->hasMany('App\Models\Project');
}
In Project
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
Once you hav ethose relationshipt, you can do the following. Add filtering as you see fit.
$count = $user->projects()
->comments()
->where('unread', true)
->count();
This is then the number you display to the user. When they perform an action you think means they've acknowledged the comment, you dispatch an asynchronous request to mark the comment as read. A REST-ish way to do this might look something like the following:
Javascript, using JQuery:
jQuery.ajax( '/users/{userId}/projects/{projectId}/comments/{commentId}', {
method: 'patch'
dataType: 'json',
data: {
'unread': false
}
})
PHP, in patch method:
$comment = Comment::find($commentId);
$comment->update($patchData);
Keep in mind you can use Laravel's RESTful Resource Controllers to provide this behavior.
try this
$unreads = $project->comments()->where('unread', 1);
dd($unreads->count());
EDIT
My be Has Many Through relation will fit your needs
User.php
public function comments()
{
return $this->hasManyTrough('App\Project', 'App\Comment');
}
Project.php
public function comments()
{
return $this->hasMany('App\Comment');
}
then you can access comments from user directly
$user->comments()->where('unread', 1)->count();
or I recommend you define hasUnreadComments method in User
public function hasUnreadComments()
{
$return (bool) $this->comments()->where('unread', 1)->count();
}
P.S.
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
this code is horrible, this way much better
$projects = Auth::user()->projects;
I have a function that I use to get the user id of Auth component. It works fine without use return json_encode. The problem is that I need this works with json_encode because I get values from ajax request.
Using json_encode it always return null to id and I can't understand why does it occur. The problem is with the function indexAjax() below.
How could I use $this->Auth->user("id") with json_encode and it not return null ?
Trying.
//using $this->set it works fine
public function index() {
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
debug($id) or die;
//$this->set(compact('empresas'));
}
//with json_encode always return null
public function indexAjax() {
$this->autoRender = false;
$id = $this->Auth->user("id");
$empresas = $this->Empresa->find('all', array(
'fields'=>array("id", "nomeFantasia", "cnpj",
"telefone1", "telefone2", "celular", "aberto"),
'conditions'=>array("users_id = "=> $id)
));
return json_encode($id);
}
solved the problem. My solution was when user make login I get the user id and write in session so when I need this id I get from session directly and not from AuthComponent.
It works.
So I search for this title hoping someone would have already answered it however, I came across similar topics on other languages but not PHP so maybe this will help others.
I am constantly using this following script to call on the database but how can I create it so that I can make it just once at the top of the class for example and use it in every method on the class page that needs it. Example: An single page may not have all of the data it needs from the same table but if the table contains 50% of the data or more for that page, how can I modify this so that I can just say it once and let the rest of the following scripts display the data it extracted in the first place by calling it all just once?
Here's what I have now.
<?php
if($res = $dbConn->query("SELECT Column FROM Table")){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
?>
I want to call on this without the printf(" "); collect and store the data so that I can then call the results while printing or echoing the results with the HTML in other methods. What os the most efficient way? I don't want to make the same call over and over and over... well, you get the point.
Should I use fetch_array or can I still do it with fetch_assoc?
not very sure if it's the answer you want.
you can use include/include_once/require/require_once at the top of the page you want to use the function
for example:
general_function.php:
-----
function generate_form( $dbConn, $sql ) {
if($res = $dbConn->query("SELECT Column FROM Table")) {
while($d = $res->fetch_assoc()) {
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
and for those pages you want to use the function, just put
include "$PATH/general_function.php";
and call generate_form
Try this:
class QueryStorage {
public static $dbConn = null;
public static $results = [];
public static function setConnection($dbConn) {
self::$dbConn = $dbConn;
}
public static function query($query, $cache = true) {
$result = (array_key_exists($query, self::$results))?
self::$results[$query] : self::$dbConn->query($query);
if($cache) {
self::$results[$query] = $result;
}
return $result;
}
public static function delete($query) {
unset(self::$results[$query]);
}
public function clean() {
self::$results = [];
}
}
usage:
at top somewhere pass connection to class:
QueryStorage::setConnection($dbConn);
query and store it:
$result = QueryStorage::query("SELECT Column FROM Table", true);
if($result){
while($d = $result->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
reuse it everywhere:
$result = QueryStorage::query("SELECT Column FROM Table", true); // it will return same result without querying db second time
Remember: it's runtime cache and will not store result for second script run. for this purposes You can modify current class to make it
work with memcache, redis, apc and etc.
If I understood you correctly, then the trick is to make an associative array and access with its 'key' down the code.
$dataArray = array();
// Add extra column in select query for maintaining uniqness. 'id' or it can be any unique value like username.
if($res = $dbConn->query("SELECT Column,id FROM Table")){
while($d = $res->fetch_assoc()){
$dataArray[$d['id']] = $d['Column'];
}
}
//you have value in the array use like this:
echo $dataArray['requireValueId'];
//or , use 'for-loop' if you want to echo all the values
You need a function which takes in the query as a parameter and returns the result.
Like this:
public function generate_query($sql) {
if($res = $dbConn->query($sql)){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
Am trying to pass some data from one function to another when i set the data into session and print the session data i get the correct data, but whe trying to use the data in another function i get the word "Assets" i dont know where this word come from. Session library is auto loaded.Any help please.
These are my codes:
First function:
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->session->set_userdata('selected_client',$sess_array);
Second function:
$client_sess = $this->session->userdata('selected_client');
$client_id= $client_sess['cl_id'];
Try this i think this will give you some idea.
function one(){
$client_id = $this->uri->segment(3);
$sess_array = array(
'cl_id' => $client_d,
'selected_client'=>TRUE,
);
$this->two($sess_array);
}
function two($id){
$client_id= $id;
}
Here is what the Model looks like:
function getResponse($gettingresponse)
{
$enrollresponse=$gettingresponse['sendresponse'];
return $enrollresponse;
}
The Controller is as follows:
public function Register()
{
$this->load->view('firstview');
$this->load->view('secondview');
if($_POST) {
$gettingresponse=array(
'sendresponse'=>$_POST['source'],
'receiverresponse'=>$_POST['destination']
);
$registration_confirm=$this->systemModel->responselogin($gettingresponse);
$resposeflag=$this->systemModel->getEmail($gettingresponse);
$data['resposeflag']=$gettingresponsevalue;
if($registration_confirm){
$this->token($data);
}
}
$this->load->view('thirdview');
}
public function token($data=array())
{
$this->load->view('firstview');
$data['resposeflag'];
$this->load->view('token',$data);
$this->load->view('thirdview');
}
The following View shows the data that has been passed between the functions of the Controller.
<?php
echo form_input(array('name'=>'source','readonly'=>'true','value'=>$resposeflag));
?>