I'm looking to hit the database once, and return a MySQL resource AND an array. I have the following code in my controller to do that:
$result = $this->data->my_method();
$data['result_resource'] = $result;
$data['result_array'] = $result->result_array();
In my view, I'm calling the following:
$this->table->generate($result_resource);
When the $data['result_array'] line is commented out, the table works as expected (i.e the column headers show) but when the $data['result_array'] line is not commented out, both the result_resource AND the result_array turn to arrays. What's happening here, and how I can avoid it?
The $data array is being passed to the view in typical CI fashion:
$this->load->view('view.php', $data);
Running the method twice does solve the problem, but I'd prefer not to do that.
This stuff about the result_array() being "consumed" is nonsense - it is simply an object that hasn't been run at all. You can use it over and over
I put your code into a controller - including the table->generate() - and everything worked just fine for me.
$result is the base object that includes the connection resource, etc & really isn't what you want to use. It works because the table library is set up so that if you DO pass that, it will look for the result_array() for you, but it isn't really the standard way of doing this.
I think you prolly have something else in your code you've looked past that is causing the trouble. Try getting rid of the $result code, and just run:
$result = $this->data->my_method();
$data['result_array'] = $result->result_array();
var_dump($data['result_array']);
echo $this->table->generate($data['result_array']);
and check everything looks normal. I suspect you'll do a facepalm at some point :-)
Related
I'm trying to paginate my json response in terms of multiples of 20 but for some reason, I'm getting Error: Call to a member function chunk() on array.
To clarify, $results has data in it and $request->get('offset'); has a value. Is there something I'm doing wrong? I'm seeing examples when searching on SO where people are doing this on a collection but for some reason, it isn't working for me. How can I make this work?
Note: If I do dd($results['num_results']);, it displays 360. I feel like I need to use this some how but I'm not sure how. I'm trying to achieve this in the most Laravel way possible. Also note, no database is being used - this is simply a get request on an external API.
Thanks in advance.
collect($results);
$outputs = $results->chunk(20)[$request->get('offset')];
dd($outputs);
$results is still an array. You are not setting the new Collection you are creating to a variable: collect($results). This does not change $results. So you are calling chunk on the array, $results. Call chunk on the Collection instead:
$collection = collect($results);
$outputs = $collection->chunk(20)...;
I have problem when I'm checking if collection is empty or not, Laravel gives me error
"Call to undefined method
Illuminate\Database\Query\Builder::isEmpty()".
Tho it work in other Controller, but when controller is in Sub folder is suddenly stops working.
Here is my code:
$group = UserGroup::where('id', $request->group_id)->first();
if($group->isEmpty()){ // I get error from here
return redirect()->back();
}
One of the most popular way of debugging in PHP still remains the same – showing variables in the browser, with hope to find what the error is. Laravel has a specific short helper function for showing variables – dd() – stands for “Dump and Die”, but it’s not always convenient. What are other options?
Note the below mentioned methods are to find where our class fails and what are all the conditions that are available after our query executes. What is our expected result before printing it. This methods are the best methods to find out the error as required by is.
First, what is the problem with dd()? Well, let’s say we want to get all rows from DB table and dump them:
$methods = PaymentMethod::all();
dd($methods);
We would see like this:
But you get the point – to see the actual values, we need to click three additional times, and we don’t see the full result without those actions. At first I thought – maybe dd() function has some parameters for it? Unfortunately not. So let’s look at other options:
var_dump() and die():
Good old PHP way of showing the data of any type:
$methods = PaymentMethod::all();
var_dump($methods);
die();
What we see now:
But there’s even more readable way.
Another PHP built-in function print_r() has a perfect description for us: “Prints human-readable information about a variable”
$methods = PaymentMethod::all();
print_r($methods);
die();
And then go to View Source of the browser… We get this:
Now we can read the contents easily and try to investigate the error.
Moreover, print_r() function has another optional parameter with true/false values – you can not only echo the variable, but return it as string into another variable. Then you can combine several variables into one and maybe log it somewhere, for example.
So, in cases like this, dd() is not that convenient – PHP native functions to the rescue. But if you want the script to literally “dump one simple variable and die” – then dd($var) is probably the fastest to type.
I have a problem, when I try to run this function in my model it does nothing. The print statement prints out.
DELETE FROM child_participantsWHERE Child_Name='test'
andParent_username='tester2'
Which when I run from command line works correctly(the record exists and is deleted). But when I try it from my web application it gives me no error but does not actually delete anything. I know i am passing data correctly because I receive it in my controller and model. What gives?
function remove_child($username, $participant_name)
{
$where = "`Child_Name`='$participant_name' and`Parent_username`='$username'";
$this->db->where($where, null, false);
$this->db->delete($this->child_table);
echo $this->db->last_query();
}
From the documentation:
If you use multiple function calls they will be chained together with AND between them:
Try changing:
$where = "`Child_Name`='$participant_name' and`Parent_username`='$username'";
to
$this->db->where('Child_Name', $participant_name);
$this->db->where('Parent_username', $username);
// translates to WHERE Child_Name='XXX' and Parent_username='XXX'
Hope this helps!
Do you get the same results when you break it out into two where method calls? I would do this over how you are using the where method.
$this->db->where('Child_Name',$participant_name);
$this->db->where('Parent_username',$username);
$this->db->delete($this->child_table);
also, turn on the profiler to see all the queries that are being run to make sure there are not other parts of code we cannot see that might be interfering or a transaction not being committed
$this->output->enable_profiler(TRUE);
Another suggestion is the practice of soft deletes so that way your data is not truly gone and also minimizes how much you need to rely on reconstructing your log file. Also to make simple CRUD operations faster you can use a very simple extension of the base model. One that I have used by recommendation is https://github.com/jamierumbelow/codeigniter-base-model
Check that does your user has delete privilege in the database. if it has than change your
code like this:
function remove_child($username, $participant_name)
{
$this->db->trans_start();
$this->db->where('Child_Name',$participant_name);
$this->db->where('Parent_username',$username);
$this->db->delete($this->child_table);
$this->db->trans_complete();
return TRUE;
}
i hope that this will solve your problem.
I'm working on exporting from a database table using Doctrine and symfony. I've made a call to my database with
$variableTable = Doctrine::getTable('Table Name')->findAll();
then I set another variable to get data from it like so:
$variable = $variableTable->getData();
I just want to be able to loop through that so I can pull the data I need to put into a csv file but I'm stuck on that part. For some reason, when I debug, it shows that the second variable that is getting set to the value of the getData is null/0.
I'm not sure if I'm missing something.
I think maybe you are trying to call getData on the collection instead of calling getData on the record... But that doesnt make much sense because you are still going to have to call getData on each record, so you might as well just loop over the collection. Additionally its possible there were no results from your findAll for some crazy reason so you should take that into account i think. Anyhow code similar to the following has worked for me in the past so without the details of your code its the best i can offer:
$records = Doctrine::getTable('RecordName')->findAll();
if($records->count()) {
$csvPath = '/path/to/csv/file.csv';
$csvh = fopen($csvPath, 'w');
$d = ','; // this is the default but i like to be explicit
$e = '"'; // this is the default but i like to be explicit
foreach($records as $record) {
$data = $record->toArray(false); // false for the shallow conversion
fputcsv($csvh, $data, $d, $e);
}
fclose($csvh);
// do something with the file
}
There are existing solutions for data import\export.
Consider using one of this:
https://github.com/orocrm/platform/tree/master/src/Oro/Bundle/ImportExportBundle
https://github.com/sonata-project/exporter
I know this is a really simple thing that I really should know but I'm trying to learn cakephp without having done much php before. I've been told thats a stupid idea, but I'm doing it for fun and so I'm doing it.
I want to pass an array from one controller action to another controllers action and then pass it to the view. I have:
sponges_controller.php
$info = $this->data;
$this->redirect(array('controller'=>'baths', 'action'=>'dashboard', $info));
baths_controller.php
function dashboard($info) {
$this->set('info', $info);
}
and then
<?php echo debug($info); ?>
in the view for dashboard.
I've tried various ways but can't make it work. All it does is print out Array()
Plz help me! :) Julia
You can't pass data that way from one controller to the other as far as I know, at most you can concat a string to the action, like an ID for view or editing.
If you want to pass the info you could try setting it in the SESSION variable in the following way:
$this->Session->write('Info', $info);
And in your other controller you can check for it:
$this->Session->read('Info');
It looks like cake will not let you pass an array into a controller action. I set up a simple example and I got an 'array to string conversion error'. Is there a specific reason why you aren't just posting the data to baths/dashboard? I can think of a workaround for your problem, but it is quite messy.
8vius's solution above will definitely work.
Here is another way, but using sessions is probably a lot better
$str = http_build_query($info);
$this->redirect('/baths/dashboard?'.$str);
So then in your baths/dashboard action, you will have access to your data using the php $_GET array.
So if you originally had this->data['name'] you can access it with $_GET['name']
I'm not sure about the passing data in different controllers but within the same controller we can do it just like a function call by writing something like this.
$this->function_name($info);
This will perfectly work as intended. I've not tried this type of data passing in different controllers function.