Fat free framework: DB query - non-object - php

We are following the get started tutorial on github, all went well but we are stranded on the DB connection.
We have created the $db object:
$db=new DB\SQL(
'mysql:host=localhost;port=3306;dbname=liselore',
'jow',
''
);
And we have set up a controller:
$f3->route('GET /',
function($f3) {
$f3->set('result',$db->exec('SELECT achternaam FROM test1'));
$template = new Template;
echo $template->render('views/homepage.html');
}
);
$f3->run();
However, we get this error:
Internal Server Error
Fatal error: Call to a member function exec() on a non-object
• fatfree-master/index.php:32
I think the error relates to the $db object that is not set. However, we do have php-pdo set, i just checked via phpinfo().
Any help would be great, thx...

You're using a closure which means the $db variable is no longer in scope. You need to use the use keyword to tell PHP to allow the use of the variable from the parent scope.
$f3->route('GET /', function($f3) use ($db) {
$f3->set('result', $db->exec('SELECT achternaam FROM test1'));
$template = new Template;
echo $template->render('views/homepage.html');
});
$f3->run();

You said it already:
all variables set using the $f3->set method are global
and yes, it's a common practise to save such objects in those framework vars. So just try
$f3->set('DB', $db=new DB\SQL('mysql:host=localhost;port=3306;dbname=liselore','jow',''));
and use this everywhere else:
$f3->set('result',$f3->get('DB')->exec('SELECT achternaam FROM test1'));

Related

How to move functions to another file [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
I developed a query to list fields with checkboxes for the user selection of ones to include in a query result. It was working in the template file (based on page.php). Then I decided to move the logic that I will be using in other templates to a db-functions.php file. Now, I'm getting
Fatal error: Call to a member function get_results() on null in /home/...
printf($the_db) returns the proper login credentials, but apparently an error because 'affected_rows' = -1.
I can't find what's missing or misconfigured. Code is below.
require_once($_SERVER['DOCUMENT_ROOT'] . $folder . '/wp-config.php');
require_once($_SERVER['DOCUMENT_ROOT'] . $folder . '/wp-load.php');
//db-setup
function dbsetup($usr, $passwd, $databas, $hst){
global $wpdb;
$the_db = new wpdb($usr, $passwd, $databas, $hst);
}
//disp-field-list
function dbfldfrm(){
$fieldlstress = $the_db->get_results("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'index_records'");
Before asking, please search for solution on this site, with the error string. Btw, you need to globalise the variable from local scope to be available globally:
function dbsetup($usr, $passwd, $databas, $hst){
global $wpdb;
global $the_db;
$the_db = ...
// same as: $GLOBALS['the_db'] = ...
and secondly, to obtain from global scope, do the same:
function dbfldfrm(){
global $the_db;
.....

PHP - Fatal error: Uncaught Error: Call to a member function query() on null in [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
I cannot find the solution, spending hours of troubleshooting, though. Frustration growns steadily.
The problem: I try, after transferring a web page to a new provider that requires the oop approach for mysql interfaces, to reset all the sql command lines. This works fine. But there is one part that I cannot get working. The called php-file movie.php looks like:
<?php
include 'scripts/init.php';
...
$cameraString = AssignPerson( $movieID, 'camera' );
?>
The important bits from init.php are:
<?php
session_start();
include 'scripts/connect2SQL.php';
include 'scripts/logInOut.php';
include 'scripts/classes_functions.php';
?>
The connect2SQL.php reads
<?php
$connection2MySQL = mysqli_connect( "localhost" , "***" , "***", "***");
mysqli_query( $connection2MySQL , "SET CHARACTER SET 'utf8'" );
mysqli_query($connection2MySQL , "SET SESSION collation_connection ='utf8_unicode_ci'" );
?>
So the variable $connection2MySQL represents the oop connection to the database.
The function AssignPerson( $movieID, 'camera' ); in the movie.php is defined in the classes-file classes_functions.php. Here, the essential snippets are
function AssignPerson( $objectID, $type = 'actor' ) {
$memoryString = '';
// THAT FOLLOWING LINE IS NOT WORKING :::
$persons = $connection2MySQL->query( "SELECT * FROM actors2movies" );
if ( mysqli_num_rows( $persons ) ) {
while ($person = mysqli_fetch_assoc( $persons )) {
$personID = $person['personeID'];
$memoryString .= $person['personName'];
}
}
return $memoryString;
}
The error message that comes up in the browser looks like:
Fatal error: Uncaught Error: Call to a member function query() on null in /var/www/web26777278/html/filmstadt-quedlinburg/scripts/classes_functions.php:173 Stack trace: #0 /var/www/web26777278/html/filmstadt-quedlinburg/movie.php(354): AssignPerson('800', 'director') #1 {main} thrown in /var/www/web26777278/html/filmstadt-quedlinburg/scripts/classes_functions.php on line 173
The issue here is, that when I delete the lines of the query (and the following ones), the program works. So the error must be in the line i indicated above. On the other hand, if I copy that line directly into the movie.php, the line works! So it must have to do something with the encapsuling thing of php-files into the others.
I checked if I need to repeat the including line of the SQL connection in the classes.php. I checked also, whether there are forgotten brackets, spelling mistakes in the database tables and that kind of things. Can't help myself.
Do you have any idea where I could have another look for the problem?
Greetings and thank you
Frank
$connection2MySQL is declared outside function so it is null inside function.
You have to pass connection object to function to work properly

Is there any way to carry down a PHP magic constant as a function default?

The idea here is to create a method for logging and debugging purposes, that doesn't require passing said method the associated 'magic constants'.
Effectively, I'm trying to achieve this using a method definition like so:
function Debug($Message,$File=__FILE__,$Line=__LINE__)
{
...
}
The problem I am running in to is that if I define the above method in a file other than the one I am 'debugging', I end up with the file and line from the file the method is defined in, rather than the one I am 'debugging'.
Consider the following set of files:
Debugging.php
<?
function Debug($Message,$File=__FILE__,$Line=__LINE__)
{
echo("$File ( $Line ) :: $Message");
}
?>
Testing.php
<?
Debug("Some message");
?>
Output:
Debugging.php ( 1 ) :: Some message
When the invocation of the message occurred in the second file - which, as should be clear by this point, isn't the intended implementation. I could of course pass the 'Debug' method those magic constants at the time of invocation, but I'm looking to eliminate unnecessary code if possible.
You would use the function debug_backtrace like so.
function Debug($Message)
{
$backtrace = debug_backtrace();
echo($backtrace[0]['file'] .'(' . $backtrace[0]['line'] . ') :: ' . $Message);
}

Having to call COM object method once before it can be used inside of function

I'm learning about using COM objects and dlls in PHP, and I've come across something that doesn't really look right. This works:
$comobj = new COM("COMLoggerClass");
echo 'here1';
$comobj->Log('test1');
echo 'here2';
function test($pComObj)
{
echo 'here4';
$pComObj->Log('test2');
echo 'here5';
}
echo 'here3';
test($comobj);
This doesn't:
$comobj = new COM("COMLoggerClass");
echo 'here1';
//$comobj->Log('test1');
echo 'here2';
function test($pComObj)
{
echo 'here4';
$pComObj->Log('test2');
echo 'here5';
}
echo 'here3';
test($comobj);
The second causes a fatal error on the line $pComObj->Log('test2'); with this message:
Cannot pass parameter 1 by reference
So essentially, in this case, the COM object's method is having to get used once in the scope the object was created in before it can be used in the method. That doesn't make any sense though. What's really going on here?

PHP, scope resolution with variable passed

$columnToChange = $this->getColumnName($questionNo); //Gets EXAMHIST_Q2_JUGDGE
$conn = Propel::getConnection(ExamHistoryPeer::DATABASE_NAME);
//Update the approriate question with user answer in exam history table;
$selectCriteria = new Criteria();
$selectCriteria->add(ExamHistoryPeer::EXAM_HISTORY_ID, $examHist->getExamHistoryId());
$updateCriteria = new Criteria();
//This shows fatal error
$updateCriteria->add(ExamHistoryPeer::$columnToChange, $userAnswer);
//$updateCriteria->add(ExamHistoryPeer::EXAMHIST_Q2_JUGDGE, $userAnswer); //This works
BasePeer::doUpdate($selectCriteria, $updateCriteria, $conn);
Fatal error: Access to undeclared static property: ExamHistoryPeer::$columnToChange
Can any of you guys, please tell me why can not this works, and how to make it work with
ExamHistoryPeer::$columnToChange
PHP is thinking that you want to get static property not constant. It's because of $ sign in ExamHistoryPeer::$columnToChange.
Instead use constant('ExamHistoryPeer::columnToChange') to get values of that constant.
You could maybe do this ?
$oReflection = new ReflectionClass(ExamHistoryPeer);
//Value of the Constant
$mValue = $oReflection->getConstant($columnToChange);

Categories