Zend database connection failure - mysql

Ok I am having real difficulty solving this. I'm trying to connect to a mysql database from a zend application and i receive the following error:
Message: No database adapter present
I have checked and double checked the connection credentials and they should be fine. The code should be fine too as it works ok in the development environment. If I deliberately change the password to be incorrect in the development environment, I get exactly the same error, which leads me to believe that maybe this is the case, despite my checking!
Any thoughts would be very welcome. If there's nothing obviously wrong here then maybe I need to look at the server/db/php settings?
Thanks!
Bootstrap code:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initPlaceholders(){
Zend_Session::start();
$this->bootstrap('View');
$view = $this->getResource('View');
$view->doctype('XHTML1_STRICT');
// Set the initial stylesheet:
$view->headLink()->appendStylesheet('/css/global.css');
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('Pog_');
Zend_Controller_Action_HelperBroker::addPath(
APPLICATION_PATH . '/controllers/helpers',
'Application_Controller_Action_Helper_');
}
}
Config file:
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.view[] =
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.view.helperPath.View_Helper = APPLICATION_PATH "/views/helpers"
database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user
database.params.password = password
database.params.dbname = test
DB connection helper:
/**
* Constructor: initialize plugin loader
*
* #return void
*/
public function __construct()
{
try{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$dbAdapter = Zend_Db::factory($config->database);
$dbAdapter->getConnection();
$this->connection = $dbAdapter;
} catch (Zend_Db_Adapter_Exception $e) {
echo 'perhaps a failed login credential, or perhaps the RDBMS is not running';
} catch (Zend_Exception $e) {
echo 'perhaps factory() failed to load the specified Adapter class';
}
}
public function getDbConnection(){
return $this->connection;
}
}
Index:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
->run();

Define your database as a resource
resources.db.adapter = pdo_mysql
resources.db.params.host = localhost
resources.db.params.username = user
resources.db.params.password = password
resources.db.params.dbname = test
In your main files you then need to do nothing but initiate a query without having to worry about assigning the database fvrom your config - its done in the inside, the DB resource is always chosen as the default adapter for your database transactions

Related

How to process incoming JSON data from connected IoT device

I need some support with a personal project Im working on. I have a connected device which sends JSON data at a defined interval (every 1 min / 5 min/ 15 mins etc) to a specific IP address on port 8080.
The JSON that is sent is in following format:
{
"MeterSN": “1234”,
"Status": ###,
“Variable1”: “###”,
"Variable2”: “###”,
"Variable3”: ###
}
I have started building a PHP Rest API to process this data but am somehow not able to save the to mySQL.
Here is what I have so far:
meterdata.php
class MeterDataInput{
private $conn;
private $table_name = "meterdata";
public $MeterSN;
public $StatusA;
public $Variable1;
public $Variable2;
public $Variable3;
public function __construct($db){
$this->conn = $db;
}
}
function createMeterRecord(){
$query = "INSERT INTO
" . $this->table_name . "
SET
MeterSN=:MeterSN, Status=:Status, Variable1=:Variable1, Variable2=:Variable2, Variable3=:Variable3";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->MeterSN=htmlspecialchars(strip_tags($this->MeterSN));
$this->Status=htmlspecialchars(strip_tags($this->Status));
$this->Variable1=htmlspecialchars(strip_tags($this->Variable1));
$this->Variable2=htmlspecialchars(strip_tags($this->Variable2));
$this->Variable3=htmlspecialchars(strip_tags($this->Variable3));
// bind values
$stmt->bindParam(":MeterSN", $this->MeterSN);
$stmt->bindParam(":Status", $this->Status);
$stmt->bindParam(":Variable1", $this->Variable1);
$stmt->bindParam(":Variable2", $this->Variable2);
$stmt->bindParam(":Variable3", $this->Variable3);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
index.php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once 'config/db.php';
// instantiate MeterData object
include_once 'objects/meterdata.php';
$database = new Database();
$db = $database->getConnection();
$meterdata = new MeterDataInput($db);
// get posted data
$data = json_decode(file_get_contents("php://input"));
// make sure data is not empty
if(!empty($data->MeterSN)){
// set product property values
$meterdata->MeterSN = $data->MeterSN;
$meterdata->Status = $data->Status;
$meterdata->Variable1 = $data->Variable1;
$meterdata->Variable2 = $data->Variable2;
$meterdata->Variable3 = $data->Variable3;
// create the meter data entry
if($meterdata->createMeterRecord()){
// set response code - 201 created
http_response_code(201);
// update the status
echo json_encode(array("message" => "Data record was added"));
}
// if unable to create the record
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to add record."));
}
}
// data is incomplete
else{
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo json_encode(array("message" => "Unable to create data record. Data is incomplete."));
}
Obviously i also have config.php and db.php
I am not sure where i am going wrong, however I am not able to see the records popupate within mySQL.

How to Add a shapefile data to postgis(postgres) using c#

am trying to add shapefile data to postgis using c#
string path = browse_path.Text;
ProcessStartInfo startInfo = new ProcessStartInfo("CMD.exe");
Process p = new Process();
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
p = Process.Start(startInfo);
string chgdir = #"chdir " + #"C:\Program Files\PostgreSQL\9.4\bin\";
p.StandardInput.WriteLine(chgdir);
string pass = #"set PGPASSWORD=postgres";
p.StandardInput.WriteLine(pass);
string cmd = #"shp2pgsql -I -s 4326 " + path + " public.states | psql -U postgres -d postgres";
p.StandardInput.WriteLine(cmd);
p.WaitForExit();
p.Close();`
and for waiting almost 7-8 mins its not working. my shp file is 160 kb only.. but the command is working fine if i run it in the cmd rather then using code..
This is a function I wrote to import shapefiles to PG. It uses Nuget packages CliWrap and Npgsql and I just copied shp2pgsql and its dependencies to a project folder 'Tools' so it can be run on a machine that doesn't have PostgreSQL installed. Its a bit messy and you might need to add error handling but it worked for my needs.
public async static Task<bool> OutputSHPtoPSGLAsync(string shpfile, string host, string user, string pwd, string db, string schema = "public", bool dropIfExists = true, string table = "[SHPNAME]")
{
FileInfo shp = new FileInfo(shpfile);
if (!shp.Exists) return false;
if (table == "[SHPNAME]") table = Path.GetFileNameWithoutExtension(shpfile).ToLower();
string args = string.Format("{0} {1}.{2}", shpfile, schema, table);
Command cli = Cli.Wrap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"tools\shp2pgsql.exe")).WithArguments(args);
ExecutionResult eo = await cli.ExecuteAsync();
string sql = eo.StandardOutput;
if (dropIfExists) sql = sql.Replace("CREATE TABLE", string.Format("DROP TABLE IF EXISTS \"{0}\".\"{1}\";\r\nCREATE TABLE", schema, table));
string constring = string.Format("Host={0};Username={1};Password={2};Database={3}", host, user, pwd, db);
using (NpgsqlConnection connection = new NpgsqlConnection(constring))
{
connection.Open();
new NpgsqlCommand(sql, connection).ExecuteNonQuery();
}
return true;
}
I was looking at NetTopologySuite which has type definitions compatible with Npgsql and PostGIS but its all still pre-release and couldn't be bothered working it out.

LDAP with Guard Authentication System in Symfony 3

What I'm pretending to do is to include the LDAP for internal users in a Guard Authentication System configured by ddbb.
I already have build my Guard Authentication System and works really nice thanks to https://knpuniversity.com/screencast/symfony-security.
But I need also to try to log in previously via LDAP mode. More precisely, the functionality must be like this:
The user try to log in on the Guard System Authentication configured with a database from MySQL and:
1- Check if exist the user in the table User from MySQL. If exist, we go to step 2. If not exist return false to the authentication with the error message.
2-Check if the user exist in the LDAP mode. If exist go to the step 3. If not exist go to the step 4.
3-Try to log in via LDAP with the username and password. If the authentication is ok, it's logged in. If can't match the password via LDAP, return false to the authentication with the error message.
4-After checking the LDAP option, we will just try to log in via Guard Authentication System. If the authentication it's ok, the user is logged in. If can't match the password via Guard with the MySQL users table, return false to the authentication with the error message.
In the LoginFormAuthenticator file I finally could manage this behavior I want as shows the next code.
<?php
namespace AppBundle\Security;
use ...
use Zend\Ldap\Ldap;
use Zend\Ldap\Exception\LdapException;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator
{
use TargetPathTrait;
private $em;
private $router;
private $passwordEncoder;
private $csrfTokenManager;
public function __construct(...
}
public function getCredentials(Request $request)
{
...
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
$ldapPassword = $credentials['password'];
$ldaphost = 'ldap.example.com'; // your ldap servers
$baseDn = 'dc=example,dc=es';
$options = [
'host' => $ldaphost,
'username' => $username,
'password' => $ldapPassword,
'bindRequiresDn' => false,
'accountDomainName' => 'example.es',
'baseDn' => $baseDn,
];
$userInterface = $this->em->getRepository('AppBundle:User')
->findOneBy(['email' => $username]);
$ldap = new Ldap($options);
try {
$ldap->bind();
$userInterface->setIsAuthenticationLDAP(true);
} catch (LdapException $zle){
$userInterface->setIsAuthenticationLDAP(false);
}
return $userInterface;
}
public function checkCredentials($credentials, UserInterface $user)
{
$password = $credentials['password'];
if($user->isAuthenticationLDAP()){
$user->setLoginAttempts(0);
$this->em->persist($user);
$this->em->flush();
return true;
} else {
if($this->passwordEncoder->isPasswordValid($user, $password)) {
$user->setLoginAttempts(0);
$this->em->persist($user);
$this->em->flush();
return true;
} else {
if($user->getLoginAttempts() == '0') $user->setFirstLoginAttempt(new \DateTime('now'));
$user->setLoginAttempts($user->getLoginAttempts() + 1);
if($user->getLoginAttempts() >= 5) {
$user->setLockedDateTime(new \DateTime('now'));
$user->setLoginAttempts(0);
}
$this->em->persist($user);
$this->em->flush();
}
}
return false;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
....
}
protected function getLoginUrl()
{
return $this->router->generate('fos_user_security_login');
}
}
I hope anyone can enjoy this answer.

Creating database connection in module.php file zf2

I have a onBootstrap method in module.php file. I want to use this function to also store user log details into the mysql db. Not able to use persist and flush methods. Any thoughts, how to create a db connection?
Thanks in advance
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach('finish', array($this, 'outputCompress'), 100);
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$app = $e->getApplication();
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
$routeMatch = $e->getRouteMatch();
// $name = $auth->getresolvedIdentity('id');
//echo "<pre>"; var_dump($auth); var_dump($routeMatch);
if($routeMatch && $auth){
$Userlog = new Userlog();
$Userlog->setUserid(10);
$Userlog->setUsername('abc');
$Userlog->setUrl_loaded('xyz');
$this->getObjectManager()->persist($Userlog);
$this->getObjectManager()->flush();
}

Creating and filling database from a Controller (Symfony 2, Doctrine)

I am trying to create an installation Bundle for my Symfony 2.2.3 application.
Therefore I want to drop/create a database (mysql) and then create the schema via Controller Actions.
My Code:
$kernel = $this->get('kernel');
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->setAutoExit(false);
// drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// create new database
$options = array('command' => 'doctrine:database:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
// check if database:create was successful, then create schema
if($result == 0) {
$options = array('command' => 'doctrine:schema:create');
$result = $application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
}
database:drop and database:create work fine (both commands return 0), but creating the schema then fails.
However, when I comment the first 2 commands out so that only doctrine:schema:create will be executed (if clause removed, of course) and reload the page without changing anything else the database schema will be created properly.
Can anyone tell me what the problem is?
This code works (Symfony 2.7)
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
/**
* #Route("/resetDB", name="adminResetDB")
*/
public function resetDBAction()
{
$application = new Application($this->get('kernel'));
$application->setAutoExit(false);
// Drop old database
$options = array('command' => 'doctrine:database:drop', '--force' => true);
$application->run(new ArrayInput($options));
// Make sure we close the original connection because it lost the reference to the database
$this->getDoctrine()->getManager()->getConnection()->close();
// Create new database
$options = array('command' => 'doctrine:database:create');
$application->run(new ArrayInput($options));
// Update schema
$options = array('command' => 'doctrine:schema:update','--force' => true);
$application->run(new ArrayInput($options));
// Loading Fixtures, --append option prevent confirmation message
$options = array('command' => 'doctrine:fixtures:load','--append' => true);
$application->run(new ArrayInput($options));
return $this->redirect($this->generateUrl('index'));
}