insert data to the database from csv file - csv

i am trying to insert data from the csv excel file to the database but the code seem not to work,
i don't know where am doing wrong.
here is my code:
public function postUploadS(){
$file = array('file' => Input::file('file'));
$rule = array('file' => 'required');
$mime = array( 'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel'
);
$uploaded_mime = Input::file('file')->getMimeType();
$staff_list=$_FILES['file']['tmp_name'];
$linecount = "";
$cols = 5;
$numx ="";
$mimes = array(
'text/csv',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',);
if(empty($staff_list)){
$_SESSION['error']="<font color='#FF0000'>Please choose the csv file to upload</font>";
}
elseif(!in_array($_FILES['file']['type'], $mimes)) {
$_SESSION['error']="<font color='#FF0000'>Invalid file format, Please choose only csv exel format</font>";
}
else{
$staff_list=$_FILES['file']['tmp_name'];
$handle=fopen($staff_list,"r");
// read the first line and ignore it
fgets($handle);
//count number of lines of uploaded csv file
$fh = fopen($staff_list,'rb') or die("ERROR OPENING DATA");
while (fgets($fh) !== false) $linecount++;
fclose($fh);
var_dump($fh); exit();
while(($fileop=fgetcsv($handle,1000,",")) !==false){
$fullname = $fileop[1];
$staff_id = $fileop[0];
$gender = $fileop[2];
$position= $fileop[3];
$department= $fileop[4];
$numx = count($fileop);
$tfulname = trim($fullname);
$lfulname = strtolower($tfulname);
$name_full = explode(' ', $lfulname);
$firstname = $name_full[0];
$middlename = implode(array_slice($name_full, 1, -1));
$lastname = end($name_full);
$phone = '';
$email = '';
$college = '';
if($gender == 'M'){
$gender == 'Male';
}
elseif ($gender =='F') {
$gender == 'Female';
}
DB::beginTransaction();
try{
$staff = new Staff;
$staff->staff_id = $staff_id;
$staff->firstname = $firstname;
$staff->middlename = $middlename;
$staff->lastname = $lastname;
$staff->gender = $gender;
$staff->position = $position;
$staff->phone = $phone;
$staff->email = $email;
$staff->college = $college;
$staff->department = $department;
$staff->save();
}
catch(Exception $e){
Session::put('key','There is a duplicate row in your data,check the file and try again');
}
$cPass = ucfirst($lastname);
$hashed_pass = Hash::make($cPass);
$user = new User;
$user->username = $staff_id;
$user->password = $hashed_pass;
$user->save();
}
if($numx!=$cols){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,number of columns does not match the defined value,please check your file and try again</font>");
}
elseif(Session::has('key')){
DB::rollback();
Session::put("error","<font color='#FF0000'>Error,duplicate entry detected in your file,please check your file and try again</font>");
}
else{
DB::commit();
Session::put("success","<font color='#0099FF'>Staff list has been uploaded successfully</font>");
}
}
}
when i run above code no data is inserted and i don't get any error. help please

$file = Reader::createFromPath('path-to-your-file');
$result = $file->fetchAll();
foreach($result as $data){
// do database add here
}

Related

No results found when i use postman

I have a PHP code connected to mysql database. I want to send user login data from the postman tool and receive it in the php code and then return it to the result
The problem is that when sending data do not get the result
PHP CODE
<?php
$response = array();
header("Content-type: application/json; charset=utf-8");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
include 'db/db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) && isset($input['password']) ){
$username = $input['username'];
$password = $input['password'];
$query = "SELECT full_name , password_hash , salt , email , id_con , born , city , country و card_id ,cardstatus, cardvalue FROM member WHERE username = ?";
if($stmt = $con->prepare($query)){
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($fullName , $passwordHashDB ,$salt, $email , $countryid , $born , $city , $country ,$cardid ,$cardstatus, $cardvalue);
if($stmt->fetch()){
//Validate the password
if(password_verify(concatPasswordWithSalt($password,$salt),$passwordHashDB)){
$response["status"] = 0;
$response["message"] = "Login successful";
$response["full_name"] = $fullName;
$response["card_id"] = $cardid;
$response["email"] = $email;
$response["id_con"] = $countryid;
$response["country"] = $country;
$response["city"] = $city;
$response["born"] = $born;
$response["cardstatus"] = $cardstatus;
$response["cardvalue"] = $cardvalue;
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
}
else{
$response["status"] = 1;
$response["message"] = "Invalid username and password combination";
}
$stmt->close();
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
//Display the JSON response
echo json_encode($response);
?>
SCREENSHOT

Can not save data but the message has been save

I have created Cake PHP 3, I want to add data, but when I clik submit button, the data is didn't save but the message show data has been save. I add into two different tables. When I try to add data in one table is fine.
This is my controller
StoreController.php
public function add()
{
$this->loadComponent('General');
$setStatus = 1;
$store = $this->Stores->newEntity();
if ($this->request->is('post')) {
// dd( $this->request->getData());exit;
$connection = ConnectionManager::get('ora');
$connection->begin();
$store = $this->Stores->patchEntity($store, $this->request->getData());;
$merchantTable = TableRegistry::get('MasterFile.Merchants');
$merchant = $merchantTable->find()->where(['MERCHANT_CODE'=>$store->MERCHANT_CODE])->first();
$store->MERCHANT_ID = $merchant->MERCHANT_ID;
$store->CREATED_DATE = date("Y-m-d h:i:s");
$store->LAST_UPDATED_DATE = date("Y-m-d h:i:s");
$store->LAST_APPROVED_DATE = date("Y-m-d h:i:s");
$store->LAST_VERSION_DATE = date("Y-m-d h:i:s");
// $store->store_address->LINE1 = $store->LINE1;
// Start - Controller Code to handle file uploading
if(!empty($this->request->data['STORE_LOGO']['name']))
{
$file = $this->request->data['STORE_LOGO']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
$fileName = $this->request->data['STORE_LOGO']['name'];
$uploadPath = WWW_ROOT.'img/store_logo/';
$uploadFile = $uploadPath.$fileName;
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
if(move_uploaded_file($this->request->data['STORE_LOGO']['tmp_name'],$uploadFile))
{
$store['STORE_LOGO'] = $uploadFile;
}
}
}
if(!empty($this->request->data['BACKGROUND_PICTURE']['name']))
{
$fileName = $this->request->data['BACKGROUND_PICTURE']['name'];
$uploadPath = WWW_ROOT.'img/background_picture/';
$uploadFile = $uploadPath.$fileName;
if(move_uploaded_file($this->request->data['BACKGROUND_PICTURE']['tmp_name'],$uploadFile))
{
$store['BACKGROUND_PICTURE'] = $uploadFile;
}
}
// now do the save
if ($this->Stores->save($store)) {
$setStatus = 1;
$message = 'The store has been saved.';
if($setStatus == 1){
$this->loadComponent('General');
$this->loadModel('MasterFile.Addresss');
$setStatus = 1;
$address = $this->Addresss->newEntity();
//dd($this->request->data);
$this->request->data['Address']['LINE1'] = $this->request->data['LINE1'];
$this->request->data['Address']['LINE2'] = $this->request->data['LINE2'];
$this->request->data['Address']['LINE3'] = $this->request->data['LINE3'];
//dd($this->request->data['Address']);
$connection = ConnectionManager::get('ora');
$connection->begin();
$address = $this->Addresss->patchEntity($address, $this->request->data['Address']);
// dd($address);
// now do the save
if ($this->Addresss->save($address)) {
$setStatus = 1;
$message = 'The store has been saved.';
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
}
}else{
$setStatus = 0;
$message = 'The store could not be saved. Please, try again.';
}
$this->Flash->set(__($message));
if($setStatus){
$connection->commit();
return $this->redirect(['action' => 'index']);
}else {
$connection->rollback();
}
}
$this->set(compact('store'));
$this->set('_serialize', ['store']);
}
What should i do?
Thank you for your help!
Try debugging the entity:
if ($this->Stores->save($store)) {
debug($store);
...

Skip the first line of a CSV file in Yii2

public function actionUpload(){
$model = new CsvForm();
if($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model,'file');
$filename = 'Data.'.$file->extension;
$upload = $file->saveAs('uploads/'.$filename);
if($upload){
define('CSV_PATH','uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
print_r($filecsv);
foreach($filecsv as $data){
$modelnew = new Customer1();
$hasil = explode(",",$data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$modelnew->username = $nim;
$modelnew->firstname = $nama;
$modelnew->lastname = $jurusan;
$modelnew->password = $angkatan;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
}
This is my CSV data
user1,name,pass,info
user2,name,pass,info
etc..,
So I want to skip Bold content and proceed my execution.
You could shift the array
$filecsvtemp = file($csv_file);
$filecsv = array_shift($filecsvtemp );
in this way the first row of the array is not present in the resulting array
otherwise use a counter
$cnt = 0;
$filecsv = file($csv_file);
print_r($filecsv);
foreach($filecsv as $data){
if ($cnt!=0){
$modelnew = new Customer1();
$hasil = explode(",",$data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$modelnew->username = $nim;
$modelnew->firstname = $nama;
$modelnew->lastname = $jurusan;
$modelnew->password = $angkatan;
$modelnew->save();
}
$cnt++;
}

yii2 active record transaction still commit when the validation failed

I'm using Yii2 active record transaction, but the validation failed in the middle of the codes, it still commit the transaction.
Please advice.
public function actionCreate()
{
$model = new PoAgen();
$seq = Sequence::FindOne(['seq_id' => 'INV/AG', 'seq_name' => (int)date('ymd')]);
if(is_null($seq))
{
$_seq = new Sequence();
$_seq->seq_id = 'INV/AG';
$_seq->seq_name = (int)date('ymd');
$_seq->value = 0;
$_seq->save();
$model->trx_id = $_seq->seq_id . '/' . $_seq->seq_name . str_pad($_seq->value+1, 3, "0", STR_PAD_LEFT);
}
else {
$seq->value += 1;
$model->trx_id = $seq->seq_id . '/' . $seq->seq_name . str_pad($seq->value, 3, "0", STR_PAD_LEFT);
$seq->update();
}
$model->pot_cong = 0;
$model->pot_basah_kg = 0;
$model->pot_tangkai = 0;
$model->ppn = 0;
$model->pot_pinjaman = 0;
$model->pot_panjar = 0;
$model->ongkos_angkut = 0;
$model->pot_angkut = 0;
$model->is_transfer = true;
$model->buy_date = date('Y-m-d');
if ($model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
try
{
$model->created_by = Yii::$app->user->identity->id;
$model->created_time = date('Y-m-d H:i:s');
$saldo = Saldo::findOne(1);
$kas = Kas::findOne(1000); // pembelian agen pks
$agen = Agen::findOne($model->agen_id);
if(!$model->is_transfer)
{
if($kas->code == 'D')
{
$saldo->balance -= $model->total_bayar;
}
else
{
$saldo->balance += $model->total_bayar;
}
$saldo->update();
}
$model->save();
// posting to kasbook
$kasbook = new KasBook();
$kasbook->kasbook_id = uniqid();
$kasbook->kas_date = $model->buy_date;
$kasbook->ref_trxid = $model->trx_id;
$kasbook->kas_id = $kas->kas_id;
$kasbook->code = $kas->code;
$kasbook->total = $model->total_bayar;
$kasbook->balance = $saldo->balance;
$kasbook->received_by = '['. $model->agen_id . '] ' . $agen->agen_name;
$kasbook->remark = 'Berat Bersih : ' . $model->r_bersih . ', Harga : ' . $model->price;
$kasbook->vehicle_id = $model->vehicle_id;
$kasbook->is_transfer = $model->is_transfer;
$kasbook->created_by = Yii::$app->user->identity->id;
$kasbook->created_time = date('Y-m-d H:i:s');
$kasbook->save();
if($model->ppn != 0)
{
$kb_1 = new KasBook();
$kb_1->kasbook_id = uniqid();
$kb_1->kas_date = $model->buy_date;
$kb_1->ref_trxid = $model->trx_id;
$kb_1->kas_id = 2000;
$kb_1->code = 'K';
$kb_1->total = $model->ppn;
$kb_1->balance = $saldo->balance;
$kb_1->remark = 'Ppn Pembelian Agen';
$kb_1->vehicle_id = $model->vehicle_id;
$kb_1->is_transfer = true;
$kb_1->created_by = Yii::$app->user->identity->id;
$kb_1->created_time = date('Y-m-d H:i:s');
$kb_1->save();
}
// kurang posting ke purchase order barang
$transaction->commit();
return $this->redirect(['view', 'id' => $model->trx_id]);
}
catch(Exception $e) {
$transaction->rollBack();
throw $e;
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
validation failed in if($model->ppn !=0) { ... }
because there is no any primary key in the master table, but the transaction still do commit and the model inserted to database.
Please advice. Thanks before.
save() method does not throw exceptions but returns boolean so you need to throw it explicitly. Replace every
...->save();
in try-catch with
if (! ...->save()) {
throw new \yii\db\Exception('Error while saving ... model!');
// or use general \Exception()
}
so now it can be caught.
You can do this by :
$flag=true;
if($model->ppn != 0)
{
$kb_1 = new KasBook();
$kb_1->kasbook_id = uniqid();
$kb_1->kas_date = $model->buy_date;
$kb_1->ref_trxid = $model->trx_id;
$kb_1->kas_id = 2000;
$kb_1->code = 'K';
$kb_1->total = $model->ppn;
$kb_1->balance = $saldo->balance;
$kb_1->remark = 'Ppn Pembelian Agen';
$kb_1->vehicle_id = $model->vehicle_id;
$kb_1->is_transfer = true;
$kb_1->created_by = Yii::$app->user->identity->id;
$kb_1->created_time = date('Y-m-d H:i:s');
if(!$kb_1->save())
{
$flag=false;
}
}
if($flag)
$transaction->commit();
else
$transaction->rollback();

How to fetch single row/data from Mysql_fetch_array?

I am reading .csv file through PHP using fgetcsv(). Now I am able to fetch I mean read data from .csv file.
Then I need to check SKU column with my fetch result & accordingly have to perform either Insertion Or Updation.
Suppose SKU is already present there, then I have to update my row in table else I need to insert new record.
I have write following code...Plz check n tell me where I am doing mistake-:
<?php
$row = 1;
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
for ($c=0; $c < $num; $c++)
{
$temp = $data;
$string = implode(";", $temp);
}
$pieces = explode(";", $string);
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password");
If (!$con)
{
die('Could not connect: ' . mysql_error());
mysql_close($con);
}
$seldb = mysql_select_db($db_name, $con);
$query_fetch = "SELECT `sku` from `imoprt_prices`";
$result_fetch = mysql_query($query_fetch);
$num_rows = mysql_num_rows($result_fetch);
for($i = 0; $i < $num_rows; $i++)
{
$value = mysql_result($result_fetch, i, 'sku');
if(strcmp('".$value."', '".$col2."') == 0)
{
$flag = 1;
break;
}
else
{
$flag = 0;
break;
}
}
if($flag == 1)
{
$query_upadte = "(UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'
)";
mysql_query($query_upadte);
$row++;
}
if($flag == 0)
{
mysql_query("INSERT INTO `imoprt_prices`(`customer_id`,`sku`,`price`,`website`) VALUES('".$col1."','".$col2."','".$col3."','".$col4."')");
$row++;
}
}
}
?>
If you have an actual UNIQUE index on your imoprt_prices table, you can use the ON DUPLICATE KEY UPDATE syntax and simplify your code a bit to something similar to; (note, can't test, so see as pseudo code)
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password") or die(mysql_error());
$seldb = mysql_select_db($db_name, $con);
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$query_upadte = "INSERT INTO imoprt_prices (customer_id, sku, price, website) ".
"VALUES('".$col1."','".$col2."','".$col3."','".$col4."') ".
"ON DUPLICATE KEY UPDATE customer_id='".$col1."', price='".$col3.
"',website='".$col4."'";
mysql_query($query_upadte);
}
}
You may also want to either mysql_real_escape_string() or use parameterized queries to make sure there's no ' in your inserted values though. That is always a danger with building sql strings like this.
Simple demo here.
In the following snippet:
$query_upadte = "UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'";
You're trying to update all the rows repeatedly, instead of just updating a single row. This is normally not allowed in MySQL. You need to specify a particular unique ID to be updated.