I'm building a simple app and trying to test DB result output. But unfortunately all I'm getting is an array of size 0. Here's the controller code excerpt:
$data['query'] = $this->db->query('SELECT role_id, role_privilege FROM role');
$this->load->view('welcome_message', $data);
And a view code excerpt:
<?php
echo count($query->result_array())."<br/>";
foreach ($query->result() as $row){
echo $row->role_id . '<br/>';
echo $row->role_privilege . '<br/>';
}
echo 'Total result '.$query->num_rows();
?>
And what I get is next:
0
Total result
Running query from a command line gives a 2 rowed output. Can someone point out what i'm missing?
EDITED:
This issue is also discussed here .
EDITED:
Maybe some platform specific stuff (I really doubt that)? I'm running LAMP (php 5.3.2, mysql 5.1.37, apache 2.2.15).
EDITED:
This prints out a "Array ( )" string. My DB is 100% filled. I can say that for sure, because I did
INSERT INTO role(role_privilege) VALUES ('ROLE_MODERATOR');
INSERT INTO role(role_privilege) VALUES ('ROLE_USER');
and then checked it through a command line.
EDITED:
After I put this into my controller:
echo $this->db->last_query(); exit;
I get next output:
SELECT role_id, role_privilege FROM role
And that's exact sql query that I needed. Unfortunately results are o sized array.
Well, this here problem is basically not a CI related one, but strange thing is that CI couldn't track this error. Here's what was going on:
While installing php I haven't specified --with-mysql-socket parameter and it looks like php tried to use a /tmp/mysql.sock (default one) which obviously was not specified in my.cnf. So CI tried to bind to a nonexistent socket. Changing mysql params in a php.ini solved the problem.
Well, it sounds like your db access is set up properly because you're not getting an error. Which I think also means that the table exists. I know you said you ran that query from the command line, but are you certain you're accessing the same data set/server/table? No weird versioning or anything? It sounds like there aren't records in the role table. Sorry, just grasping at straws as your code looks right.
How about doing
SELECT * FROM role
and then doing a
print_r($query->result_array());
in your view? That should reveal column names at least so you know you're accessing the right data.
Try that and report back with any detail and hopefully it will supply some hints.
Related
I'm trying to get sessions to work in Laravel 5.7, but I can't seem to get it working; I'm not sure why. I've looked at the official docs, looked at a bunch of SO posts, done Googling for the issue on other sites, and I still can't figure it out.
Basically, I've got a route like the following in web.php:
Route::get('/some_path', 'SomeController#index');
Then, in the index method of SomeController, I have the following:
session(['test', 'Some Value']);
session(['test2', 'Some Other Value']);
session(['test3', 'Some Third Value']);
$value = session('test', 'Backup Value');
echo $value;
With that, I'm always getting Backup Value echoed to the screen.
If I go into /storage/framework/sessions, I see a session file that has the following content (which I have anonymized):
a:5:{s:6:"_token";s:40:"token-here";s:9:"_previous";a:1:{s:3:"url";s:26:"http://example.com/some_path";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}i:0;s:5:"test3";i:1;s:16:"Some Third Value";}
Basically, it looks like the session is kind of working, but it only seems to store test3. If I comment out the test3 line in the controller, then it only stores test2. And even if I only have the test line in the controller, it still doesn't retrieve the value.
I also tried switching the session to a DB session with the proper session migrate file a la https://laravel.com/docs/5.7/session, but it's still not working.
Basically, I have no clue what's up. I can say that I'm not using the native Laravel auth, so I'm not sure if that matters, but I feel like it shouldn't. Also, I tried restarting my localhost, but that didn't make a difference and running both of the following commands, neither of which seem to change anything:
php artisan config:clear
php artisan route:clear
Lastly, I tried adding use Session at the top of the controller, but that doesn't seem to matter either.
Basically, I don't know what to do. What could possibly be causing this? Thank you.
What's happening here is that when you add this:
session(['test', 'x'])
It adds test at the 0th index of the session and x at 1st.
Now when you again do a session(['test1', 'xx'])
It overwrites the 0th and 1st index of session with new values.
Therefore when you print the session data you get the last values.
You can check this by doing a dd(session()->all()) and seeing the same on screen.
If you want to make a key value relation and store the data in such away, please use the syntax like this:
session(['test' => 'x']);
session(['test1' => 'xx']);
those who are unable to save the session the issue is you guys are forgot to put the save() function after put given is the example.
$cartCount = Session::get('cartCount');
if(empty($cartCount)){
$cartCount = 0;
Session::put('cartCount', $cartCount);
}
Session::save();
Session::save() can be a life saver, definitely try that if still issues.
Laravel 5.7 - store value in session with File system:
Set the value in session:
session()->put('email', 'jai#gmail.com');
Get the value from session:
$email = session()->get('email');
Delete the session of email:
session()->forget('email');
It works like charm :)
If for some reason your code doesn't run through - eg you're using dd() somewhere, then your session will never save. This tripped me up for a good 20 minutes.
In this case, all you need to do is add a "web" middleware chain function to your route rule.
e.g
Route::get('/some_path', 'SomeController#index')->middleware('web');
Then clear cache:
php artisan config:clear
php artisan route:clear
I have this function on 'myproject/controllers/sample.php'
public function callTest()
{
$this->load->database();
$this->db->query("INSERT INTO table_name (client_id, subscription_id, platform, device) VALUES (1, 1, 1, 1)");
$this->load->view('sample');
}
Whenever I run it on the browser (localhost/index.php/sample/callTest), it successfully runs and inserts the data on the table, but when I use command line (php index.php sample callTest), the SQL won't run.
I removed the database part and it shows the code for the view, which I think is correct. But if I put a database logic to it, it won't run and the output is blank. No error logs also.
Am I doing something wrong? Am I missing an argument?
My codeigniter version is 2.2.6.
This is my reference https://www.codeigniter.com/userguide2/general/cli.html
Edited: Aril 17,2017
I just figured out that in some of environment, the command line above works. I suspect that the cause of this was me converting PHP 5.5 to 5.6 in Ubuntu 14, some of the dependencies might not be configured correctly.
You need to specify controller and function name as well,
Example
php index.php/sample/callTest
Also you need to set one config variable as below
$config['uri_protocol'] = 'AUTO'
Read the document answer is hidden there.
Now normally you would visit the your site using a URL similar to
this:
example.com/index.php/tools/message/to
I started learning this very nice PHP ORM api last week: http://phpdatamapper.com/
and have been trying to get up to speed with it
What I'm not seeing in the site documentation, is how to iterate with "$postMapper->all()"?
http://phpdatamapper.com/documentation/usage/finders/
When I try to iterate through the value returned from ->all(), it seems only to have gotten the last element in the table.
Here's the code I have:
// $postMapper uses phpDataMapper framework. It works to create the schema & insert values
$postEntities = $postMapper->all();
$postEntities->execute(); // tried adding this to help things
foreach ( $postEntities as $postEntity);
{
echo $postEntity->title;
echo "<br/>";
}
I see other folks are forking it from GitHub and using it in their projects, so I believe I'm making some mistake in my call logic.
It would be great if someone could share a small example of how to access the query data correctly when using mapper->all()? This is an important part of a PHP stack and I would very much like to be able to use this particular solution in my projects going forward. Thanks
Ok, this turned out to be a "not so smart" mistake on my part. The font in my IDE was too small I guess, and I didn't see the ';' at the end of the line that declares the for loop.
So the ORM is all good, just my code wasn't. I'm updating this in case someone else can learn from my mistake - other option is to just delete the post all together (... not sure which is better)
i am creating a CMS and have php creating a page. i have a while loop like this
while($row = mysql_fetch_array($results)) {
echo "some html code" . $row['name'];
its shortend but hopefully you get the point. i have the full thing in my page working just as it should and i wanted to move it to a function include as i want to reuse it. the problem is i do that and it stops working.
i did some testing and found that the function is getting the query result and after doing a var dump both were identical the problem comes when i try to assign it to an array. it comes back as false so in the above code, for example,
$row = false;
im toatly lost in this and if my explanation is confusing i appologise but i am a bit of a newbie i have tried searching but....i dont really know where to begin
any thoughts.
the query you are doing is basically wrong, try posting exactly the code which you have in $query and then let us see the problem.
also, it is better to use mysqli functions.
but for this, edit the question and type the query, or simply put a die(mysql_error()) at the end of your query which is in $query. It will show your exact error.
i fugured it out
when i was testing the function i commented out the original code on the main page but for some reason i had not comented out enough (it was a mix of php and html clearly the php had not been commented out properly) this must have been causing a clash of some kind as when i put the function above the code on my page the function worked and the long code below it did not
sorry for wasting your time guys
This is a bit of an oddity for me. PHP is my forte, and I can normally figure out any issue I encounter.
I have a custom framework that I have been using for years. I have taken it upon myself to rewrite it, and I'm doing everything essentially the same that I was before. The problem lies in the following construct:
function ModPages_GetPage() {
$page = ModPages_GetPageByName($_GET['page_name']);
if($page != false) {
include(TPL_DIR.'pages/pages.view.php');
} else {
ErrorMessage('Invalid Page', 'The selected page could not be found.');
}
}
function ModPages_GetPageByName($page_name = null) {
$db = new Database;
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
$page = $db->GetRow($query);
return $page;
}
This code is being called with 'home' for the value of $_GET['page_name']. The call to ModPages_GetPageByName() is working fine, but the value of $page in ModPages_GetPage() isn't getting set. Matter of fact, any debugging statements thrown in after that call are failing to display anything.
I have display_errors set to on, and error_reporting set to E_ALL. I get a couple notices from my Database class, but that's it.
Running the script at a shell fails to produce any errors. When using strace, I do see the process spits out an 'exit_group(255)'.
This one has me quite baffled. I could sure use some direction on this.
I would think it's your query, shouldn't you just return the page name instead of star? as star (*) would return an array which is probably being passed back as the value? just my guess.
$query = '
SELECT *
FROM pages
WHERE page_name = "'.CleanStr($page_name).'"
AND page_enabled = "yes"
LIMIT 1
';
if you do a print_r on the $page return I would think it should be an array
$page = $db->GetRow($query);
echo "Page:<pre>".print_r($page,true)."</pre><br />\n";
Then maybe return something like this
return $page['page_name_field'];
ok before we get to a solution can we first make sure that before setting the $page variable, first just echo $_GET['page_name'] to see if there is a value being received.
PK
Does your script stop right after your database call, or just doesn't display any output?
If the first is true, then it looks like a fatal error. With E_ALL, it should be displayed, are you sure both display_errors and error_reporting are as you say at that point, and that the GetRow function doesn't alter them in any way? If so, maybe there's something in the Apache error log (PHP errors are sometimes logged there).
If the latter is true I'm thinking about an exception being thrown in a method that is being called, and caught in a higher level function. To check this you can put the database call (ie: the point where things go wrong) inside a try/catch block and see if you reach the catch block.
I would try following:
replace $_GET with $_REQUEST (maybe your form is using POST?)
do a print_r to check contents of your variables.
use mysql_error to view any errors, or print your mysql query in your browser, copy/paste it in phpmyadmin, is it returning anything? error.. data?
something similar happend to me once, my framework was encoded in ANSI and my calling php file was UTF8+BOM... I changed everything to UTF8+BOM and it worked.
try also different browser, I know it might not be a browser problem, but it might be that your script is cached somewhere.
are you using some caching? like eaccelerator?
Are those functions in a class? If so, you will need $page = $this->ModPages_GetPageByName().
Also I would echo out the argument and the sql statment in ModPages_GetPageByName(). This way you can verify that it isn't a SQL error.
I can't say for sure why your code isn't working, but I can make some suggestions that might help in locating the error.
The first thing I notice is you don't check that $db actually contains a valid database. I don't know the details of your Database object but I'm assuming there's some mechanism in there for checking if it's actually connected to the database. You should use that to determine if the database is connected before running queries on it.
$db = new Database ();
if ($db -> isConnected ())
{
$query = 'SELECT * (etc etc etc)';
// ...
}
else
{
// Put some kind of DB connection error notification or throw an exception here
}
Just on a stylistic note, you don't need to store the results of your DB lookup before returning it, unless you're planning on doing some processing on the result before returning it. You can just return the lookup directly. Of course that's just a stylistic choice, but it saves a line or two :)
return ($db->GetRow($query));
After you run your getpage function, I'd strongly recommend var_dump()ing the result. Even if your function returned NULL, you'll still see this in the var_dump. If in doubt, dump it out :). I'd also recommend installing xdebug to make the var_dump output more readable.
$page = ModPages_GetPageByName($_GET['page_name']);
var_dump ($page);
I would also strongly recommending var_dumping your query before you execute just to make absolutely sure that you're running the query you think you're running. Copy and paste the outputted query into sqlyog or phpmyadmin or whatever you use for interactive access to your database and make sure it returns what you think it should return.
Other things to check, is the page you're trying to return actually set page_enabled='yes'? Does the page_enabled column actually store the value as 'yes', or is it a bool or an integer or something else? Is magic quotes enabled or disabled? If they're in one state when you think they're in the other they can cause confusion. Are errors actually being reported to the browser? Add a line at the top of your script that's guaranteed to fail just to make sure, like an attempted foreach on an integer. If you don't see an error, then maybe error reporting isn't configured properly. I know those are obvious questions but I also know how easy it is to overlook the obvious if you're not getting what you expect out of a query.
Are you sure $page is not set, or is it just that your debug instructions don't print anything? Try logging to a file or a database instead; maybe your code triggered output buffering or something like that.
Also, you are calling ModPages_GetPageByName before declaring it. That is usually okay, but might not be in special circumstances (e.g. when the code is wrapped in an if block). Try swapping the two.
Also, check your environment and disable opcode caching and other possible error sources. APC for example can call the old version of the script long after you changed the PHP file.
While some of you have put extra effort into responding to this, nobody has been able to see the full picture, even given the details I have provided. I have been unable to trace the issue back to its source, but have moved on to a different project.