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");
Related
I'm about to use mysqli instead of mysql for the first time in my procedural PHP application.
index.php
include(db_conn.php);
<html>
<body>
<?php include(content.php);?>
</body>
</html
db_conn.php
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
content.php
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
# more code...
mysqli_query necessarily requires the connection variable and my connection is stored in variable $con in the included db_conn.php file which is unavailable in another included content.php file.
Within your content.php use require(db_conn.php); And if you have a function defined in there, you're going to have to put require(db_conn.php); INSIDE that function.
The database connection doesn't seem to have exactly the same scoping as a standard variable.
I know when coding it, you feel like "I should only have to include this once!" but shrug get everything else working first, and if someone wants to pay you to go back and try to "fix" this... work on it then. ;)
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
I want to use a single file for my php application to connect to a database when the user register for the first time or login in
what is the code is it same as below is good:
$username="root";
$password="root";
$database="test";
function Save($name)
{
global $username;
global $password;
global $database;
$link = mysql_connect('localhost', $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO test (name)" .
"VALUES ('" . $name . "')";
mysql_query($query);
mysql_close();
}
Also, how can i do the require for that file? it is located in the root of the application folder should but i back slash first after require '/filename.php' or should i put double dots first?
If the file is in the same directory, you could simply use: include_once "db.php";
If it is in parent directory(ie, one level up), then use: include_once "../db.php";
Another one is to append the global DOCUMENT_ROOT with the filename(like others have given examples below).
And also, avoid mysql_* functions. Use PDO or mysqli instead.
Wish you good luck. :)
Your question essentailly boils down to "how can I include a file that is in the root from anywhere". Well, there's two answers.
The first answer is to just use inlude($_SERVER['DOCUMENT_ROOT']."/connect.php");, but that's a lot to type, especially if you have a lot of includes.
Personally, I like to start my script with chdir($_SERVER['DOCUMENT_ROOT']); Then I don't have to worry about where I am anymore - I will always be in the root folder.
Probably it is not good that you open mysql connection on every save, if there will be many such calls per request.
inlude($_SERVER['DOCUMENT_ROOT'] . '/db.php');
A few comments:
First, if you don't need to use the password and username and database elsewhere, you should just define them in the function.
Second, If I'm not mistaken if you put the "/" in front of the path that will take you all the way down to the root of the filesystem, which I'm guessing this user wouldn't have access to. That being said, I would use ".." to navigate up the hierarchy. So use:
require_once("../path/to/file.php")
Rather that putting the include file in the document root, you should create a directory for common include files, and add it to the include_path setting in php.ini. Then you can just do include 'connect.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.
Given a file called index.php which contains:
$db = NewADOConnection($db_dsn);
if (!$db) die("Connection failed");
$arrpage = $db->GetArray("SELECT * FROM somewhere");
include("functions.inc.php");
details("SELECT * FROM somewherelse");
The $arrpage contains the expect information
Then in the functions.inc.php file:
function details($query) {
global $db; //should check to make sure it exists
$options_array = $db->GetArray($query);
The $options_array is empty even though it should contain data.
var_dump($db) shows the DB object is all there. var_dump($options_array) is blank.
PHP 5.3.4
MySQL 14.14
ADODB 5.14
try:
$options_array = $db->GetAll($query);
Well after a lot of troubleshooting, all I needed to do was get up, have a pint of good beer and come back to it another time.
The short of it is: the system uses caching and upon close inspection of my error logs I noticed that the the cache files weren't being written to the cache folder because of folder permission issues.
I therefore fixed the folder permissions and now that the cache files can be saved, the DB query has something to refer to.
Thanks for the help anyways, I do appreciate it.