Creating database connection in module.php file zf2 - mysql

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();
}

Related

How to send values from variables and arrays from controller to the model

I want to change the script below.
where the script below is using the query "like" and "array" to find data.
I want to send these 2 variables to the model and send them back to the controller for processing.
My Controller:
if($lewati == 0){
$sql = "SELECT * FROM tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
// $jml_id_filter = count($id_filter);
// $id_filter[$jml_id_filter] = $row['id'];
$filter_ok++;
}
}
My Model:
function tampil_data_spesifik($kata,$i)
{
return $this->db->query('select tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'');
}
From codeigniter's official documentation, it's a better practice to do all db queries in your model and you don't need to manually type any database connection scripts.
Your controller handles incoming requests, often times from routes. For codeigniter version 3, your controller method should be
public function method(){
$lewati = 0;
$array_data = array(3, 5, 9, 4);
$another_thing = $array_data[1] //get first item
if($lewati === 0){
$result = $this->model_name->method_in_model($lewati, $another_thing); //your model will accept two params
}
echo json_encode($result);
}
Then you can update your model to something like this
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_name extends CI_Model {
public function method_in_model($lewati, $another_thing){
$this->db->where('column_name', $lewati);
$this->db->like('spesifikasi_foto LIKE', $another_thing);
$result = $this->db->get('YOUR_TABLE_NAME');
if(empty($result->row_array())){
return true;
}else{
return false;
}
}
}
Let me know if it solved your problem already
in your controller method
$this->load->model('name_of_the_model_class');
$data = $this->name_of_the_model->function_name($variable1,$variable2);
in your model class method
//do whatever your process and return the output
return $output;

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.

JSON response assign to $var then save to db

I'm using Dropzone.js to upload multiple files in Laravel, which works fine uploads to my uploads folder but now I want the save the json object to the db.
Currently I have:
$file = Input::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/userfiles', $fileName);
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));
So now how would I store this in my users table in the uploads column?
Depends what you want to store...
As I understand it, you want to associate uploads with a user? If you just want to store the filename, which may suffice, maybe do this:
// models/User.php
class User extends Eloquent {
// ...
public function setFilesAttribute(array $files)
{
$this->attributes['files'] = json_encode(array_values($files));
}
public function getFilesAttribute($files)
{
return $files ? json_decode($files, true) : array();
}
}
// Your script
$file = Input::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/userfiles', $fileName);
$user = User::find(1); // Find your user
$user->files[] = $fileName; // This may work, not too sure if it will being a magic method and all
$user->files = array_merge($user->files, [$fileName]); // If not, this will work
$user->save();
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));
Something like this?
Of course, you could get more complex and create a model which represents a "file" entity and assign multiple files to a usre:
// models/File.php, should have `id`, `user_id`, `file_name`, `created_at`, `updated_at`
class File extends Eloquent {
protected $table = 'files';
protected $fillable = ['file_name']; // Add more attributes
public function user()
{
return $this->belongsTo('User');
}
}
// models/User.php
class User extends Eloquent {
// ...
public function files()
{
return $this->hasMany('File');
}
}
// Your script
$file = Input::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/userfiles', $fileName);
$user = User::find(1); // Find your user
$file = new File([
'file_name' => $fileName,
// Any other attributes you want, just make sure they're fillable in the file model
]);
$file->save();
$user->files()->attach($file);
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));

php mySQL Reliable way to check if a row matches a object class

I'm looking for a reliable way to check to see if a database entry matches an equivalent object class in php.
My current method is unreliable, I was hoping someone could supply a better solution.
My current solution seems to work most of the time, but out of around 600 entries, Ill randomly return about 5 entry's that are false positives.
Here is a simplified object class Im using
class MemberData
{
public $AccountID;
public $AccountName;
public $Website;
}
I then use reflection to loop through each property in the class and build my query string in the form of :
SELECT 1 WHERE `Property1` = value1 AND `Property2` = value2 AND `Property3` = value3
However like i mentioned, my code only works most of the time, and I cant pin down a common link on why Im getting false positives. It appears random.
Below is my full function.
//Pass in a member class and see if there is a matching database entry
function SqlDoRowValuesMatch($memberData)
{
//declare global vars into this scope
global $host, $user, $password, $dbname, $tableName;
//initiate the connection using mysqli
$databaseConnection = new mysqli($host, $user, $password, $dbname);
if($databaseConnection->connect_errno > 0)
{
die('Unable to connect to database [' . $databaseConnection->connect_error . ']');
}
//Get all the properties in the MemberData Class
//Using Reflection
$reflect = new ReflectionClass($memberData);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
//Build the query string
$sql = "SELECT 1 FROM `".$tableName."` WHERE ";
foreach($props as $prop)
{
if(!is_null($prop->getValue($memberData)))
{
$sql = $sql.$prop->getName()."=".addSingleQuotes(addslashes($prop->getValue($memberData)))." AND ";
}
}
//Cut Trailing operator
$sql = rtrim($sql, " AND ");
if(!$result = $databaseConnection->query($sql))
{
die('There was an error creating [' . $databaseConnection->error . ']');
}
$databaseConnection->close();
//Check for a value of 1 to indicate that a match was found
$rowsMatch = 0;
while($row = $result->fetch_assoc())
{
foreach($row as $key => $value)
{
if($value == 1)
{
$rowsMatch = 1;
break;
}
}
}
return $rowsMatch; //0 = false, 1 = true
}

Zend database connection failure

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