PHP - Using a function outside the file it has been created in - php

I have 3 php files. The first (connexion.php) one contains a function I use to create a new PDO connexion:
<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Europe/Paris');
function connexion($host, $user, $pass, $db){
$db_host = $host;
$db_user = $user;
$db_password = $pass;
$db_database = $db;
return $connexion = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_password);
}
?>
The second file (my_function.php) contains a function that contains only one function that connects to a db and then is echoing some information.
<?php
include(connexion.php);
function my_first_function(){
try{
$connexion = connexion('localhost', 'user', 'user', 'mydb');
$connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//some code that echoes information
}
catch(...){...}
}
?>
My problem is when I try to include that last file into my third php script in order to be abble to use the function. The script is not even launching. I just have 'internal error'. If I remove the include(my_function.php) my file is loaded properly. I don't get it. Hope someone can help me understand. Thanks in advance. Cheers. Marc. Here below the third file:
<?php
include('connexion.php');
include('my_function.php');
//some code
my_first_function();
?>

You should not use include('connexion.php'); in the third file as it will also be included already automatically when you do include('my_function.php');
As it contains a function declaration, that will lead to an error because that function has already been declared.

"Internal error" is not a PHP thing, you may want to check your .htaccess or other apache settings.

If you are trying to include the file more than once, you will get errors because PHP won't allow you to redeclare a function with the same name. To get around that, use:
include_once("my_include_file.php");

You are either not providing the relative path to the include file or your include file has an error inside it. To test this, try the following code..
if( file_exists('the_file_where_the_function_is.php') )
{
echo "Found the file";
} else {
echo "File not found";
}
If it finds the file, then you most likely have a syntax error in the included file. Also I am guessing you are using IE and getting an "Internal Server Error" ??? If so go into your preferences for IE and turn off friendly error messages to see the actual PHP error.

Related

mysqli_connect() causes fatal error - PHP

I have the following lines of code in a script;
include '../details.php';
$conn = false;
//$conn = mysqli_connect($servername, $username, $serverpassword, $dbname);
if(!$conn){
echo "no connection";
//header("location: //www.mattwoolford.co.uk/contact/?err=003");
}
The commenting out and $conn = false; is for debugging, as is the echo statement. Here's the deal:
When I uncomment $conn = mysqli_connect(), the page goes blank from an error. Tried or die() to no avail. Tested echoing the credentials from details.php, and they present themselves correctly and successfully.
What's happening and why?
UPDATE:
Error is shown to occur on a following line:
$service = mysqli_real_escape_string($conn, $service);
"Catchable fatal error: Object of class mysqli could not be converted to string in ("path") on line 81"
UPDATE 2: FIXED
An EOT; was indented, so it was trying to convert all the functions respectively as if it were included within <<<EOT
EOT;
There may be multiple things happen:
Confirm the file path, may be it's not getting the actual file path.
Try to connect with mysql connection setting, May server support earlier mysql version.
Final thing, check for the dbname, username, password and host url.
So there can be only these three possibility, Try to do it.
It should fix.
Thanks

Constant variable already defined Xampp error

I am troubleshooting a site for someone and one of the error goes like this:
Constant serverusername already defined in C:\xampp\htdocs\employee\inc\db.php on line 5
The contents of db.php is as follows:
<?php
//Database Connection Settings
define ('hostnameorservername','localhost'); //Your server name or hostname goes in here
define ('serverusername','root'); //Your database username goes in here
define ('serverpassword',''); //Your database password goes in here
define ('databasenamed','asset'); //Your database name goes in here
global $connection;
$connection = #mysql_connect(hostnameorservername,serverusername,serverpassword) or die('Connection could not be made to the SQL Server. Please report this system error at <font color="blue">info#servername.com</font>');
#mysql_select_db(databasenamed,$connection) or die('Connection could not be made to the database. Please report this system error at <font color="blue">info#servername.com</font>');
?>
When I search the "serverusername" on the entire directory, I can't find it anywhere else other than on
:\xampp\htdocs\employee\inc\db.php on line 5
However the line:
include 'inc/db.php';
exists on numerous files.
What seems to be the problem? How can I resolve it? Thank you in advance
This problem may be occurred due to include of db.php file many times on same page.
Try this :
include_once 'inc/db.php';
Replace your code with this:
defined('hostnameorservername') or define('hostnameorservername', 'localhost');
defined('serverusername') or define('serverusername', 'root');
defined('serverpassword') or define('serverpassword', '');
defined('databasenamed') or define('databasenamed', 'asset');

What would cause include_once to break my code in PHP with MySQL?

The code below was not working:
public function __construct($thread_id)
{
require_once('../private/mysqli_connect.php');
require_once('../php_classes/class_message.php');
$this->thread_id=$thread_id;
$q="SELECT *
FROM message_thread_name
WHERE thread_id=2";
if($r=#mysqli_query($dbc, $q))
{
while($row=mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$this->poster=$row['name'];
$this->subject=$row['thread_subject'];
}
}
$qm="SELECT message_id
FROM message
WHERE thread_id=$this->thread_id";
if($rm=#mysqli_query($dbc, $rm))
{
while($rowm=mysqli_fetch_array($rm, MYSQLI_ASSOC))
{
$message=new message($rowm['message_id']);
array_push($this->messages, $message);
}
}
}
I ran out of ideas for fixing it, so I changed require_once('../private/mysqli_connect.php'); to require('../private/mysqli_connect.php');, and much to my surprise, it worked. Any ideas as to why that may be?
Thanks.
When you use require_once PHP will check if the file has already been included, and if so, not include (require) it again. You can read it here.
So whats the problem here?
From your problem statement, I am assuming you have created another instance of this class before, or you have already included mysqli_connect.php somewhere else. And in your mysqli_connect.php you have created the connection link something like.
$dbc= mysqli_connect( ... );
So when you using require_once as the mysqli_connect.php is not loading again, your $dbc variable remain undefined. and your query does not work. But when you use require instead of require_once the file loaded again, and new connection created again, and your code works.
NB: Though changing to require, solved your problem, you should not use it like this. It will create new connection to your database, each time you create new instance of your class. For your thought: you can try creating something like this

Why can't i write my MySQL database using a 'required' function?

I'm using a file called "lib.php" in which i have defined many functions.
One of these functions is the following :
function dbconn()
{
$servername="127.0.0.1";
$username="root";
$conn=mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("profit",$conn) or die(mysql_error());
}
In all the .php pages of my website, i've been using this dbconn() function, and it seemed to work fine for reading information from the database. However, when trying to write information, it seems to pose a problem. Specifically, the following code did not function :
<?php
require ("lib.php");
set_time_limit(60);
session_start();
dbconn();
$sql="update `city` set end_dt=now() where city_id='$_POST[killcity]'";
$result=mysql_query($sql,$conn) or die(mysql_error());
header("Location: manipulate.php");
?>
It says that conn is an undefined variable, whereas it should be defined by dbconn() in lib.php.
So, i've found a way around this, by instead creating a new php file called dbconn.php, which contains the exact same thing as dbconn(), and by inserting require ("dbconn.php"); instead of dbconn();.
But i'm still wondering : why did the original way not work ?
You could add a return statement for the function, through you could use global variable in a function, that's not good practice. If you want to, see how global variable works.
function dbconn() {
$servername="127.0.0.1";
$username="root";
$conn=mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("profit",$conn) or die(mysql_error());
return $conn;
}
$conn = dbconn();

PHP define() doesn't seem to be working with include()

I've been trying my hand at OO PHP, and currently have three files. I have a class_lib.php which, at the moment, just has a databaseServer class, an index.php file and a definitions.php file. I want to put all my sensitive database info into the definitions file. However, when I do, I get an error when trying to connect to the database: "Unkown server DB_HOST". My definitions file is:
<?php
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PASS","password");
define("DB_NAME","database");
?>
Then I use them in the index file like so:
include('definitions.php');
include('class_lib.php');
$testing = new databaseServer();
$testing->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
And the function I use in the databaseServer class is this:
function connect($host,$user,$pw,$db) {
$this->con = mysql_connect($host,$user,$pw);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
$this->selectDb($db);
}
function selectDb($database) {
$this->db = mysql_select_db($database,$this->con);
if (!$this->db) {
echo "Could not Select database: " . mysql_error();
}
}
Any ideas why this would not work? I've also tried putting the definitions file into an include in the class_lib file, but it still doesn't work.
This should work fine, and I've never seen it not work.
Make 100% sure the includes are in the correct order (the defines need to be loaded first)
Make test outputs of the constant values in the "definitions.php" file and the index file
Make 100% sure you are calling the right files
Please check if your server supports short_open_tag this value would be commented.
I just enabled it with on and it started working.
call it config.php
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
?>
then include("config.php"); on your pages
working
<?php
define('KLINGON_SEPARATOR', '');
?>
not working
<?php
define('KLINGON_SEPARATOR', '');
silly... IDEA says "redundant closing tag"
You just need to take out the define functions of the destinations file and transfer it to the source file (in your case "translation.php") and ready to work!
Like this the bug with define functions on receiving string params do not happen and you will include the CONSTANTS implemented already.
I faced this trouble and found myself just this one solution.
I had a similar issue today and it seems to possibly be an invalid character code at the end of the file. I found this on stack PHP define is not registering constants His solution (removing extra spaces) worked for me.
The key in this is using the constant() function to pull the value from the defined constants:
echo constant("DB_USERNAME");

Categories