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 1 year ago.
i have a problem including MySQL connection file into my 'functions.inc.php'. If i require inside my functions, it works, but functions doesn't work if i include into another page. Like this:
function AddToVoteLogs($server_ip){
include_once 'dbh.inc.php'; // WORK
CODE ...
}
include_once 'dbh.inc.php'; // dont work
function AddToVoteLogs($server_ip){
CODE ...
}
I try to do with _ DIR _ still dont work. Another problem. My functions work in functions.inc.php page but dont work in another pages.
function AddToVoteLogs($server_ip){
include_once 'dbh.inc.php'; // WORK
$Zip = getUserIP();
$sql = "SELECT last_vote FROM votes WHERE IP = '$Zip';";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
if (time() - 86400 >= $row['last_vote']) {
$hoursIn = 1;
}
else {
$hoursIn = 0;
}
}
date_default_timezone_set('Europe/Vilnius');
$dates = date("Y-m-d H:i:s");
$ipas = getUserIP();
$sqla = "INSERT INTO vote_log VALUES ('$dates', '$ipas', '$server_ip', $hoursIn);";
$result = mysqli_query($conn, $sqla);
}
It usually doesn't matter if its called within a function or not. Frequently its caused by misunderstanding of include path resolution.
Remember that paths are resolved relative to the entry script (e.g. usually index.php). Not the functions.inc.php here.
To debug this kind of issue, try:
Use "require_once" instead of "include_once". It complains if the file is not found. The error message would show what path it is expecting.
It's usually more reliable doing paths with the constant __DIR__. The constant __DIR__ is defined against the current script file (functions.inc.php in your case). So unless you move that file around frequently, this is much more reliable.
If your dbh.inc.php is in the same directory as functions.inc.php, the path to it should be:
__DIR__ . '/dbh.inc.php'
In your case (because I do not know the structure of your project), it is better to use only absolute paths for include_path().
To do this, you should declare a constant with a root path in the root of the project and use it in include_path() in the future.
For example:
// index.php
define('DEFINED_ROOT_PATH', __DIR__.'/your-project-root-dir/'); // or $_SERVER[DOCUMENT_ROOT] or any other way
...
// Your custom .php file
include_once(DEFINED_ROOT_PATH. '/lib/dbh.inc.php');
...
Use global variable
Try This
function AddToVoteLogs($server_ip){
//include_once 'dbh.inc.php'; // NOT WORK
global $conn; // WORK
$Zip = getUserIP();
$sql = "SELECT last_vote FROM votes WHERE IP = '$Zip';";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
if (time() - 86400 >= $row['last_vote']) {
$hoursIn = 1;
}
else {
$hoursIn = 0;
}
}
date_default_timezone_set('Europe/Vilnius');
$dates = date("Y-m-d H:i:s");
$ipas = getUserIP();
$sqla = "INSERT INTO vote_log VALUES ('$dates', '$ipas', '$server_ip', $hoursIn);";
$result = mysqli_query($conn, $sqla);
}
Related
So recently I started a project where I need to load some files. In these files I have colors that come via SQL;
The Problem is, I can only include one color in a file where they'll be used. The first file to be included will work properly, but the second one will not.
The weirdest thing is that if I try to add some echo, all included files will echo it, but only the first one in the order of the import will actually work. It's kind of complicate to explain, but some code can help:
Portifolio.php (where I will use the colors)
<?php
error_reporting(E_ALL);
include_once ('php/db.php');
include_once ('php/colors/accent.php');
include_once ('php/colors/primary.php');
$page =
<<<HTML
// Long HTML code here
<nav class="$primarycolor">
// More code
<a class ="$accentcolor">
accent.php:
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 2";
$getcolor = mysqli_query($conn, $sql);
echo "Accent.php included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$accentcolor = $row['color'];
}
}
mysqli_close($conn);
?>
primary.php
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 1";
$getcolor = mysqli_query($conn, $sql);
echo "Primary.php has been included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
}
mysqli_close($conn);
?>
db.php
<?php
$conn = mysqli_connect("localhost","mucap","pswd","webdata");
echo "DB included.";
if (mysqli_connect_errno())
{
echo "Error: " . mysqli_connect_error();
}
?>
In this case:
No errors are gonna be displayed.
$accentcolor will work
$primarycolor will simply pretend it does not exists
All files will echo what they were told to.
I did a lot of research and figured out it could be something with file paths, but I dont think so: Here goes (part of) my file structure:
I cant do [$DOCUMENT_ROOT] as this is not supposed to have a fixed path, long explanation.
What should I do?
Try replacing your statement with this:
if ($getcolor) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
} else{
echo"no results in row";
}
The simple if check is possible because the results of a search return "FALSE" if there's no data in the results.
The else statement is required just for verification purposes.
If you only expect 1 result, you can do "LIMIT 1" as well as eliminate the while statement.
If you don't want the script to run at all, you should use require_once, not include_once
Hoping someone can help me with a Call to undefined function error I am getting in the following code:
$query = \FreePBX::Database()->query('SELECT model, dns, buttons, loadimage
FROM sccpdevmodel
WHERE dns > 0
ORDER BY model');
$res = $query->fetchAll();
foreach ($res as $row) {
$modelData['model'][] = $row[0];
$modelData['dns'][] = $row[1];
$modelData['buttons'][] = $row[2];
$modelData['loadimage'][] = $row[3];
}
return $modelData;
This first part seems to be ok then I get the error $modelData = sccp_get_model_data(); in this line.
<?php
$modelData = sccp_get_model_data();
$numModels = count($modelData['model']);
$addonData = sccp_get_addon_data();
$numAddons = count($addonData['model']);
?>
Any advice?
Here is a link to the source file if anyone can help please?
https://github.com/Cynjut/SCCP_Manager/tree/master
Make sure you are using an include or require statement to load your functions. I found what seems to be the full code base for this on github and didn't see where it loads in the functions you use.
Not sure if you want them conditionally loaded, but if not, you can include 'functions.inc.php'; at the top of the file that needs to use them.
I've search the answer about this question , but it doesn't solve my problem.
I have include these class
include "class/config.class.php";
include "config/config.php";
include "class/db.mssql.class.php";
on my check_login.php
and when i tried to login , after i have done type username and password, it does not do anything. Instead it show error when i use firebug .
Fatal error: Class 'cfgConn' not found in D:\wamp\www\mapis\config\config.php on line 2
this is what config.php looks like..
<?php
$cfgConn = new cfgConn();
$confMs = $cfgConn->getConf("mssql_configuration");
$dbHostMs = $confMs['host'];
$dbPortMs = $confMs['port'];
$dbNameMs = $confMs['dbName'];
$dbUserMs = $confMs['user'];
$dbPasswordMs = $confMs['pass'];
this is the path of config.php
D:\wamp\www\mapis\config\config.php
I did not see where is the error. The web is fine before i change my WAMP from 2.2 to 2.4, and after that this is what happen.
Note : the class/config.class.php was included just fine. it does not show error, instead it show the output at Firebug.
Can anybody show me what is wrong with my code?
Additional :
This is cfgConn class defined and the file name is config.class.php
<?
class cfgConn
{
function getConf($chs)
{
switch($chs)
{
//SQLServer Connection
case "mssql_configuration" : {
$c['host'] = "IT-KUNTO";
$c['dbName'] = "MAP";
$c['port'] = "";
$c['user'] = "rafi";
$c['pass'] = "P#ssw0rd";
}break;
}
return $c;
}
}
?>
In config.php file include config.class.php like this.
<?php
include "class/config.class.php";
$cfgConn = new cfgConn();
$confMs = $cfgConn->getConf("mssql_configuration");
$dbHostMs = $confMs['host'];
$dbPortMs = $confMs['port'];
$dbNameMs = $confMs['dbName'];
$dbUserMs = $confMs['user'];
$dbPasswordMs = $confMs['pass'];
So, I have a PHP class that has a method which updates a session variable called $_SESSION['location']. But the problem is, each time the method is called, it doesn't find the saved session variable, and tells me it isn't set. It's supposed to store a location ID, and the method pulls the next location from a MySQL database based on the session variable, then storing the new ID. But the place in the SQL code, that's supposed to include the variable, is empty.
I do have session_start() at the beginning of the page. I've tried manually setting the variable, and it doesn't do anything either. Also tried to reach that variable from another PHP page, and no luck either. Please help.
Small sample of my code:
class location {
#session_start();
function compass($dir) {
$select = $_SESSION['location'];
if($dir == "north") {
$currentlat = mysql_result(mysql_query("SELECT `lat` FROM `locationdb` WHERE id=".$select), 0, "lat");
$currentlon = mysql_result(mysql_query("SELECT `lon` FROM `locationdb` WHERE id=".$select), 0, "lon");
$sql = "[THE SQL CODE THAT GETS THE NEXT LOCATION]";
$id = mysql_result(mysql_query($sql), 0, "id");
$_SESSION['location'] = $id;
$return['loc'] = $this->display_location($id);
$return['lat'] = $this->display_lat($id);
$return['long'] = $this->display_long($id);
$return['id'] = $id;
}
return $return;
}
}
I have tested your code
**Dont use session_start() in this file.
For simple testing first add this inside your compass() function.
$_SESSION['location'] .= 'World';
Then create a php script with these codes.
<?php
session_start();
$_SESSION['location'] = 'Hello';
include_once('*your name of class file*');
$obj = new location();
$obj -> compass('north');
echo $_SESSION['location'];
?>
Run this script
If the output is "HelloWorld" then your $_SESSION['location'] is working.
Check your phpinfo(), to see if the session save path is defined. If not, define a directory to store the sessions. In your code:
session_save_path('/DIRECTORY IN YOUR SERVER');
Then try again.
This is closer to what your method should look like. There are some settings that will help reduce errors being thrown when running the function. With this function, and other suggestions, you should be able to remove the error your are getting.
class location
{
public function compass($dir = '')
{
// Set the $select by $_SESSION or by your function
$select = (isset($_SESSION['location']))? $_SESSION['location']: $this->myFunctionToSetDefault();
// I set $dir to empty so not to throw error
if($dir == "north") {
$currentlat = mysql_result(mysql_query("SELECT `lat` FROM `locationdb` WHERE id=".$select), 0, "lat");
$currentlon = mysql_result(mysql_query("SELECT `lon` FROM `locationdb` WHERE id=".$select), 0, "lon");
$sql = "[THE SQL CODE THAT GETS THE NEXT LOCATION]";
$id = mysql_result(mysql_query($sql), 0, "id");
$_SESSION['location'] = $id;
$return['loc'] = $this->display_location($id);
$return['lat'] = $this->display_lat($id);
$return['long'] = $this->display_long($id);
$return['id'] = $id;
}
// This will return empty otherwise may throw error if $return is not set
return (isset($return))? $return:'';
}
}
Hey I've a problem with my code.
It works fine for the first 10 name, but then "file_get_contents" return just empty strings
Is this a timeout problem? or has it a other reason?
And how can i fix this?
my Code:
<?php
$member;
mysql_connect("localhost","**********","********");
mysql_select_db('bf3_ezstats');
$sql = mysql_query('SELECT id, name FROM ez2bf3_player ORDER BY id ASC');
while($row = mysql_fetch_assoc($sql)){
$member[$row['id']] = $row['name'];
}
mysql_close();
print_r($member);
foreach ($member as $ip => $player){
ini_set('default_socket_timeout', 120);
$SC = file_get_contents('http://battlelog.battlefield.com/bf3/user/'.$player);
$SC = split('<surf:container id="profile-gamereport-previews">',$SC);
$SC = split('</surf:container>',$SC[1])[0];
$IPs = array(0=>$player);
while(strpos($SC,'href') !== false){
$start = strpos($SC,"href");
$end = strpos($SC,'"',$start+6);
$IP= substr($SC,$start,$end-$start);
$IPs[] = "http://battlelog.battlefield.com".str_replace('href="',"",$IP);
$SC = substr($SC,$end,strlen($SC)-1);
}
print_r($IPs);
}
?>
file_get_contents() on external URIs is just a huge security issue. This method could lead to many errors, probably including yours.
If you need to work on external servers, through HTTP, I strongly recommand the use of cURL (http://php.net/manual/fr/book.curl.php). You'll find it more handy, I think, and you may save yourself a lot of trouble.