I have to create separate log files for the companies Laravel 5. I have already done this in Laravel by just putting my logic in global.php file. This makes it easy to trace the errors if a specific company admin puts a complaint. Anyway, in Laravel 5 the whole structure is changed for the framework.
I've tried to override Illuminate\Foundation\Bootstrap\ConfigureLogging class in app/bootstrap directory. Every thing is going fine but when I try to get Company::find($id);, which I needed there, Laravel thrown error Call to a member function connection() on null which means I'm trying to use Laravel services before they get started.
So, I used mysqli PHP library to get company name. Now it's working fine. But somehow I want to use Eloquent instead of mysqli. But don't know how can I use Eloquent in other words starting Laravel Services in such scenarios.
Here is my code:
$companyId = isset($_COOKIE['companyId'])?$_COOKIE['companyId']:null;
if(!(is_null($companyId))){
$today = date('d-m-Y');
if(!file_exists(storage_path().'/logs/'.$today)){
// I've created the Filesystem instance as File Facade was not working here.
$file = new Filesystem;
$file->makeDirectory(storage_path(). '/logs/' . $today, 0777);
} // No problem till here
// I need to get company name from db and want to use the following two lines But...
$company = Company::find($id);
$companyName = str_replace(' ', '_', $company->name).'_'.$companyId;
// ... as laravel services are not yet started I have to use the following mysqli block (13 lines) from mysqli_connect() to mysqli_close()
// ENDING MYSQLI BLOCK
$link = mysqli_connect('localhost', 'root', 'pass', 'myDb', '3306');
if (!$link) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
mysqli_query($link, 'SET NAMES \'utf8\'');
$sql = 'SELECT name FROM companies WHERE id='.$companyId;
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$companyName = $row['name'];
}
}
mysqli_close($link);
// ENDING MYSQLI BLOCK
$log->useDailyFiles(storage_path().'/logs/'.$today.'/'.$companyName.'.log', $app->make('config')->get('app.log_max_files', 5));
}elseif(is_null($companyId)){
$log->useDailyFiles(storagePath().'/logs/laravel.log', $app->make('config')->get('app.log_max_files', 5));
}
Should I change Logging behavior in any other way i.e. using Service Providers or something else? Please help me in this regard.
Related
I've successfully connected to a remote IBM i DB2 database (AS400) from my local Windows PC via PHP. I'm using the IBM Data Server Client in conjunction with the db2_* functions in PHP. The problem I'm having is that despite my library list being set properly, it is not being used for unqualified table names. Instead it uses the current user name as the library. However, when I qualify the table names everything works like a charm.
I've confirmed that my library list is actually changing when I create the connection by querying QSYS2.LIBRARY_LIST_INFO.
$database = '<database name>';
$user = '<user name>';
$password = '<password';
$port = <port>;
$options['i5_naming'] = DB2_I5_NAMING_ON;
$options['autocommit'] = DB2_AUTOCOMMIT_OFF;
$options['i5_libl'] = 'MYLIB YOURLIB ANYLIB';
$conn = db2_connect($database, $user, $password, $options);
if ($conn) {
echo "Connection succeeded."; //It succeeds
}
else {
echo db2_conn_error()." | ".db2_conn_errormsg()."<br />";
echo "Connection failed.";
}
$sql = "SELECT * FROM QSYS2.LIBRARY_LIST_INFO";
//Works and proves my library list reflects
//what I passed in when creating the connection.
//$sql = "SELECT * FROM LIBRARY_LIST_INFO";
//Generates: "42S02 : [IBM][CLI Driver][AS] SQL0204N "<user name>.LIBRARY_LIST_INFO" is an undefined name. SQLSTATE=42704 SQLCODE=-204"
//where <user name> is the username used to connect to the DB.
//It should be using the library list specified when creating the connection though.
//This holds true for any table from any library including those specified
//when creating the connection (which includes QSYS2).
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
if($result){
while($row = db2_fetch_assoc($stmt)){
echo "<pre>";
var_dump($row); //In addition to entries for QSYS, QSYS2, QUSRSYS and QHLPSYS I get entries for MYLIB, YOURLIB and ANYLIB.
echo "</pre>";
}
}else{
echo "failed<br />";
echo db2_stmt_error()." : ".db2_stmt_errormsg()."<br />";
}
Has anyone ever run into this while enabling i5_naming when connecting to a remote DB2 server? I'm not really sure why it wouldn't be using my library list as the PHP manual states "Unqualified files are resolved using the library list for the job." when enabled. http://php.net/manual/en/function.db2-connect.php
I finally solved this after opening a PMR with IBM. All I had to do was apply the latest Fix Pack for DB2 Connect Personal Edition.
Suggested Fix Packs for DB2 Connect:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21321001
Basically the DB2 Connect version I had was released prior to 2013. It was in 2013 IBM added two tier support by adding the i5_naming option. So my DB2 Connect setup was effectively ignoring the option I was passing. So that explains why the other options still went through. On the DB side, since it didn't receive a value for i5_naming - it remained as the default.
hoping someone can help me, I am having the following error, looked online and tried a load of things but can't seem to figure it out, error:
Fatal error: Call to undefined method mysqli::mysqli_fetch_all() in C:\xampp\htdocs\cyberglide\core-class.php on line 38
heres my code:
<?php
class Core {
function db_connect() {
global $db_username;
global $db_password;
global $db_host;
global $db_database;
static $conn;
$conn = new mysqli($db_host, $db_username, $db_password, $db_database);
if ($conn->connect_error) {
return '<h1>'."Opps there seems to be a problem!".'</h1>'.'<p>'."Your Config file is not setup correctly.".'</p>';
}
return $conn;
}
function db_content() {
//this requires a get, update and delete sections, before its complete
$conn = $this->db_connect();
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM content";
// Escape Query
$query = $conn->real_escape_string($query);
// Execute Query
if($result = $conn->query($query)){
// Cycle through results
while($row = $conn->mysqli_fetch_all()){
//echo $row->column;
}
}
}
}
$core = new Core();
?>
I am trying to create a db_connect function, which I want to be able to call anywhere on the site that needs a database connection, I am trying to call that function on a function within the same class, I want it to grab and display the results from the database. I am running PHP 5.4.7, I am calling the database on a blank php file which includes a require to include the class file, then using this at the moment $core->db_content(); to test the function. I am building this application from scratch, running from MySQLi guides (not used MySQLi before, used to use normal MySQL query's) so if I am doing anything wrong please let me know, thanks everyone.
mysqli_fetch_all is a method of a mysqli_result, not mysqli.
So presumably it should be $result->fetch_all()
References:
http://php.net/manual/en/mysqli-result.fetch-all.php
Important: keep in mind mysqli_result::fetch_all returns the whole result set not a row as you assume in your code
There are three problems I see here.
while($row = $conn->mysqli_fetch_all()){
The method name is fetch_all() when used in the OOP way.
fetch_all() should be used with the $result object
fetch_all() is only available when the mysqlnd driver is installed - it frequently is not.
Reference
Only $result has that method. If you want to use it in a while loop use fetch_assoc(). fetch_all() returns an associative array with all the data already.
while($row = $result->fetch_assoc()){
}
thanks all, its working fine now, i had it as while($row = $conn->fetch_assoc()){
} before and changed to what i put above, but dident see it should of been $result instead of $conn, thanks for pointing that out.
Why do I get a "mysql_query(): supplied argument is not a valid" for the first...
$r = mysql_query($q, $connection);
In the following code...
$bId = trim($_POST['bId']);
$title = trim($_POST['title']);
$story = trim($_POST['story']);
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = {$bId}";
$r = mysql_query($q, $connection);
//confirm_query($r);
if (mysql_num_rows($r) == 1) {
$q = "UPDATE " . DB_NAME . ".`blog` SET
`title` = '{$title}',
`story` = '{$story}'
WHERE `id` = {$bId}";
$r = mysql_query($q, $connection);
if (mysql_affected_rows() == 1) {
//Successful
$data['success'] = true;
$date['errors'] = false;
$date['message'] = "You are the Greatest!";
} else {
//Fail
$data['success'] = false;
$data['error'] = true;
$date['message'] = "You can't do it fool!";
}
}
I also get an "mysql_num_rows(): supplied argument is not a valid MySQL result resource" error too.
Side notes: I am using 1&1 Hosting (worst hosting ever), custom .htaccess file with one line text to enable PHP 5.2 (only way with 1&1 Hosting).
Extra stuff add after the questions was posted...
Here is how $connection is defined. It is on its own page called connection.php that is called up using the require_once function. It it is called up on every page that require a database connection including the one in question...
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database Connection Failed: </br>" . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database Selection Failed: </br>" . mysql_error());
}
... I know it is working because this the same connect that I use for the page I have and I have no problems with it. I havent testing on my home server yet, but I am going to later to see if it is related to a 1&1 Hosting issue.
UPDATE: I am in the process of moving from 1&1 Hosting to HostMoster. 1&1 runs a PHP as CGI and runs PHP4 instead of PHP5 (you can make a custom .htaccess file to make it run PHP5). I will update you later.
The first would be because it's not a connection, and the second would be because it's not a query result because it wasn't a connection. Use mysql_error() to figure out what went wrong in the connection.
My guess is that $connection has not been properly opened. You should have a line like:
$connection = mysql_error($server, $user, $pass);
Also check mysql_error() to see the reason why it's failing.
I think that cletus meant to suggest that you need to have a mysql_connect() instead of mysql_error() before you attempt to perform a mysql_query(). It will probably look like this (with the exception that 1and1 may have given you a specific hostname to connect to for your database which you should use in place of localhost below):
//Make sure this goes before any of your other mysql_* functions
$connection = mysql_connect('localhost', 'yourUserName', 'yourPassword');
Passing $connection around for each of your queries isn't really necessary unless you have multiple database connections open concurrently that you are using and need to make sure to differentiate between the two when making query calls. Otherwise, mysql_query assumes that you are using the last database that you connected to.
Also, for security purposes as mentioned by Frank you should use mysql_real_escape_string() like so:
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = ".mysql_real_escape_string($bId).";
Tested on my local system (via WAMP), I had no problems. At the time when I had problems, I was using 1&1 Hosting. 1&1 Hosting run PHP as CGI, which probably cause my problems. I couldnt handle allof the crap with 1&1 and switch to HostMonster. Now, I don't any issues. Plus, I rather use cPanel over 1&1's admin panel.
I have mananed to use the odbc_connect like the following for access 2007 and 2003 and I can get data. But when I try to get the column names the following function will not work for access 2007 but will for acccess 2003 - why?
if($type[1]=='mdb'){
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $username, $password);
}else{
$connection = odbc_connect("Driver={Microsoft Access Driver (*.accdb)};Dbq=$mdbFilename", $username, $password);
}
function get_columns($activity_file){
global $connection;
global $typee;
$coulmn_array = array();
$result = odbc_columns($connection, $typee, "", $activity_file, "%");
while (odbc_fetch_row($result)) {
$coulmn_array[] = odbc_result($result, "COLUMN_NAME");
}
echo '<br>Exporting table '.$activity_file;
return $coulmn_array;
}
I mean I can get the data and everything, it just seems this function just won't work!
Please help!
Update
I had a google around and found this thread.
I can confirm what this person is saying. Supplying a table_name means this won't work. But if you don't it will. This isn't acceptable as what columns are being returned and for what table? I need to know this!!
This is a long shot, but there was a problem with the ODBC function SQLDescribeCol and SQLColAttributes related to Access 2007. Those functions would likely be used by odbc_columns. It is described in this KB article.
I'm trying to write php script that would:
connect to mysql
create database
create user and password
add user to database
import prepared sql file to database
The thing is that it'll be on shared host (and I'm trying to make it universal and work with different hosts). I guess database and db user will be prefixed with my account name (what I use for ftp, to login to control panel, etc) on shared hosts? Something like mylogin_dbname and mylogin_dbuser. It's visible for example in cpanel - when I add database I enter its name and after it's created cpanel shows it as mylogin_somedb. How do I make my script work with this on multiple different shared hosts - add my prefix automatically depending on my main login?
Now working with such code (don't have a clue if it works, that's just what came to my mind):
<?php
mysql_connect("host", "user", "password"); // Connection to MySQL
$query = "CREATE DATABASE somedb;
USE somedb;
SOURCE path/to/sqlfile.sql;
CREATE USER someuser IDENTIFIED BY PASSWORD 'somepass';
GRANT SELECT,INSERT,UPDATE,DELETE ON somedb.* TO 'someuser'#'host';";
$arr= explode( ';', $query );
foreach( $arr as $command )
{
mysql_query( $command );
}
mysql_close(); // Disconnection from MySQL
?>
KISS principle: just use phpMyAdmin? It's almost certainly installed. If it's not, install it.
Its import capability is magnificent. If your database is by any chance too big, gzip it. If it's still to big, try splitting it up in a few pieces. I doubt you need to transfer it as a single big transaction. Do you?
After the explanation in first comment, well, here goes. This is my very simplistic script which does what you want. Except it doesn't take a look at the separators: one query == one line.
<link rel="stylesheet" href="style/contents.css"/>
<?
function timesanitize($v) {
if ($v > 0)
return round($v, 4);
else
return 0;
}
$startmt = microtime();
include_once 'include/db.php';
$f = fopen("db.sql","r");
echo dbGetEngine() . "<br>";
echo "<ul>";
do {
$l = rtrim(fgets($f));
if (strlen($l) == 0)
continue;
if (substr($l, 0, 1) == '#')
continue;
$l = str_replace(
array("\\n"),
array("\n"),
$l);
if (dbGetEngine() == "pgsql")
$l = str_replace(
array("IF NOT EXISTS", "LONGBLOB"),
array("", "TEXT"),
$l);
try {
echo "<li>".nl2br(htmlspecialchars($l));
$mt = microtime();
$db->query($l);
echo "<ul><li>ok - " . timesanitize(microtime() - $mt) . "</ul>";
} catch (PDOException $e) {
echo "<ul><li>".$e->getMessage() . "</ul>";
}
} while (!feof($f));
fclose($f);
echo 'total: ' . timesanitize(microtime() - $startmt);
?>
It also outputs a small statistic of how long each query took. It's based around PDO; I believe PDO was introduced in PHP5.1 or PHP5.2. I think it should be trivial to modify it to work directly with mysql_*() functions, if for some reason you prefer that.
And once again: yes, I know it sucks. But as long as it Works For Me (tm), and possibly You... :-)
To complete the code, here are include/db.php and a sample include/config.php:
include/db.php:
<?
include_once 'include/config.php';
try {
$attribs =
array(
PDO::ATTR_PERSISTENT => $config['db']['persistent'],
PDO::ATTR_ERRMODE => $config['db']['errormode']
);
$db = new PDO(
$config['db']['uri'],
$config['db']['user'],
$config['db']['pass'],
$attribs
);
$db->query("SET NAMES 'utf8'");
$db->query("SET CHARACTER SET 'utf8'");
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
function dbGetEngine() {
global $config;
return substr($config['db']['uri'], 0, strpos($config['db']['uri'], ':'));
}
?>
include/config.php:
<?
//$config['db']['uri'] = 'sqlite:' . realpath('.') . '/site.db'; // PDO's database access URI
$config['db']['uri'] = 'mysql:host=localhost;dbname=sitedb'; // server should be : 195.78.32.7
//$config['db']['uri'] = 'pgsql:host=localhost;dbname=sitedb';
$config['db']['user'] = 'user_goes_here'; // database username
$config['db']['pass'] = 'pass_goes_here'; // database password
$config['db']['persistent'] = false; // should the connection be persistent
$config['db']['errormode'] = PDO::ERRMODE_EXCEPTION; // PDO's error mode
?>
Included are sample connection strings for SQLite, MySQL and PostgreSQL.
The fact that this is on a shared host shouldn't make that much of a difference in my opinion. Whatever your environment, you'll have to use your username and either the database name gets prefixed with that or it doesn't according to hosting setup. That said it is probably smart to adopt a naming convention with your username as a prefix or some other prefix naming convention.
As to what you're trying to do I have some suggestions:
You should run each statement separately (as you do) but add error checking between each step so you don't attempt to source the file if the database wasn't created for instance.
Maybe create separate functions for each kind of operation and send in parameters for the values. This would clean up the code in the longer run.
If you have a situation where something is automatically prefixed to the name you provide and you have to detect the final name, you can probably do a "show databases;" query and search for the name you gave in the results. Then use the complete name for the resulting queries.
Use mysql_error()
http://us3.php.net/manual/en/function.mysql-error.php
So you can see what went wrong.
eg:
if (mysql_query( $command ) === false) {
echo mysql_error();
die;
}
The same for mysql_connect()
if (($link = mysql_connect("host", "user", "password")) === false) {
echo mysql_error();
die;
}
You have to make sure the user you are using has privileges to create databases.
For CPanel I believe you have to use your account username and pass. Then like you said prefix your db name with your username, or it will fail to create.
Regarding import, if upload limit is an issue, there are at least one alternative to phpMyAdmin that allows you to select a file on the webserver instead of uploading it. For example adminer (adminer.org) allows that. In adminer, click "SQL command" and then click "from server"