Email attachment does not download with imap_fetchstructure function - mysql

I am trying to download email attachment through imap_fetchstructure().
but attachment does not download to the server.
code other parts are perfectly working. text message insert to the database as I coded. only problem is attachment part, can you please help me to resolve this problem. bellow is my code
#!/usr/bin/php -q
<?PHP
//echo $output;
$servername = "localhost";
$username = "user";
$password = "pssw";
$dbname = "db_name";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* connect to email */
$hostname = '{example.org:995/pop3/ssl/novalidate-cert}';
$username = 'test#example.org';
$password = '123456';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to SERVER: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'NEW');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
asort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1);
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 3 = BASE64 encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 4 = QUOTED-PRINTABLE encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
/* prefix the email number to the filename in case two emails
* have the attachment with the same file name.
*/
$fp = fopen("./" . $email_number . "-" . $filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
}
}
//Attachement close
$subject = $overview[0]->subject;
$from = $overview[0]->from;
$received_date = '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '<div class="body">'.$message.'</div>';
}
//INSERT INTO DATABASE
$sql = "INSERT INTO msg_messages (`customer_id`, `msg_title`, `msg_content`, `received`, `handle_by`, `agent_asign`,`dep_id`, `msg_received_date`, `priority_status`, `from_lyca`) VALUES ('".$cus_id."', '".$subject."', '".$remove_customer_mobile_from_message."', '".$cus_mail."', '999999', '999999', 1, '".date("Y-m-d H:i:s")."', 2, 1)";
$result = mysqli_query($conn, $sql);
}
/* close the connection */
imap_close($inbox);
?>

Related

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);
...

WordPress and PHP | Check if row exists in database if yes don't insert data

I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...

Sage Pay v3.00 Integration

Can anyone help me incorporate the Sagepay v3.00 AES/CBC/PKCS#5 algorithm (encryption) into the following file. I'm really struggling to understand how to include so that customer data is encrypted to the new standard and then decrypted on the way back. Using Sagepay Form with a very old version of cs-cart, though have successfully managed to upgrade from version 2.22 to 2.23, but Sagepay are pulling all support from July.
Not sure how much of this script is relevant to the encryption:
<?php
if ( !defined('IN_CSCART') ) { die('Access denied'); }
if (defined('PAYMENT_NOTIFICATION')) {
// Get the password
$payment_id=db_get_field("SELECT $db_tables[payments].payment_id FROM $db_tables[payments] LEFT JOIN $db_tables[payment_processors] ON $db_tables[payment_processors].processor_id = $db_tables[payments].processor_id WHERE $db_tables[payment_processors].processor_script='protx_form.php'");
$processor_data = fn_get_payment_method_data($payment_id);
$result = "&".simpleXor(base64Decode($_REQUEST['crypt']), $processor_data["params"]["password"])."&";
preg_match("/Status=(.+)&/U", $result, $a);
if(trim($a[1]) == "OK") {
$pp_response['order_status'] = ($processor_data["params"]["transaction_type"] == 'PAYMENT') ? 'P' : 'O';
preg_match("/TxAuthNo=(.+)&/U", $result, $authno);
$pp_response["reason_text"] = "AuthNo: ".$authno[1];
preg_match("/VPSTxID={(.+)}/U", $result, $transaction_id);
$pp_response["transaction_id"] = #$transaction_id[1];
} else {
$pp_response['order_status'] = 'F';
preg_match("/StatusDetail=(.+)&/U", $result, $stat);
$pp_response["reason_text"] = "Status: ".trim($stat[1])." (".trim($a[1]).") ";
}
preg_match("/AVSCV2=(.*)&/U", $result, $avs);
if(!empty($avs[1])) {
$pp_response['descr_avs'] = $avs[1];
}
include $payment_files_dir.'payment_cc_complete.php';
fn_order_placement_routines($order_id);
}
else
{
global $http_location, $b_order, $_total_back;
$post_address = ($processor_data['params']['testmode'] != "N") ? "https://test.sagepay.com/gateway/service/vspform-register.vsp" : "https://live.sagepay.com/gateway/service/vspform-register.vsp";
$post["VPSProtocol"] = "2.23";
$post["TxType"] = $processor_data["params"]["transaction_type"];
$post["Vendor"] = htmlspecialchars($processor_data["params"]["vendor"]);
// Form Cart products
$strings = 0;
if (is_array($cart['products'])) {
$strings += count($cart['products']);
}
if (!empty($cart['products'])) {
foreach ($cart['products'] as $v) {
$_product = db_get_field("SELECT product FROM $db_tables[product_descriptions] WHERE product_id='$v[product_id]' AND lang_code='$cart_language'");
$products_string .= ":".str_replace(":", " ", $_product).":".$v['amount'].":".fn_format_price($v['subtotal']/$v['amount']).":::".fn_format_price($v['subtotal']);
}
}
if (!empty($cart['payment_surcharge'])) {
$products_string .= ":Payment surcharge:---:---:---:---:".fn_format_price($cart['payment_surcharge']);
$strings ++;
}
if (!empty($cart['shipping_cost'])) {
$products_string .= ":Shipping cost:---:---:---:---:".fn_format_price($cart['shipping_cost']);
$strings ++;
}
$post_encrypted .= "Basket=".$strings.$products_string;
$post["Crypt"] = base64_encode(simpleXor($post_encrypted, $processor_data["params"]["password"]));
$post["Crypt"] = htmlspecialchars($post["Crypt"]);
$msg = fn_get_lang_var('text_cc_processor_connection');
$msg = str_replace('[processor]', 'Protx Server', $msg);
echo <<<EOT
<html>
<body onLoad="document.process.submit();">
<form action="{$post_address}" method="POST" name="process">
<INPUT type=hidden name="VPSProtocol" value="{$post['VPSProtocol']}">
<INPUT type=hidden name="Vendor" value="{$post['Vendor']}">
<INPUT type=hidden name="TxType" value="{$post['TxType']}">
<INPUT type=hidden name="Crypt" value="{$post['Crypt']}">
<p>
<div align=center>{$msg}</div>
</p>
</body>
</html>
EOT;
}
exit;
//
// ---------------- Additional functions ------------
//
function simpleXor($InString, $Key) {
$KeyList = array();
$output = "";
for($i = 0; $i < strlen($Key); $i++){
$KeyList[$i] = ord(substr($Key, $i, 1));
}
for($i = 0; $i < strlen($InString); $i++) {
$output.= chr(ord(substr($InString, $i, 1)) ^ ($KeyList[$i % strlen($Key)]));
}
return $output;
}
function base64Decode($scrambled) {
// Initialise output variable
$output = "";
// Fix plus to space conversion issue
$scrambled = str_replace(" ","+",$scrambled);
// Do encoding
$output = base64_decode($scrambled);
// Return the result
return $output;
}
?>
You could try dropping the following functions into the script, then swapping out simpleXor for encryptAes. Make sure that you also add an '#' symbol as the first character of the crypt string (and strip it off when decoding the response from Sage Pay).
function addPKCS5Padding($input)
{
$blockSize = 16;
$padd = "";
$length = $blockSize - (strlen($input) % $blockSize);
for ($i = 1; $i <= $length; $i++)
{
$padd .= chr($length);
}
return $input . $padd;
}
function removePKCS5Padding($input)
{
$blockSize = 16;
$padChar = ord($input[strlen($input) - 1]);
$unpadded = substr($input, 0, (-1) * $padChar);
return $unpadded;
}
function encryptAes($string, $key)
{
$string = addPKCS5Padding($string);
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $key);
return strtoupper(bin2hex($crypt));
}
function decryptAes($strIn, $password)
{
$strInitVector = $password;
$strIn = pack('H*', $hex);
$string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, $strIn, MCRYPT_MODE_CBC,$strInitVector);
return removePKCS5Padding($string);
}
You could try this. I can't test it, so let me know how you get on.
<?php
if ( !defined('IN_CSCART') ) { die('Access denied'); }
if (defined('PAYMENT_NOTIFICATION')) {
// Get the password
$payment_id=db_get_field("SELECT $db_tables[payments].payment_id FROM $db_tables[payments] LEFT JOIN $db_tables[payment_processors] ON $db_tables
[payment_processors].processor_id = $db_tables[payments].processor_id WHERE $db_tables[payment_processors].processor_script='protx_form.php'");
$processor_data = fn_get_payment_method_data($payment_id);
#Rik added:
$result = "&".decryptAes($_REQUEST['crypt'], $processor_data["params"]["password"])."&";
#$result = "&".simpleXor(base64Decode($_REQUEST['crypt']), $processor_data["params"]["password"])."&";
preg_match("/Status=(.+)&/U", $result, $a);
if(trim($a[1]) == "OK") {
$pp_response['order_status'] = ($processor_data["params"]["transaction_type"] == 'PAYMENT') ? 'P' : 'O';
preg_match("/TxAuthNo=(.+)&/U", $result, $authno);
$pp_response["reason_text"] = "AuthNo: ".$authno[1];
preg_match("/VPSTxID={(.+)}/U", $result, $transaction_id);
$pp_response["transaction_id"] = #$transaction_id[1];
} else {
$pp_response['order_status'] = 'F';
preg_match("/StatusDetail=(.+)&/U", $result, $stat);
$pp_response["reason_text"] = "Status: ".trim($stat[1])." (".trim($a[1]).") ";
}
preg_match("/AVSCV2=(.*)&/U", $result, $avs);
if(!empty($avs[1])) {
$pp_response['descr_avs'] = $avs[1];
}
include $payment_files_dir.'payment_cc_complete.php';
fn_order_placement_routines($order_id);
}
else
{
global $http_location, $b_order, $_total_back;
$post_address = ($processor_data['params']['testmode'] != "N") ? "https://test.sagepay.com/gateway/service/vspform-register.vsp" :
"https://live.sagepay.com/gateway/service/vspform-register.vsp";
$post["VPSProtocol"] = "2.23";
$post["TxType"] = $processor_data["params"]["transaction_type"];
$post["Vendor"] = htmlspecialchars($processor_data["params"]["vendor"]);
// Form Cart products
$strings = 0;
if (is_array($cart['products'])) {
$strings += count($cart['products']);
}
if (!empty($cart['products'])) {
foreach ($cart['products'] as $v) {
$_product = db_get_field("SELECT product FROM $db_tables[product_descriptions] WHERE product_id='$v[product_id]' AND lang_code='$cart_language'");
$products_string .= ":".str_replace(":", " ", $_product).":".$v['amount'].":".fn_format_price($v['subtotal']/$v['amount']).":::".fn_format_price($v
['subtotal']);
}
}
if (!empty($cart['payment_surcharge'])) {
$products_string .= ":Payment surcharge:---:---:---:---:".fn_format_price($cart['payment_surcharge']);
$strings ++;
}
if (!empty($cart['shipping_cost'])) {
$products_string .= ":Shipping cost:---:---:---:---:".fn_format_price($cart['shipping_cost']);
$strings ++;
}
$post_encrypted .= "Basket=".$strings.$products_string;
#Rik added:
$post["Crypt"] = "#".encryptAes($post_encrypted, $processor_data["params"]["password"]);
# $post["Crypt"] = base64_encode(simpleXor($post_encrypted, $processor_data["params"]["password"]));
# $post["Crypt"] = htmlspecialchars($post["Crypt"]);
$msg = fn_get_lang_var('text_cc_processor_connection');
$msg = str_replace('[processor]', 'Protx Server', $msg);
echo <<<EOT
<html>
<body onLoad="document.process.submit();">
<form action="{$post_address}" method="POST" name="process">
<INPUT type=hidden name="VPSProtocol" value="{$post['VPSProtocol']}">
<INPUT type=hidden name="Vendor" value="{$post['Vendor']}">
<INPUT type=hidden name="TxType" value="{$post['TxType']}">
<INPUT type=hidden name="Crypt" value="{$post['Crypt']}">
<p>
<div align=center>{$msg}</div>
</p>
</body>
</html>
EOT;
}
exit;
//
// ---------------- Additional functions ------------
//
function simpleXor($InString, $Key) {
$KeyList = array();
$output = "";
for($i = 0; $i < strlen($Key); $i++){
$KeyList[$i] = ord(substr($Key, $i, 1));
}
for($i = 0; $i < strlen($InString); $i++) {
$output.= chr(ord(substr($InString, $i, 1)) ^ ($KeyList[$i % strlen($Key)]));
}
return $output;
}
function base64Decode($scrambled) {
// Initialise output variable
$output = "";
// Fix plus to space conversion issue
$scrambled = str_replace(" ","+",$scrambled);
// Do encoding
$output = base64_decode($scrambled);
// Return the result
return $output;
}
#added by Rik
function addPKCS5Padding($input)
{
$blockSize = 16;
$padd = "";
$length = $blockSize - (strlen($input) % $blockSize);
for ($i = 1; $i <= $length; $i++)
{
$padd .= chr($length);
}
return $input . $padd;
}
function removePKCS5Padding($input)
{
$blockSize = 16;
$padChar = ord($input[strlen($input) - 1]);
$unpadded = substr($input, 0, (-1) * $padChar);
return $unpadded;
}
function encryptAes($string, $key)
{
$string = addPKCS5Padding($string);
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $key);
return strtoupper(bin2hex($crypt));
}
function decryptAes($strIn, $password)
{
#Sagepay specific - remove the '#'
$strIn = substr($strIn,1)
$strInitVector = $password;
$strIn = pack('H*', $hex);
$string = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $password, $strIn, MCRYPT_MODE_CBC,$strInitVector);
return removePKCS5Padding($string);
}
?>
/*First build your data. */
$data = 'variableA='.$this->variableA;
$data .= '&variableB='.$this->variableB;
...
$data .= '&variableZ='.$this->variableZ;
/** Encript data */
$dataEncrip = $this->encData($data);
/** function to Encrypt *//
public function encData($data){
$data = $this->pkcs5_pad( $data, 16);
$dataEnc = "#".bin2hex( mcrypt_encrypt( MCRYPT_RIJNDAEL_128,
$this->passwordToEncript,
$data,
MCRYPT_MODE_CBC,
$this->getPasswordToEncrypt()));
return $dataEnc;
}
/** Pkcs5_pad */
public function pkcs5_pad( $data, $blocksize ){
$pad = $blocksize - (strlen( $data ) % $blocksize);
return $data . str_repeat( chr( $pad ), $pad );
}

insert data to the database from csv file

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
}

PHP MySQL script gone wrong

I'm working on a site and created this experimental script which populates a category menu dynamically based on the database entry.
It worked for a day and then suddenly stopped. I changed my includes for requires and it gave me this error message
Fatal error: Maximum execution time of 30 seconds exceeded in /home1/advertbo/public_html/dev_area/origocloud/include/views/blog/dbget.php on line 34
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
$array = mysql_fetch_array($result);
mysql_close($con);
$pre = NULL;
$hc = 0;
$sc = 1;
while ($array) {
if($pre == NULL){
$pre = $row["headc"];
$test[0][0]=$row["headc"];
$test[0][1]=$row["subc"];
}
else
{
if($pre ==$row["headc"]){
$sc++;
$test[$hc][$sc] = $row["subc"];
}
else
{
$hc++;
$sc = 1;
$test[$hc][0]=$row["headc"];
$test[$hc][$sc]=$row["subc"];
$pre = $row["headc"];
}
}
}
foreach( $test as $arrays=>$cat)
{
$first = TRUE;
foreach($cat as $element)
{
if($first == TRUE)
{
$htmlString.= '<h3>'.$element.'</h3>
<div>
<ul>
';
$first = FALSE;
}
else
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$element.'</a></li>';
}
}
$htmlString.= '</ul> </div>';
}
return $htmlString;
}
I'm really stuck, the page just keeps timing out the point where i call the function
Try this:
while ($array = mysql_fetch_array($result)) {}
Take a look on PHP docs http://php.net/mysql_fetch_array
If does not work, your SQL Query returns too much values and craches the php execution
=]
I think it's time to take a step back and look at what you're doing :) This function should do what you want (even if you fixed the infinite loop problem in the function you gave, I don't think it would act how you want it to.):
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
// arrays can have strings as keys as well as numbers,
// and setting $some_array[] = 'value'; (note the empty brackets [])
// automatically appends 'value' to the end of $some_array,
// so you don't have to keep track of or increment indexes
while ($row = mysql_fetch_assoc($result))
{
$test[$row["headc"]][] = $row["subc"];
}
// don't close the connection until after we're done reading the rows
mysql_close($con);
// $test looks like: array('headc1' => array('subc1', 'subc2', 'sub3'), 'headc2' => array('subc4', 'subc5'), ...)
// so we step through each headc, and within that loop, step through each headc's array of subc's.
foreach($test as $headc => $subc_array)
{
$htmlString.= '<h3>'.$headc.'</h3><div><ul>';
foreach($subc_array as $subc)
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$subc.'</a></li>';
}
$htmlString.= '</ul></div>';
}
return $htmlString;
}