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;
.....
Related
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
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'));
$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);
This question already has answers here:
PHP errors are not shown
(2 answers)
Closed 9 years ago.
I'm feeling my way around php for the first time in years. I'm trying to perform a simple select statement. I've confirmed the statement works directly against mysql. My php does not complete. I'd like to know why my real_query isn't working, I'd also like to know how to coax an error message out of this scenario. Here's the code:
function getRoot($nid)
{
echo $nid; //displays 0
try
{
echo "Hello?"; //This displays
//Why doesn't this work?!
if($mysqli->real_query("SELECT * FROM gem, bundles WHERE gem.nid = bundles.baseNid AND bundles.nid = " . $nid))
{
echo "dafuq?"; //does not display
}
else
{
echo "foo"; //doesn't display
echo $mysqli->error; //doesn't display
}
}
catch (Exception $e)
{
echo "Tralalalala"; //doesn't display
}
echo "teeheehee"; //doesn't display
}
Thanks for your help!
There is no $mysqli variable declared in the function, so your code produce a FATAL ERROR - you are calling a method of a non-object. if $mysqli is a global variable, you have to add global $mysqli; in the beginning of the function
$mysqli is not defined in the function, and PHP throws a fatal error, which is not catcheable using standard exceptions.
You need to enable error reporting (display_errors set to On in php.ini, or through ini_set, eg: ini_set('display_errors', '1'); );
First let me say sorry for the amount of code I'm posting below I'm going to try and keep it as short as possible but this is built on top of my MVC (lightweight-mvc)
Ok So my Problem is that for some reason php is throwing a fatal error on code that should not be being used in my current code,
So how this works I have my MVC witch used the first 2 parts of the url to know what its loading, the problem is I'm building a Moulder CMS into my MVC so it's boot strapping twice,
So here is my Problem,
http://{domain}/admin/control/addon/uploader/method/uploadCheck/
I'm using the above now let me explain a little into that the /admin/control are for the main MVC System it auto-loads the Admin controller then fires the controlAction method from the controller much the same as most MVC's,
The next part are URL paramters that build an array the same as GET or POST would
array('addon'=>'uploader', 'method'=>'uploadCheck')
So from that my control action will auto load as is the code below
public function controlAction(){
global $_URL;
if(cleanData::URL("addon")){
$addonName = "addon_".cleanData::URL("addon");
$methodName = (cleanData::URL("method"))? cleanData::URL("method")."Action" : "indexAction";
echo $methodName;
$addon = new $addonName();
$addon->$methodName();
return;
}else{
$this->loadView("CMS/controll");
}
}
cleanData::URL is an abstract method that just returns the value of the key provided though addSlashes()
So as you can see from the code below it will then use the autoloader to load the module(AKA addon)
Just so you can follow the auto loader works in a simpler version of the Zend Frame work autoloader _ so you have class name addon_admin that would be inside file admin.php that is in the folder addon so the autoloader will load addon/admin.php
So As above with my URL and controlAction it's loading addon/uploader.php and as such this is the contents
<?php
class addon_uploader extends Addons{
public function uploadCheckAction(){
echo 0;
}
public function uploaderAction(){
if (!empty($_FILES)) {
$tmpFile = $_FILES['Filedata']["tmp_name"];
$newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']);
move_uploaded_file($tmpFileName, $newLock);
$POSTback = array(
'name' => $_FILES['Filedata']['name'],
'type' => $_FILES['Filedata']['type'],
'tmp_name' => $newLock,
'error' => $_FILES['Filedata']['error'],
'size' => $_FILES['Filedata']['size']
);
echo json_enocde($POSTback);
}
}
}
?>
But as you can see from my URL its using the uploadCheckAction method witch for debugging i have set so it always says false (AKA 0),
But i seem to get this error:
Fatal error: Only variables can be passed by reference in C:\xampp\htdocs\FallenFate\addon\uploader.php on line 11
But line 11 is $newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']); witch should not be being used could any one provide any help into why this would occur and how i could fix it
end() PHP Manual needs an expression of a single variable (more precisely an array), but not a function return value or any other type of expression.
I think that's basically the cause of your error, more specifically with your code:
$newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']);
you're even driving this far beyond any level of treatment PHP can cope with:
you concatenate an array with a string (which results in a string).
you run end() on that string - not on a variable, not even an array.
I have no clue what you try to do with the code, but I can try:
$filename = $_FILES['Filedata']['name'];
$parts = explode('/', $tmpFile);
$last = end($parts);
$newLock = "../uploads/". $last . $filename;
Or probably even only this:
$filename = $_FILES['Filedata']['name'];
$newLock = "../uploads/". $filename;