Gets Data From Mssql to Mysql Database Using PDO - mysql

I'm getting data from my accounting program in Windows Platform to my PHP Script. I'm transferring data from mssql to mysql. I decided to use PDO. I have a problem with transition. How can i supply two connection simultaneously ?
Here is my own PDO Class.
class Database {
protected $_host = "***********";
protected $_engine = "mysql";
protected $_dbuser = "***********";
protected $_dbpassword = "***********";
protected $_db = "***********";
protected $_sql;
protected $pdo;
/* #desc This Function is Setting SQL Connection
* #return SQL Connection
*
*/
protected function getPdo()
{
if ($this->pdo === NULL) {
try {
$dsn = $this->_engine.':dbname='.$this->_db.';host='.$this->_host.';charset=utf8';
$this->pdo = new PDO($dsn, $this->_dbuser, $this->_dbpassword, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
));
//$this->pdo->setAttribute();
//$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
return $this->pdo;
}
/* #desc This Function is Preparing Sql Statement For Query
* #return array Returns PDO Object Query
*
*/
public function query($sql)
{
return $this->_sql = $this->getPdo()->prepare($sql);
}
/* #desc This Function is for Binding Values into SQL Statements
* #return Binded SQL Statements
*
*/
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->_sql->bindValue($param, $value, $type);
}
/* #desc This Function Execute Query
* #return SQL Execution
*
*/
public function execute($values = NULL){
return (!isset($values)) ? $this->_sql->execute() : $this->_sql->execute($values);
}
/* #desc This Function Execute Query and Fetch Multiple Result
* #return array Returns Array of Table Rows. Array is multidimensional
*
*/
public function queryResults(){
$this->execute();
return $this->_sql->fetchAll(PDO::FETCH_ASSOC);
}
/* #desc This Function Execute Query and Fetch Only Single Result
* #return array Returns Array of Table Row. Array is not multidimensional.
*
*/
public function queryResult(){
$this->execute();
return $this->_sql->fetch(PDO::FETCH_ASSOC);
}
public function queryColumn($index = NULL){
$index = (isset($index)) ? intval($index) : 0;
$this->execute();
return $this->_sql->fetchAll(PDO::FETCH_COLUMN,$index);
// $this->execute();
// return $this->_sql->fetchAll(PDO::FETCH_COLUMN);
}
/* #desc This Function Returns Effected Row Count during Update, Delete and Insert
* #return int Returns Effected Row Count
*
*/
public function effected(){
return $this->_sql->rowCount();
}
/* #desc This Function Returns Effected Row Count during Update, Delete and Insert
* #return int Returns Effected Row Count
*
*/
public function rowCount(){
return count($this->queryResults());
}
public function lastID(){
return $this->_sql->lastInsertId();
}

You need to create 2 instances of PDO class - one for MSSQL and one for MySQL.

Related

Yii2 relation between three table using ActiveRecord

I have three tables in mysql database like this picture below :
Now, with gii, I create those model like this :
For table BuktiPenerimaan
class BuktiPenerimaan extends \yii\db\ActiveRecord{
/**
* #return \yii\db\ActiveQuery
*/
public function getInvoiceReports()
{
return $this->hasMany(InvoiceReport::className(), ['bukti_penerimaan_id' => 'id']);
}
}
And InvoiceReports:
class InvoiceReport extends \yii\db\ActiveRecord{
/**
* #return \yii\db\ActiveQuery
*/
public function getInvoiceReportDetails()
{
return $this->hasMany(InvoiceReportDetail::className(), ['invoice_id' => 'id']);
}
My question is, how to access all record in table invoice_report_detail if I created an object that came from BuktiPenerimaan.
I use like this :
$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice = $model->invoiceReports; //exist
$dataInvoiceDetail = $model->invoiceReports->invoiceReportDetails // failed, always null.
Please advixe
$dataInvoice = $model->invoiceReports; is Array of InvoiceReport object.
You need to loop over each InvoiceReport to get related InvoiceReportDetail.
$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice = $model->invoiceReports; //exist , but array of objects
$dataInvoiceDetail = [];
foreach($dataInvoice as $dInvoice):
$dataInvoiceDetail[] = array_merge($dataInvoiceDetail,$dInvoice->invoiceReportDetails );
endforeach;
// $dataInvoiceDetail contains all invoice_report_detail

Can't initialise \AsyncMysqlQueryResult object

I want simply initialise the \AsyncMysqlConnectionResult $connec; object
<?hh
namespace Connection;
require_once("ini.php");
/**
* Class for execute and fetch query
*/
class MyQuery
{
/**
* if connection isn't valid recreate pool
*/
private ?\AsyncMysqlConnectionPool $pool;
/**
* \AsyncMysqlConnection object, store $conn
*/
private \AsyncMysqlConnection $connec;
/**
* \AsyncMysqlQueryReturn object, store return query
*/
private \AsyncMysqlQueryResult $result;
/**
* check if $conn object isValid(), if not release
* connection
*/
public function __construct(\AsyncMysqlConnection $conn)
{
if ($conn->isValid() == false)
{
$this->pool = new MyPool();
$this->connec = $this->pool->connect();
}
else
$this->connec = $conn;
$this->result = object;
}
/**
* escape query and execute it
*/
public async function query(string $query): Awaitable<\AsyncMysqlQueryResult>
{
$query = $this->connec->escapeString($query);
echo "Query escape\n";
/* Try to execute the query, if fail display error */
try
{
$this->result = await $this->connec->query($query);
//log request with ini
}
catch (Exception $e)
{
echo "Couldn't execute the request, error with message :<br>";
var_dump($e->getMessage());
//log request with fail
}
echo "Query done succefully\n";
return $this->result;
}
/**
* escape Map array and execute the request
*/
public async function queryf(HH\FormatString<HH\SQLFormatter> $query, array<string> $params): Awaitable<\AsyncMysqlQueryResult>
{
$i = 0;
while ($params[$i++])
$params[$i] = $this->connec->escapeString($params[$i]);
/* Try to execute the query, if fail display error */
try
{
$result = await $this->connec->queryf($query, implode(', ', $params));
//log request with ini
}
catch (Exception $e)
{
echo "Couldn't execute the request, error with message :<br>";
var_dump($e->getMessage());
//log request with fail
}
echo "Query done succefully\n";
return $this->result;
}
}
newtype AsyncMysqlConnectionResult = object;
newtype FormatString<T> = string;
async function simple_query(\AsyncMysqlConnection $conn): Awaitable<Vector>
{
$connec = new MyQuery($conn);
$ret = await $connec->query('SELECT * FROM users');
return $ret->vectorRows();
}
function run_query(\AsyncMysqlConnection $conn): void
{
$r = \HH\Asio\join(simple_query($conn));
var_dump($r);
}
run_query($conn);
For having this object I use https://docs.hhvm.com/hack/reference/class/AsyncMysqlConnectionPool/connect/ class and connect() method to have this : \AsyncMysqlConnectionResult $connec object.
I can't find a way to initialise this variable type, I've try to
create newtype AsyncMysqlConnectionResult = object but the filechecker return me :
Unbound name: Connection\object (an object type)
Instead of storing the result on the class, why doesn't your query methods simply return the result. For example:
public async function query(string $query): Awaitable<\AsyncMysqlQueryResult>
{
$query = $this->connec->escapeString($query);
return await $this->connec->query($query);
}
or if you really want the result to be stored on the class, make it nullable. This will allow you to not set it in the constructor, and only set it after a query has been made.
private ?\AsyncMysqlQueryResult $result;
This is the only way a find to rewrite queryf() method.
public async function queryf($query, array<int, string> $params): Awaitable<\AsyncMysqlQueryResult>
{
$result = "";
/* Try to execute the query, if fail display error */
try // execute query
{
$result = await $this->connec->queryf($query, implode(', ', $params));
// If log_request === TRUE log request with ini
if ($this->log_request === TRUE)
await $this->logRequest($query, 0);
}
catch (Exception $e) // If the query can't be execute display error
{
echo "\nCouldn't execute the request, error with message :<br>\n";
var_dump($e->getMessage());
//log request with fail
await $this->logRequest((string)$query, -1);
}
return (object)$result;
}
I have no error and everything work fine.
If someone have a better and solution I'm here.

Error: Call to a member function setStats() on a non-object

I am trying to update a single data in my entity class, but the doctrine is always returning this error
Error: Call to a member function setStats() on a non-object**
$em = $this->getDoctrine()->getManager();
$result = $em->getRepository('MyBundle:UserStats')->findBy(array('ownerPhone' => 1002));
if( isset($result) && $result !== false ) {
echo $result->setConditionState(0); // ConditionState is a boolean condition which i want to set it to false
}
$em->flush();
My entity class for conditionState---
/**
* Set conditionState
*
* #param boolean $conditionState
*
* #return UserStats
*/
public function setConditionState($conditionState)
{
$this->conditionState = $conditionState;
return $this;
}
/**
* Get conditionState
*
* #return boolean
*/
public function getConditionState()
{
return $this->conditionState;
}
Do anyone have an idea where I am making the mistake?
findBy method returns an array. Use findOneBy instead.

Update discriminator column Doctrine2 with Symfony2

I have an entity called User which has inheritance for Student, Professional and Business.
When a user is registered, is only a User but they must update their profile and choose which kind of user is, I have a form which handles this, a controller which gets the form data, but I can't update the discriminator field type with $userEntity->setType()
This is my mapping stuff
class User
{
const TYPE_BASIC = "Basico";
const TYPE_STUDENT = "Estudiante";
const TYPE_PROFESSIONAL = "Profesional";
const TYPE_BUSINESS = "Empresa";
protected $type = self::TYPE_BASIC;
public function getType()
{
return self::TYPE_BASIC;
}
public function setType($type)
{
$this->type = $type;
}
class Student extends User
{
protected $type = self::TYPE_STUDENT;
And then Professional and Business just like Student (changing const)
<entity name="User" table="user_base" inheritance-type="JOINED">
<discriminator-column name="type" type="string"/>
<discriminator-map>
<discriminator-mapping value="Basico" class="User"/>
<discriminator-mapping value="Estudiante" class="Student"/>
<discriminator-mapping value="Profesional" class="Professional"/>
<discriminator-mapping value="Empresa" class="Business"/>
</discriminator-map>
the child tables are named user_xxx where xxx = Student/Professional/Business
And this is my controller
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$data = $form->all();
$type = $data['type']->getData();
$email = $data['email']->getData();
$profile = $data['profile']->all();
$name = $profile['name']->getData();
$lastName = $profile['lastName']->getData();
$birth = $profile['birth']->getData();
$profileEntity = new Profile();
$profileEntity->setBirth($birth);
$profileEntity->setName($name);
$profileEntity->setLastName($lastName);
$profileEntity->setUser($user);
$em->persist($profileEntity);
ladybug_dump($type);
$userEntity = $em->getRepository('User')->find($user);
$userEntity->setProfile($profileEntity);
$userEntity->setType($type);
if($user->getEmail() != $email)
$userEntity->setEmail($email);
$em->persist($userEntity);
$em->flush();
}
Everything is persisted but type field, which remains it's original data. I know when I change discriminator column I need to create a new row inside it's child element, but first I want to know how to change the discriminator column.
it is possible if you use this custom bit of code in the Form of a Trait which you can use inside a Repository.
The Trait:
namespace App\Doctrine\Repository;
use App\Exception\InvalidDiscriminatorClassException;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
/**
* Discriminator Trait
*/
trait DiscriminatorTrait
{
/**
* #return ClassMetadata
*/
abstract public function getClassMetadata();
/**
* #return EntityManager
*/
abstract public function getEntityManager();
/**
* Update Discriminator Column
*
* #param integer $id
* #param string $class
* #return boolean
* #throws InvalidDiscriminatorClassException
*/
private function updateDiscriminatorColumn($id, $class)
{
/* #var ClassMetadata $classMetadata */
$classMetadata = $this->getClassMetadata();
if (!in_array($class, $classMetadata->discriminatorMap)) {
throw new InvalidDiscriminatorClassException($class);
}
$identifier = $classMetadata->fieldMappings[$classMetadata->identifier[0]]["columnName"];
$column = $classMetadata->discriminatorColumn["fieldName"];
$value = array_search($class, $classMetadata->discriminatorMap);
/* #var Connection $connection */
$connection = $this->getEntityManager()->getConnection();
try {
$connection->update(
$classMetadata->table["name"],
[$column => $value],
[$identifier => $id]
);
}
catch (DBALException $e) {
return false;
}
return true;
}
}
According to the Doctrine documentation on Inheritance mapping, it is not possible to either get or set the type. You may wish take advantage of PUGXMultiUserBundle, which readily handles the mapping. This bundle also makes it possible for your users to register with the appropriate profile.

How to get proper collection in magento grid?

I have a custom grid tab in magento category with separate table to store data.
This is table with data:
When I filter by 'Yes' under first column. It does return associated rows with ID (284 & 285) but when I select 'No', it returns IDs (281-283), it's supposed to return 283 only which is the only stream not configured already.
And when I select ANY, it returns all associated and not associated with duplicate streams to select.
What I need is show each streams once only and work with first column filter.
I think I have incorrect joins with another table which holds all the streams (groups).
This is another table
protected function _prepareCollection()
{
if ($this->getCategory()->getId()) {
$this->setDefaultFilter(array('selected_tcategoryacl'=>1));
}
/* #var $collection Technooze_Tcategoryacl_Model_Mysql4_Tcategoryacl_Collection */
$collection = Mage::getModel('tcategoryacl/tcategoryacl')->getCollection();
$collection->getSelect()->joinRight('school_group', 'school_group_id=group_id');
$collection->addFieldToFilter('school_group_status', 1);
//$collection->getSelect()->group('school_group.school_group_id');
$collection = $this->insertFakeIdsToCollection($collection);
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _addColumnFilterToCollection($column)
{
$tcategoryaclIds = $this->_getSelectedTcategoryacl();
switch($column->getId()){
case 'selected_tcategoryacl':
if (empty($tcategoryaclIds)) {
$tcategoryaclIds = 0;
}
//$this->getCollection()->addFieldToFilter('category_id', $this->getCategory()->getId());
if ($column->getFilter()->getValue()) {
$this->removeRightJoin();
$this->getCollection()->clear()->addFieldToFilter('tcategoryacl_id', array('in'=>$tcategoryaclIds));
} elseif(!empty($tcategoryaclIds)) {
$this->getCollection()->clear();
$this->getCollection()->addFieldToFilter('tcategoryacl_id', array('nin'=>$tcategoryaclIds));
//$this->getCollection()->addFieldToFilter('school_group.school_group_id', array('nin'=>$this->_getSelectedSchoolGroupIds()));
$this->setCollection($this->insertFakeIdsToCollection($this->getCollection()));
}
break;
/*case 'allow_from':
case 'allow_to':
$this->getCollection()->addFieldToFilter($column->getId(), array('like'=>$column->getFilter()->getValue()));
break;*/
default: parent::_addColumnFilterToCollection($column);
}
return $this;
}
private function removeRightJoin(){
$this->getCollection()->clear()->getSelect()->reset('RIGHT JOIN');
}
protected function insertFakeIdsToCollection($collection)
{
$i = 0;
foreach($collection as $v){
// lets have fake ids for empty tcategoryacl_id, so checkbox can be selected
if(!$v->getData('tcategoryacl_id')){
$v->setData('tcategoryacl_id', '0' . $this->getCategory()->getId() . $i++);
$v->setId($v->getData('tcategoryacl_id'));
}
// lets auto select different groups in each row
if(!$v->getData('group_id')){
$v->setData('group_id', $v->getData('school_group_id'));
}
}
return $collection;
}
/**
* #return array
*/
protected function _getSelectedSchoolGroupIds()
{
$selected_tcategoryacl = array();
$category = $this->getCategory();
$collection = Mage::getModel('tcategoryacl/tcategoryacl')->getCollection();
$collection->addFieldToFilter('category_id', $category->getId());
foreach($collection as $v)
{
$selected_tcategoryacl[] = $v->getGroupId();
}
return $selected_tcategoryacl;
}
/**
* #return array
*/
protected function _getSelectedTcategoryacl()
{
$selected_tcategoryacl = array();
$category = $this->getCategory();
$collection = Mage::getModel('tcategoryacl/tcategoryacl')->getCollection();
$collection->addFieldToFilter('category_id', $category->getId());
foreach($collection as $v)
{
$selected_tcategoryacl[] = $v->getTcategoryaclId();
}
return $selected_tcategoryacl;
}
Update
added code on repo - https://github.com/dbashyal/Tcategory_ACL/blob/master/app/code/community/Technooze/Tcategoryacl/Block/Adminhtml/Catalog/Category/Tab/Tcategoryacl.php