CodeIgniter connection db custom error - codeigniter

i have this code
$specific['hostname'] = "localhost";
$specific['username'] = "root";
$specific['password'] = "";
$specific['database'] = "ci_forsyria";
$specific['dbdriver'] = "mysql";
$specific['dbprefix'] = "";
$specific['pconnect'] = FALSE;
$specific['db_debug'] = FALSE;
$specific['cache_on'] = FALSE;
$specific['cachedir'] = "";
$specific['char_set'] = "utf8";
$specific['dbcollat'] = "utf8_general_ci";
$specific_db = $this->load->database($specific, TRUE);
i use this parameter "FALSE" to hide connection error !
$specific['db_debug'] = FALSE;
but how i can create custom error message if connection field
like
$connect = $this->db->connect;
if(!$connect)
{
// print error message ..
}

DB_Debug is designed to show Database error messages.
You have turned that functionality off with "$specific['db_debug'] = FALSE;"
So instead you need to turn it back on, and filter the $error message on the error_db.php file.
i.e. inside error_db.php
<? php if ($message === 'Database connection error')
{
echo $message;
}
else
{
echo "error - sorry";
} ?>
or something like that

Related

Interval in for e-mail sending

I made a system for sending e-mail but I need to put a interval in the send, today I only show the sending using an "echo" but if you have a progress it would be even better.
I don't know what the best way to do it when I tried to send with more than 3000 contacts was a timeout, but it remained sending.
I found function sleep, but I don't know if it would be suitable for the current code.
$locale = DB::table('email_contact')
->where('list_id','=',$list)
->get();
for($i = 0;$i < count($locale);$i++){
if($creditemail < count($locale)){
echo "you not credit!";
break;
}else{
$sender = $locale[$i];
$sending = $sender[$i]->email;
$name = $sender[$i]->name;
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = 'host';
$mail->SMTPAuth = true;
$mail->Username = 'user';
$mail->Password = 'pass';
$mail->SMTPSecure = false;
$mail->Port = 587;
//Recipients
$mail->setFrom('mail#my.com', 'Mail - My');
$mail->addAddress($sending, $name); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $text;
$mail->send();
$number = $i+1;
DB::table('users')
->where('id','=',Auth::id())
->decrement('email_credit', 1);
echo 'Sender: '.$number.'/'.count($locale)."<br>";
}catch (\Exception $e){
echo $e;
}
}
}
Use laravel mailer. You can easily add a delay there and also you can improve the code quality as well. Have a look at the documentation https://laravel.com/docs/7.x/mail
$when = now()->addMinutes(10);
Mail::to($request->user())
->cc($moreUsers)
->bcc($evenMoreUsers)
->later($when, new OrderShipped($order));

Strange error session get destroyed

I have a problem when I execute controller method it process controller code but destroy all session including user.
So after process thus controller and I try to open home page, there is no logged in account.
I'm sure no destroy session code, nor logout code in my controller. and I can say this is not about session expired.
I don't know what wrong is this about code, yii2 configuration or logic, but is someone have similar problem in past?
Hope you can guide me to solve this problem.
If you need more information, please let me know.
This not related to code maybe, but here is my controller code.
<?php
namespace frontend\controllers;
use Yii;
use common\models\TbCustomer;
use yii\web\Controller;
use common\models\Model;
use common\models\VwProdukAgent;
use common\models\TbCart;
use yii\helpers\VarDumper;
use common\models\VwProduk;
use yii\data\ActiveDataProvider;
use common\models\VwProdukCustomer;
use common\models\TbCustomerShipment;
use common\component\BeoHelper;
use common\models\TbProdukEkspedisi;
use common\models\TbKota;
use yii\helpers\Url;
/**
* CustomerController implements the CRUD actions for TbCustomer model.
*/
class Pengiriman1Controller extends Controller
{
public function beforeAction($action)
{
Yii::$app->timeZone = 'Asia/Jakarta';
if(Yii::$app->user->isGuest)
{
//$url = Url::to([['home'],'message'=>'Anda Harus Login Terlebih Dahulu']);
\Yii::$app->getSession()->setFlash('message', \Yii::t('app', 'Anda Harus Login Terlebih Dahulu'));
$this->goHome();
return FALSE;
}
//if ($action->id == 'my-method') {
$this->enableCsrfValidation = false;
// }
return parent::beforeAction($action);
}
public function actionIndex()
{
//get alamat customer
//$lsalamat = array();
if(!\Yii::$app->user->isGuest)
{
BeoHelper::refreshCart();
//cek cart kosong atau tidak
if(isset(\Yii::$app->session['produkcart']))
{
$lsproduk = \Yii::$app->session['produkcart'];
if (count($lsproduk)<1)
{
\Yii::$app->getSession()->setFlash('message',"silahkan berbelanja terlebih dahulu");
return $this->redirect(Url::to(['cart/index']));
}
}
$customer_id = Yii::$app->user->id;
$message = '';
$model = null;
if(\Yii::$app->request->post('opsi_alamat',null)!=null)
{
$opsi_pengiriman = \Yii::$app->request->post('opsi_alamat',null);
//return $opsi_pengiriman;
if($opsi_pengiriman == 'new')
{
$model = new TbCustomerShipment();
$model->load(Yii::$app->request->post());
$model->customer_id = $customer_id;
if($model->save())
{
\Yii::$app->session['shipemenadd'] = $model;
//get kurir preselected
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where(['produk_id' => $produk->produk_id])->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $model->kota_id ")->one();
$berat_produk = $produk->kuantitas *$produk->berat_produk;
$berat_produk = round($berat_produk);
$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $berat_produk, $kode,$service,$produk->produk_id);
if(count($result)!=0)
{
$produk->harga_kurir = $result[0]['value'];
$produk->estimasi_sampai = $result[0]['etd'];
}
else
{
$message = "pilihan kurir untuk lokasi tersebut tidak tersedia";
}
//return VarDumper::dump($result);
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
if(isset(Yii::$app->session['shipemenadd'])){
return "exists";
}else{
return "doesn't exist";
}
//return $this->redirect(['pengiriman2/index','message'=>$message]);
//print_r(Yii::$app->session['shipemenadd']);
}
//else
//{
// VarDumper::dump($model);
//}
}
else
{
$pengiriman_selected = TbCustomerShipment::find()->where("customer_shipment_id = $opsi_pengiriman")->one();
\Yii::$app->session['shipemenadd'] = $pengiriman_selected;
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where("produk_id =$produk->produk_id")->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
//get kota id rajaongkir
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $pengiriman_selected->kota_id ")->one();
//$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $produk->berat_produk, $kode,$service);
//return VarDumper::dump($result);
//if(count($result)!=0)
//{
//$produk->harga_kurir = $result[0]['value'];
//$produk->estimasi_sampai = $result[0]['etd'];
$produk->harga_kurir = 0;
$produk->estimasi_sampai = 0;
//}
//else
//{
// $message = "pilihan kuriri untuk lokasi tersebut tidak tersedia";
//}
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
return $this->redirect(['pengiriman2/index','message'=>$message]);
}
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
if(count($lsalamat)==0)
//insert to tb shipment
{
$datacustomer = TbCustomer::find()->where(['customer_id'=>$customer_id])->one();
$newalamat = new TbCustomerShipment();
$newalamat->customer_id = $customer_id;
$newalamat->kota_id = $datacustomer->kota_id;
$newalamat->kecamatan_id = $datacustomer->kecamatan_id;
$newalamat->negara_id = $datacustomer->negara_id;
$newalamat->propinsi_id = $datacustomer->propinsi_id;
$newalamat->alamat = $datacustomer->alamat;
$newalamat->shipment_name = "Alamat Rumah";
$newalamat->penerima = $datacustomer->nama;
$newalamat->hp_penerima = $datacustomer->hp;
$newalamat->save();
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
return $this->render('index',['lsalamat'=>$lsalamat,'newalamat'=> $model]);
}
else
{
return $this->goHome();
}
}
}
here is the problem
\Yii::$app->session['shipemenadd'] = $model;
it should
$currentTbCustomerShipment = TbCustomerShipment::find()->where(['customer_user_id' => $model->customer_user_id])->one(); //find latest object
Yii::$app->session['shipemenadd'] = $currentTbCustomerShipment;

Create category programmatically in multiple languages in Magento

i am tyring to add categories programmatically for german and english languages.
website-ID: 1
website store-ID: 1
view-ID english, code "en" => 1
view-ID german, code "de" => 2
$category['general']['path'] = $v['cat_name_de'];
$category['general']['name'] = $v['cat_name_de'];
$category['general']['meta_title'] = "";
$category['general']['meta_description'] = "";
$category['general']['is_active'] = 1;
$category['general']['url_key'] = urlencode($v['cat_name_de']);
$category['general']['display_mode'] = "PRODUCTS";
$category['general']['is_anchor'] = 0;
$category['category']['parent'] = $v['magento_cat_id'];
$storeId = 0; // default
$magento_subcat_id = createCategory($category, $storeId);
...
function createCategory($data, $storeId) {
echo "Erzeuge '{$data['general']['name']}' - Elternkategorie:
[{$data['category']['parent']}] ...";
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
}
if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) &&
!$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
}
try {
$category->save();
return $category->getId();
} catch (Exception $e) {
return FALSE;
}
}
}
What i am puzzling with at the moment is setting view-ID individually for passing the $category['general']['name'] for each language.
I tried to set each language string with a foreach setting english/german texts. But this did not work out, because i somehow mixed up setting the view correctly.
To make it short:
Creating categories and subcategories like this does work very good, but i do not get it to work to pass english/german categoty titles.
Thanks guys
For all of you who are struggeling with this situation i made a workaound like this:
I added all those values to the affected database tables directly. This is for sure a quick and dirty way, but it does the job.
For all in need of some ideas here is the (undocumented) snipped belonging to my initial post.
// Get values for next language insert
$entity_type_id = $category
->getResource()
->getTypeId();
$entity_id = $category->getEntityId();
$read_entity = Mage::getSingleton('core/resource')
->getConnection('core_write');
$sql_entity = "SELECT * FROM eav_attribute WHERE
`attribute_code` = 'name' AND
`entity_type_id` = " . $entity_type_id . ";";
$row_entity = $read_entity
->fetchRow($sql_entity);
$attribute_id = $row_entity['attribute_id'];
// prepare value for name field in different langauge
$val = Mage::getSingleton('core/resource')
->getConnection('default_write')
->quote($v['en']);
$sql_insert = "INSERT INTO `catalog_category_entity_varchar`
(`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`)
VALUES ($entity_type_id,$attribute_id,$storeId,$entity_id,$val);";
$read_entity->query($sql_insert);
I hope this helps someone out who is in need of this.

$this->db->insert_id() giving fatal error postgresql codeigniter

I am using Codeigniter 2.0.1 and Postgresql 8.1. My code uses transactions within try-catch blocks.
On a simple insert at times I get a "Fatal Error"
Fatal Error: Call to a member function row() on a non-object in
<...path...>/system/database/drivers/postgre/postgre_driver.php on
line 357
My Database Config is:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "***";
$db['default']['password'] = "***";
$db['default']['database'] = "***";
$db['default']['dbdriver'] = 'postgre';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
The lne of my Model code that is causing the error is "$id = $this->db->insert_id();".
I say so because the line that causes the error is within insert_id() method and it is being used only once in the model.
A code snapshot of the model is given below.
try {
// CODE TO FILL UP $data ARRAY
$this->DBquery("BEGIN");
$this->DBinsert('<TABLE NAME>', $data);
$id = $this->db->insert_id();
// SOME MORE CODE
}
catch(Exception $e) {
$this->DBquery("ROLLBACK");
//echo $e->getMessage();
return 0;
}
$this->DBquery("COMMIT");
return $id;
$this->DBquery and $this->DBinsert are custom methods made by me on a base model class which extends the CI_Model class. These methods function full well.
Below is the insert_id method in postgre_driver.php and line 357 is "$row = $query->row();"
function insert_id()
{
$v = $this->_version();
$v = $v['server'];
$table = func_num_args() > 0 ? func_get_arg(0) : NULL;
$column = func_num_args() > 1 ? func_get_arg(1) : NULL;
if ($table == NULL && $v >= '8.1')
{
$sql='SELECT LASTVAL() as ins_id';
}
elseif ($table != NULL && $column != NULL && $v >= '8.0')
{
$sql = sprintf("SELECT pg_get_serial_sequence('%s','%s') as seq", $table, $column);
$query = $this->query($sql);
$row = $query->row();
$sql = sprintf("SELECT CURRVAL('%s') as ins_id", $row->seq);
}
elseif ($table != NULL)
{
// seq_name passed in table parameter
$sql = sprintf("SELECT CURRVAL('%s') as ins_id", $table);
}
else
{
return pg_last_oid($this->result_id);
}
$query = $this->query($sql);
$row = $query->row(); // LINE 357
return $row->ins_id;
}
Its so more confusing because the problem is not always. It happens sometimes but with a good enough frequency to hamper work. The system is being used by about 8-10 users and so I guess concurrency should not be an issue.
Also, I am using pconnect and number of connections is unlimited.
This sounds like maybe some of your insert statements are failing. If something errors out inside of a transaction like this, it can invalidate the transaction. If you look in the log file, you may find entries like "current transaction is aborted, commands ignored until end of transaction." (What's happening is the $query variable in the insert_id function doesn't receive a valid query result value, so calling functions on it fails at that point)
The best way to handle this is probably to modify your custom DBinsert function to return a value indicating the success or failure of the insert operation. (You should just be able to return the value of whatever insert command you're running internally)
Then, you can do something like this:
$insert_ret_val = $this->DBinsert('<TABLE NAME>', $data);
if($insert_ret_val){
//insert success!
$id = $this->db->insert_id();
}else{
//handle failed insert here, rollback, whatever
}

CodeIgniter - Active Record returning empty results with Access ODBC

I'm connecting to an Access DB via mdbtools on a Linux system and on running any query via Active Record it returns an empty result. No errors or anything to show in the logs. Any ideas ? It connects to the database without a hitch and I have no problem accessing the tables or running queries with the default PHP method (e.g. odbc_exec(...)).
The DB Connection looks like this:
$db['access']['hostname'] = 'MyDB';
$db['access']['username'] = '';
$db['access']['password'] = '';
$db['access']['database'] = 'MyDB';
$db['access']['dbdriver'] = 'odbc';
$db['access']['dbprefix'] = '';
$db['access']['pconnect'] = TRUE;
$db['access']['db_debug'] = TRUE;
$db['access']['cache_on'] = FALSE;
$db['access']['cachedir'] = '';
$db['access']['char_set'] = 'utf8';
$db['access']['dbcollat'] = 'utf8_general_ci';
$db['access']['swap_pre'] = '';
$db['access']['autoinit'] = TRUE;
$db['access']['stricton'] = FALSE;
The odbc.ini looks like:
[MyDB]
Description = My Database
Driver = /usr/lib64/libmdbodbc.so
Database = /var/database/MyDB.mdb
Connecting with:
$this->access = $this->load->database('access', TRUE);
I do not have microsoft access database to test with the following configuration, but I think this should be able to give you an idea to experience with different configuration. You can specify data source name in your configuration and I collected the settings from codeigniter forum and merge with yours.
$db['access']['hostname'] = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=/var/database/MyDB.mdb";
$db['access']['username'] = "ADODB.Connection";
$db['access']['password'] = "";
$db['access']['database'] = "/var/database/MyDB.mdb";
$db['access']['dbdriver'] = "odbc";
$db['access']['dbprefix'] = "";
$db['access']['pconnect'] = TRUE;
$db['access']['db_debug'] = TRUE;
$db['access']['cache_on'] = FALSE;
$db['access']['cachedir'] = "";
$db['access']['char_set'] = "utf8";
$db['access']['dbcollat'] = "utf8_general_ci";
$db['access']['swap_pre'] = "";
$db['access']['autoinit'] = TRUE;
$db['access']['stricton'] = FALSE;

Resources