I'm having a problem with an array in php, which I use to store configuration data for different environments. The idea is that I only have to switch out the file with the config data when going from local testing to using it on the server. The file looks like this:
<?php
$_ENV = array(
'MySQL' => array(
'database'=>'<DATABASENAME>',
'server'=>'<SERVERNAME>',
'username'=>'<USERNAME>',
'password'=>'<PASSWORD>'
)
);
?>
And I include it this way:
include('../env.php');
For the connection to the database I use it like this:
$conn = mysql_connect($_ENV['MySQL']['server'], $_ENV['MySQL']['username'],$_ENV['MySQL']['password']) or die("No connection possible: " . mysql_error());
Ignoring the fact that I'm still using mysql instead of PDO or mysqli, which is a thing I'm going to change soon, this should work. But it does not:
Notice: Undefined index: MySQL in D:\data\dev\applications\wtc-feedback\dashboard\include\SQLrequest.php on line 36
The strange thing is that when I dump the environment variable onto the screen with var_dump() the indexes and the contents are all just fine.
Does anyone know how to fix this?
If You want to work with environmental variables use getenv, putenv
or use .env files (package here, docs here) and add .env to .gitignore
in fact Your code must be like this:
env.php:
<?php
putenv('DB_NAME=DATABASENAME');
putenv('DB_HOST=SERVERNAME');
putenv('DB_USER=USERNAME');
putenv('DB_PASS=PASSWORD');
connection.php:
<?php
include('../env.php');
$conn = mysql_connect(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'))
OR die("No connection possible: " . mysql_error());
".env" way:
.env file:
DB_NAME=DATABASENAME
DB_HOST=SERVERNAME
DB_USER=USERNAME
DB_PASS=PASSWORD
connection.php:
<?php
require_once('../vendor/autoload.php');
use Symfony\Component\Dotenv\Dotenv;
(new Dotenv())->load(__DIR__.'/../.env');
$conn = mysql_connect(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'))
OR die("No connection possible: " . mysql_error());
Simple solution wouuld be, return the simple array from the file. as
<?php
return array(
'MySQL' => array(
'database'=>'<DATABASENAME>',
'server'=>'<SERVERNAME>',
'username'=>'<USERNAME>',
'password'=>'<PASSWORD>'
)
);
?>
In other file
$credentials = require_once "../env.php";
Use the $credentials array to supply parameters to mysql connection function
Related
Please excuse the long post - I've tried to be as succinct as possible, whilst giving as much detail as I can ... and I've historically been a procedural PHP programmer, now getting my feet wet with objects.
I'm working on a test project where I'm using a 3rd party class (loaded via phar) to capture a stream from an online server. The online server posts events, I capture (using "capture.php") each event with the 3rd party class, serialize the data and then store it to a MySQL database as a BLOB field.
//capture.php
// include phar file
require_once 'PAMI-1.72.phar';
// set include path to have pami's phar first
ini_set('include_path', implode(PATH_SEPARATOR, array('phar://pami.phar', ini_get('include_path'))));
use PAMI\Client\Impl\ClientImpl as PamiClient;
use PAMI\Message\Event\EventMessage;
use PAMI\Listener\IEventListener;
$pamiClient = new PamiClient($pamiClientOptions);
// Open the connection
$pamiClient->open();
$pamiClient->registerEventListener(function (EventMessage $event) {
// Following line dumps the event to a text file in rawCapture.php
//var_dump($event);
$mysqli = new mysqli($server, $user, $pass, $db);
if ($mysqli->connect_error) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit;
}
$serializedData = $mysqli->real_escape_string(serialize($event));
$sql = 'insert into obj (data) values ("' . $serializedData . '")';
echo "\r\nSQL is $sql\r\n";
});
In a different script ("read.php" - I know - I'm VERY creative in script naming) I ensure that I have the include files to the class definition files, pick up the first entry in the database, pull the BLOB data and then unserialize it. At this point I'm testing the variable type in read.php and the variable is an object:
require_once 'PAMI-1.72.phar';
// set include path to have pami's phar first
ini_set('include_path', implode(PATH_SEPARATOR, array('phar://pami.phar', ini_get('include_path'))));
use PAMI\Client\Impl\ClientImpl as PamiClient;
use PAMI\Message\Event\EventMessage;
use PAMI\Listener\IEventListener;
/* All the MySQL stuff to get the $data from the db */
$event = unserialize($data);
echo "\r\nevent is " . gettype($event) . "\r\n";
print_r($event);
And this is the result I get:
event is object
PAMI\Message\Event\NewchannelEvent Object
(
[rawContent:protected] => Event: Newchannel
Privilege: call,all
Channel: Local/s#tc-maint-00006a43;2
ChannelState: 4
ChannelStateDesc: Ring
CallerIDNum:
CallerIDName:
AccountCode:
Exten: s
Context: tc-maint
Uniqueid: 1443368640.57856
[lines:protected] => Array
(
)
[variables:protected] => Array
(
)
[keys:protected] => Array
(
[event] => Newchannel
[privilege] => call,all
[channel] => Local/s#tc-maint-00006a43;2
[channelstate] => 4
[channelstatedesc] => Ring
[calleridnum] =>
[calleridname] =>
[accountcode] =>
[exten] => s
[context] => tc-maint
[uniqueid] => 1443368640.57856
)
[createdDate:protected] => 1443368636
)
Ok - so far so good, IMHO. This certainly appears to be an object, all the data certainly appears to have been stored correctly (rawCapture.php is another script which also polls the data and var_dumps the same events out to a text file, so that I can "compare" and ensure that everything is being recorded correctly).
However, now I want to deal with some of the object data and this is where I'm having issues. For example, I'm trying to obtain the value of the Uniqueid, but using $id = $event->Uniqueid; I get the following error PHP Notice: Undefined property: PAMI\Message\Event\NewchannelEvent::$Uniqueid in /home/dave/objRead.php on line 69
Now I'm stuck. I've tried checking that $event is in fact an object, using get_object_vars():
$objVars = get_object_vars($event);
if(is_null($objVars)){
echo "\r\nobjVars doesn't appear to be an object?!\r\n";
} else {
if(is_array($objVars)){
print_r($objVars);
} else {
echo "\r\nobjVars isn't an array!!\r\n";
}
}
and I'm getting my own error code "objVars doesn't appear to be an object?!".
Can anyone give me some advice on what on earth I'm doing wrong??
Also - I've tried to keep indentation in the code sections above but it wouldn't let me post without removing them. I've also amended my OP to show that I'm including the 3rd party code so that the class definitions are loaded, and the line that I use to unserialize the data from the MySQL table.
Have you tried changing the case of Uniqueid in $id = $event->Uniqueid; to lower case? So it would be $id = $event->uniqueid;
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'));
how do i use getLastError() within php to check if my save method is inserting to mongo?
i set up my db as follows:
$this->databaseEngine = $app['mongo'];
$this->db = $this->databaseEngine->dbname;
$this->collection = $this->db->collectionname;
my insert query then looks like this:
$query = array(
'fieldname' => $fieldname
);
$this->collection->insert($query);
I want to then use getLastError() to check whether it is inserting correctly, and if not why. but im not sure how to implement it.
do i use after the insert:
$this->collection->getLastError("what goes here?");
cheers.
Update
i eventually used this to get the last error:
echo '<pre>' . print_r($this->databaseEngine->lastError(), true) . '</pre>';
Sammaye's way works just as well, see below.
$this->collection->getLastError("what goes here?");
Nothing goes there, the return of the getLastError is the last error from MongoDB ( http://www.php.net/manual/en/mongodb.lasterror.php ). Also it is used on the MongoDB class (atm).
You don't have to use it like that, instead you can do:
$this->collection->insert($query, ARRAY('safe' => TRUE));
This will return an array from the function detailing whether or not it actually inserted. The details of the array can be found by reading this page:
http://www.php.net/manual/en/mongocollection.insert.php
I am trying to get data from MySQL database but in the php file I get this error:
Fatal error: Call to undefined function: json_encode() in /homez.100/pizzapar/www/clic/marwa/test/base.php on line 13
Here is my php file:
<?php
echo"welcom <br>";
$conn = mysql_connect('xxx.xxx.xxx.xxx','xxx','xxx');
if ($conn) {
mysql_select_db('zak', $conn);
$sql=mysql_query("select * from zak_user");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
}
else
{
echo"erreur connexion";
}
Can some one help?
According to the manual, json_encode() is available in PHP >= 5.2.0 only. You are probably running an older version.
See here:
http://www.boutell.com/scripts/jsonwrapper.html
This is a replacement for JSON in earlier PHP versions.
Usage:
require 'jsonwrapper.php';
At the top of your code and you're ready to go. Of course,
jsonwrapper.php must be in the same folder. If not, adjust the require
command.
json_encode example
Just to give you a sense of the possibilities:
$data = array(
array('name' => 'Jane', 'age' => 35),
array('name' => 'Steve', 'age' => 37)
);
<script>
var data = <?php echo json_encode($data) ?>;
</script>
And this is the direct download:
http://www.boutell.com/scripts/jsonwrapper.tar.gz
json_encode used to be not part of PHP, you might have to compile an extension to enable this function.
It's been awhile that json_encode is shipped with PHP(since 5.2), I advise you to upgrade.
Consider the following code:
<?php
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database', $conn);
?>
This works as expected, but how does PHP know what database connection to use when calling mysql_select_db() in the following example?
<?php
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
?>
The PHP documentation states that "If the link identifier is not specified, the last link opened by mysql_connect() is assumed." (PHP: mysql_select_db())
Where is the last connection stored or retrieved from?
I suppose a link to the last opened connection is kept somewhere in memory, to make things easier (as we generally often use only one connection).
Quickly going through the sources of ext/mysql :
(All line numbers are in php_mysql.c -- the version of the sources is a random snapshot of PHP 5.3.2-dev from a couple of weeks ago ; so, they might have changed a bit)
The user-space function called mysql_connect seems to correspond to the C-level function called php_mysql_do_connect (line 922)
The php_mysql_do_connect function calls php_mysql_set_default_link (line 832)
To store the last opened connection
There is also a function called php_mysql_get_default_link (line 908)
That php_mysql_get_default_link function is called by mysql_select_db, when there is no link passed to it (line 992)
And php_mysql_set_default_link is calling this to store the default_link :
MySG(default_link) = id;
That MySG being a macro, defined like this (in php_mysql_structs.h) :
#ifdef ZTS
# define MySG(v) TSRMG(mysql_globals_id, zend_mysql_globals *, v)
#else
# define MySG(v) (mysql_globals.v)
#endif
Pretty much looks like a global variable to me ;-)
If you want, you can take a look at the sources yourself : ext/mysql/php_mysql.c and ext/mysql/php_mysql_structs.h.
As I said, this has probably been modified a bit since the version in which I checked -- which means the line numbers might not match exactly ; but the functions names are easy anough to understand, so you should be able to track down what calls what and where :-)
I wish this class will help you , i had already written it ............ sorry it needs testing
class connectionManager(){
protected $array = array(
"connection1" => "host3-username-password-database1" ,
"connection2" => "host2-username-password-database2" ,
"connection3" => "host1-username-password-database3" ,
)
protected $history = array();
public function __construct($connectionID = connection1){
$this->savelastConnecton($connectionID);
/*do you magic here to change the string above to desired format
sorry but i gatta go
btw i liked your question
*/
mysql_connect($host , $username , $password);
mysql_select_db($database);
return true ;
}
publich function getLastConnection( ){
return end($this->history[$lastnumber]) ;
}
private function saveLastConnection($connectionID){}
$this->history[] = $connectionID ;
return true ;
}