Codeigniter remote connection does not return queries - mysql

I have a local and a remote connection with my mysql database. The local connection works just fine. But the remote connection, while it makes a connection, it does not return anything. I usually get the following:
Fatal error: Call to a member function result() on a non-object
I use for the remote connection the following configuration:
$db['mydb']['hostname'] = "ip_address_of_database";
$db['mydb']['username'] = "username";
$db['mydb']['password'] = "password";
$db['mydb']['database'] = "database";
$db['mydb']['dbdriver'] = "mysql";
$db['mydb']['dbprefix'] = "";
$db['mydb']['pconnect'] = FALSE;
$db['mydb']['db_debug'] = FALSE;
$db['mydb']['cache_on'] = FALSE;
$db['mydb']['cachedir'] = "";
$db['mydb']['char_set'] = "utf8";
$db['mydb']['dbcollat'] = "utf8_general_ci";
In my function that accesses the database I check if there is a connection with the remote server and then I try to retrieve data.
$mydb = $this->load->database('mydb', TRUE);
if (!isset($mydb->conn_id) && !is_resource($mydb->conn_id)) {
$error = 'database is not connected';
return $error;
}else{
$query = $mydb->query("SELECT * FROM database LIMIT 1;");
return $query->result();
}
This works fine in the localhost database but not in the remote database. I allways get the error
Fatal error: Call to a member function result() on a non-object
Can you please help? What am I doing wrong? I stuck on this.

Finally, I found the solution after contacting my web hosting provider. The issue had to do with the Remote database access and their servers. The IP address exception and the domain name that I had added didn’t do the job. I had to add an internal domain name that my host was using in order the Remote database access to be allowed. I spent 2-3 hours chatting with them in order to find a solution.
Anyway now is solved. I am posting that FYI.

Related

Codeigniter insert query to database problem

I'm facing an issue to do insert query into the database.
Not sure is a setting issue or a connection issue. The setting I did at .env file while the query I did at controller site
Here is my setting at env file:
CI_ENVIRONMENT = development
app.baseURL = 'http://localhost:8080/'
database.default.hostname = 127.0.0.1 #localhost:8080
database.default.database = learn_ci4_tutorial
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
here my code at controller site:
public function __construct(){
this->db = \Config\Database::connect();
}
public function insertRaw(){
echo "<h1>Test connection</h1>";
$insert_query = "Insert into tbl_user(name,email,phone_no) values('Alyah','aliyah#gmail.com','123456')";
$this->db->query($insert_query);
if($this->db->query($insert_query)){
echo "<h1>Insert record successful.</h1>";
}else{
echo "<h1>Insert record failed.</h1>";
}
}
here the error come out:
ErrorException #1
Uncaught ErrorException: print_r(): Property access is not allowed yet in C:\xampp\htdocs\ci4\app\Views\errors\html\error_exception.php:96
Which part should I fix so I can do insert query to database?

Can I check which connection is being used to the query - laravel read-write connection?

Is there any way to check which connection read/write is being used to the query ? I am trying to log the query object it returns me both the connection pdo & readPdo but do not specifying that which connection is being used
DB::listen(function ($query) {
dump($query->connection);
});
$table = DB::table('table')->first();
Output:

Adldap2 authentication always returns true - Yii2

I'm working in Yii2 with the Adldap extension found here: https://github.com/Adldap2/Adldap2
I'm running into an issue when I try to authenticate users on my ldap server. I can successfully make a connection and and retrieve user data, but when trying to authenticate if a user's username and password are correct or not, it always returns true, even if the creds are wrong. Below is my code snippet (with the config array not showing of course):
$ad->addProvider($config);
try {
// If a successful connection is made to your server, the provider will be returned.
$provider = $ad->connect();
//User below does return the correct information from the ldap server
$user = $provider->search()->users()->find('quillin');
try{
$provider->auth()->attempt("wrongUsername","wrongPassword");
die("WIN");
}catch( Exception $e ){
die("Exception " . $e);
}
}catch (\Adldap\Auth\BindException $e) {
die( "There was an issue binding / connecting to the server. <br />" . $e);
}
No matter what I put in for the username and password fields, it always returns true and hits the die("WIN"); line. In my composer.json file, i'm using "adldap2/adldap2": "v7.0.*"
I have also tried to bind the user using the following:
try{
$provider->auth()->attempt("wrongUsername","wrongPassword", $bindAsUser = true);
die("WIN");
}catch( Exception $e ){
die("lose :(");
die("Exception " . $e);
}
And that also always returns true;
I figured this out and will explain here in anyone else has the same issue.
1) $provider->auth()->attempt() should be wrapped in an IF, and not a try/catch.
2) The first parameter, $username, is actually looking for the userprincipalname, the docs had made it sound like it was looking instead for a username.
After that, I was able to authenticate the user successfully.

Making PDO Database Connection available in controllers and models

right now, I am kinda frustrated and I hope someone can help me and point me into the right direction.
I have an "old" project which uses the mysql statements for connection to database, etc.
Within this project I have the following:
An index file containing
*
* load configuration and connect to database
*/
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect($projectConfiguration->databaseHost, $projectConfiguration->databaseName, $projectConfiguration->databaseUser, $projectConfiguration->databasePass);
// load controller
$ReqMod = FatFramework\Functions::getRequestParameter("mod");
if (!$ReqMod) {
$ReqMod = FatFramework\Functions::getRequestParameter("controller");
}
$module = ($ReqMod) ? $ReqMod : 'default';
In this style I call the views and actions in classes, like SaveAction()
Using mysql always made it very simple to use this database connection in the models called by the controllers like
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$sql = mysql_query($sQuery);
while (($customer = mysql_fetch_object($sql)) != false) {
$aCustomers[] = $customer;
}
return $aCustomers;
}
I want to totally refractor this project and use PDO. I tried for the last 4 hours to find a solution, but I can't figure out how to make it work.
I think I don't need an extra dbconnect class since PDO is a class itself, am I right?
In the new index file I tried the following:
$db = new database();
try{
$dbc = new PDO($db->get_DbConSettings());
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo 'Verbindung fehlgeschlagen: '.$e->getMessage();
}
But with this $dbc will not available in controllers or models. It there a way to make it available there? If not, what is the best solution?
Do I have to make a database connection in every model?
An other issue I have with this is:
$db->get_DbConSettings()
in
$dbc = new PDO
gives back
'mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123'
($dbc = new PDO('mysql:host=127.0.0.1; dbname=c1virtbkk', 'root', '123');)
I cannot connect to the database. I get the following:
Verbindung fehlgeschlagen: could not find driver
If I don't use $db->get_DbConSettings and put the required information manually in, I don't get any error and can do queries. Any hints?
Help is really appreciated.
Thanks in advance!
Mark
Definitely don't create a new PDO connection in each model. Creating MySQL database connections is fairly quick, but there's still some overhead to doing so. You want to reuse a connection throughout your request. If nothing else, it allows you to share a transaction across multiple models.
Some frameworks store shared resource objects in a "registry" class which is a singleton key-value store. It's not really much more than a global hash array, but making it a class makes the registry itself more easily tested with PHPUnit. See https://framework.zend.com/manual/1.12/en/zend.registry.using.html for an example of a registry.
You're right that PDO is a class, even though it's implemented as a C extension instead of a PHP class. But it's a class, and new PDO(...) returns an object of that class.
One reason to create a db class of your own is to help you in unit-testing, because you could create a mock object for your db class so you can test your other classes (even model classes) without needing a live database connection. Your db class could extend or else contain a PDO object.
Your issue about the error "could not find driver" is probably because the PDO driver for mysql is not installed. PDO is one PHP extension, and then there's a separate extension for each brand of SQL database. You can confirm this with:
$ php -i
...lots of output...
PDO
PDO support => enabled
PDO drivers => mysql, odbc, sqlite
pdo_mysql
PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $
...more output for other extensions...
Note that PDO tells me which drivers I have installed: mysql, odbc, and sqlite.
So you need to install pdo_mysql. I'm not sure what OS you're on, but I'm often on CentOS Linux or Ubuntu Linux. The pdo_mysql is available as a separate package via yum or apt.
Re your comment:
Okay, here's an example of a registry:
class registry {
protected static $items = array();
public static get($key) {
return isset(self::$items[$key])?
self::$items[$key] : null;
}
public static set($key, $object) {
self::$items[$key] = $object;
}
}
In your controller initial code, you'd create a database object and store it in the registry:
$projectConfiguration = new projectConfiguration();
$dbconnect = $projectConfiguration->connect(
$projectConfiguration->databaseHost,
$projectConfiguration->databaseName,
$projectConfiguration->databaseUser,
$projectConfiguration->databasePass);
registry::set('db', $dbconnect);
Then in your model class methods (or anywhere you need the database), get the db object from the registry and use it:
public function loadCustomersList($sAdditionalWhere = false)
{
$sQuery = "SELECT * FROM customers WHERE 1 ";
if ($sAdditionalWhere) {
$sQuery .= "AND " . $sAdditionalWhere . " ";
}
$sQuery .= "ORDER BY company";
$db = registry::get('db');
$stmt = $db->query($sQuery);
$aCustomers = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $aCustomers;
}

How to create user on hMailServer programatically?

We are writing a specialized PHP e-mail client and would like to give administrators of this client the ability to create user accounts on hMailServer.
I tried out imap_createmailbox(...) but it just creates a directory in the user's folder structure but does not "create a mailbox for a new user" as we want.
Is there some kind of interface that hMailServer has so that I can enable our PHP e-mail client to create hMailServer accounts via code?
Yes there two interfaces to create accounts in hmailserver.
One, via database, you can choose account and password hash type (0,1,2,3) and signature and other classic informations. I don't recommend this method for synchronisation reason, hmail-server take a caching time to consider the database update.
Two, which i recommend is to use API COM, its offers all possible methods in all cummon languages.
You have to enable D-COM in your windows server.
The API guide
hmailserver version: hMailServer 5.6.4 - Build 2283
complete solution of create new email account by hmailserver in c#
if you have configured hmailserver successfully, so then you can use the following steps to create new account by hmailserver in c#
hmailserver connection
private Domain HMailServerConnection() {
var objGlobal = new ApplicationClass();
objGlobal.Authenticate(ConfigurationManager.AppSettings["HMailUsername"], ConfigurationManager.AppSettings["HMailPassword"]);
return objGlobal.Domains.get_ItemByName(ConfigurationManager.AppSettings["hMailDomain"]);
}
function to create new email account
public string AddNewAccount(string email,string password)
{
try
{
Domain domain = HMailServerConnection();
Accounts accounts = domain.Accounts;
Account mailbox = accounts.Add();
mailbox.Address = email;
mailbox.Password = password;
mailbox.Save();
return "success";
}
catch(Exception ex)
{
return "error";
}
}
App settings in App.config or web.config
<appSettings>
<add key="hMailDomain" value="domainname"/>
<add key="HMailUsername" value="Username"/>
<add key="HMailPassword" value="password"/>
</appSettings>
see the link
its working i tested it.
<?php
header('Content-Type: text/html; charset=utf-8');
$obBaseApp = new COM("hMailServer.Application", NULL, CP_UTF8);
$obBaseApp->Connect();
$hmail_config['rooturl'] = "http://localhost/";
$obAccount = $obBaseApp->Authenticate("Administrator", "hMailserver Administrator
password");
if (!isset($obAccount)) {
echo "<b>Not authenticated or Administrator's password wrong</b>";
} else {
try {
echo "<b>Logon COM [OK], now we can add accounts</b>";
$obDomain = $obBaseApp->Domains->ItemByDBID(1);
$obAccount = $obDomain->Accounts->ItemByDBID(1); // account id
$domainname = $obDomain->Name;
$obAccounts = $obDomain->Accounts();
$obAccount = $obDomain->Accounts->Add();
$newalias = "powerranger";
$firstname = "Arnold";
$lastname = "Schwarzenegger";
$my_domainname ="#mydomain.com";
$obAccount->PersonFirstName = $firstname;
$obAccount->PersonLastName = $lastname;
$obAccount->MaxSize = 102; // 102 MB set inbox space
$obAccount->Address = $newalias .$my_domainname;
$obAccount->Password = "secret"; // provide this in Thunderbird/Outlook ect.
$obAccount->Active = true; // set account to active
$obAccount->Save(); // save, finish.
/* If we reaching this point, everything works as expected */
echo "<br/><h3> Account was successfully created, now you can login with".
"an POP3 or IMAP-Client </h3>";
}
/* OK, if something went wrong, give us the exact error details */
catch(Exception $e) {
echo "<h4>COM-ERROR: <br />".$e->getMessage()."</h4><br />";
}
}