How to return variable values in codeigniter language line strings? - codeigniter-2

To be more clear, none of these lines in default language's general_lang.php work:
$lang['general_welcome_message'] = 'Welcome, %s ( %s )';
or
$lang['general_welcome_message'] = 'Welcome, %1 ( %2 )';
I expect an output like Welcome, FirstName ( user_name ).
I followed the second (not accepted) answer at https://stackoverflow.com/a/10973668/315550.
The code I write in the view is:
<div id="welcome-box">
<?php echo lang('general_welcome_message',
$this->session->userdata('user_firstname'),
$this->session->userdata('username')
);
?>
</div>
I use codeigniter 2.

You will need to use php's sprintf function (http://php.net/manual/en/function.sprintf.php)
Example from http://ellislab.com/forums/viewthread/145634/#749634:
//in english
$lang['unread_messages'] = "You have %1$s unread messages, %2$s";
//in another language
$lang['unread_messages'] = "Hi %2$s, You have %1$s unread messages";
$message = sprintf($this->lang->line(‘unread_messages’), $number, $name);

I extended Code CI_Lang class like this..
class MY_Lang extends CI_Lang {
function line($line = '', $swap = null) {
$loaded_line = parent::line($line);
// If swap if not given, just return the line from the language file (default codeigniter functionality.)
if(!$swap) return $loaded_line;
// If an array is given
if (is_array($swap)) {
// Explode on '%s'
$exploded_line = explode('%s', $loaded_line);
// Loop through each exploded line
foreach ($exploded_line as $key => $value) {
// Check if the $swap is set
if(isset($swap[$key])) {
// Append the swap variables
$exploded_line[$key] .= $swap[$key];
}
}
// Return the implode of $exploded_line with appended swap variables
return implode('', $exploded_line);
}
// A string is given, just do a simple str_replace on the loaded line
else {
return str_replace('%s', $swap, $loaded_line);
}
}
}
ie. In your language file:
$lang['foo'] = 'Thanks, %s. Your %s has been changed.'
And where-ever you want to use it (controller / view etc.)
echo $this->lang->line('foo', array('Charlie', 'password'));
Will produce
Thanks, Charlie. Your password has been changed.
This handles single 'swaps' as well as multiple
Also it won't break any existing calls to $this->lang->line.

Related

How can I export data tab separated

I'm exporting some Data from a DB and I want to have the 2 columns that I generate Tab separated.
I've already tried to use implode after my fputcsv but it always appears comma separated. Also tried changing my separator (,) to some other character, but a comma is always printed in the CSV.
This is the function that I'm using for it.
public function ResearchExport(Request $request)
{
//Export ProductID and KitID of all the Kits created from the given date to the actual moment
$TubeAddDate = $request->input('TubeAddDate');
$select = DB::table('tubes')->select('TubeBarcodeID', 'ActivationCode')->where('LOG_important', '2')->whereBetween('TubeAddDate', array($TubeAddDate, NOW()))->get();
$tot_record_found=0;
if (count($select)>0) {
$tot_record_found=1;
$CsvData=array('TubeBarcodeID,ActivationCode');
foreach ($select as $value) {
$CsvData[]=$value->TubeBarcodeID.",".$value->ActivationCode.;
}
$filename=date('Y-m-d').".csv"; //stores the file with the date of today as name
$file_path=storage_path().'/'.$filename;
$file = fopen($file_path, "w+");
foreach ($CsvData as $exp_data) {
fputcsv($file, explode(",", $exp_data));
}
fclose($file);
return response()->download($file_path, $filename);
}
return view('InsertForms/download', ['record_found' =>$tot_record_found]);
}
At the moment I'm getting this as output
TubeBarcodeID,ActivationCode
FF01111112,IKG5G-B0FIZ
FF0111113,6XMP8-760Y3
but I expect something tab separated in the CSV like this
TubeBarcodeID ActivationCode
FF01111112 IKG5G-B0FIZ
FF0111113 6XMP8-760Y3
So I actually just solved thanks to one of the commentaries that pointed out my error.
I just had to change my .csv to .xls and then override the third parameter of fputcsv with a "\t".
$filename=date('Y-m-d').".xls"; //stores the file with the date of today as name
$file_path=storage_path().'/'.$filename;
$file = fopen($file_path, "w+");
foreach ($CsvData as $exp_data) {
fputcsv($file, explode(",", $exp_data), "\t");
}

$_SESSION variables use in queries

I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"

how to get required label from string of objects

In my code-igniter application, I have an string that contains json objects. each object has value and label, and I want to get the label from an object where the value matches. Please tell how can I do that?
String:
$my_string = '{value:"123",label:"example"},{value:"321",label:"required label"}';
Hope this will help you :
Use json_decode and foreach for that like this :
Working demo : https://eval.in/1008536
/*your json string should be like this */
$my_string='[{"value":"123","label":"example"},{"value":"321","label":"required label"}]';
$arr = json_decode($my_string,true);
if ( ! empty($arr))
{
foreach ($arr as $item) {
if ($item['value'] == '321')
{
$label = $item['label'];
}
}
}
echo $label;
/* Output : required label*/
For more : http://php.net/manual/en/function.json-decode.php

error foreach in View Codeigniter : Illegal string offset

Please help, i use foreach to return data from database, but it only return the last data (array always update with last data). So i modified the code but i got error : Illegal string offset in foreach.
here is my controller
foreach($dataDesa as $desa)
{
$namaDesa = json_decode($this->curl->simple_get($desa->alamat_api.'/info_desa?ID_DESA=1'));
$datakonten[$namaDesa] = array(
'proyek' =>json_decode($this->curl->simple_get($desa->alamat_api.'/proyek_pertanian')),
'nama_desa' =>json_decode($this->curl->simple_get($desa->alamat_api.'/info_desa?ID_DESA=1')),
'lelang' =>json_decode($this->curl->simple_get($desa->alamat_api.'/pelelangan'))
);
}
$datakonten['getAllDesa'] = $this->M_desa->getAllDesa($idStatus);
$nama_Desa = array();
foreach($datakonten['getAllDesa'] as $row)
{
$nama_Desa[] = $row->nama_desa;
}
$datakonten['nama_desa']=$nama_Desa;
$data['content'] = $this->load->view('public/konten/v_home',$datakonten,TRUE);
$this->load->view('public/halaman/v_home',$data);
and here is my view
$i=0;
foreach($nama_desa[$i]['proyek'] as $rows)
{
$nama = $rows->nama_proyek;
i++;
}
i've tested $nama_desa[0] and $nama_desa[1] and they have value returned (the value is "Kranon" and "Wulung") and i use the value like $Kranon['proyek'] and theres no error and returned the value that i want, but when i combined it with $nama_desa[$i]['proyek'] i got this error.
`
Please help, thanks in advance
You only push $row->nama_desa to $nama_desa. and try to get ['proyek'] from $nama_desa?
As you explained above, you getting value with this $nama_desa[1] but you trying to access this key $nama_desa[$i]['proyek'] which means its looking for $nama_desa[1]['proyek'] which is not exist.
Just do
print_r($name_desa);die;
You will find there is no key present with the name of 'proyek' on $name_desa[1] (key '1' i have only given for example. It can be any number of key)
I guess you will get your value by accessing this $nama_desa['proyek'] OR You will get idea with print result.
I have just found my solution.
I always getting an error whenever i want to pass variable that refers another value into foreach, so I modified my controller so I can pass the value into foreach in View directly. And I moved kind of "get-data-from-API" from Controller into View.
My Controller :
$datakonten['getAllDesa'] = $this->M_desa->getAllDesa($idStatus);
$data['content'] = $this->load>view('public/konten/v_home',$datakonten,TRUE);
My View :
foreach($getAllDesa as $rows)
{
$proyek = json_decode($this->curl->simple_get($rows->alamat_api_lelang));
foreach($proyek as $baris)
{
$namaProyek = $baris->nama_proyek;
?>
Nama Proyek : <?php echo $namaProyek;?></br>
<?php
}
}

Generate MS word document in Joomla

What I try to accomplish:
Admin creates MS Word document with placeholders that will be filled with data from Joomla database
Admin uploades MS Word file to Joomla and connects it with SQL statement
User execute "Generate MS Word" function and gets MS Word document filled with data from database.
Is there any components for Joomla that does this?
I have done this in my application using Interop libraries.
recently I've done this for a joomla component using phpdocx and pclzip libraries, where
a *.docx file is generated from a template file.
Config:
$params = Object with form data; // data from requeest
$template = 'xml_file_name'; // jfrom xml file name and *.docx template file name
$pl = '#'; // place holder prefix & suffix: (example: #PLACEHOLDER#)
$date_placehold = '#DATE#'; // will be replaced with current date
$date_formt = 'F j, Y'; // php date format
$template_path = JPATH_COMPONENT_SITE .DS.'templates'.DS.$template.'.docx';
$temp_dir = JPATH_ROOT.DS.'tmp'.DS.'phpdocx-temp-dir'; // + write access
$output_mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
$filename = $params->first_name .' - '. $params->second_name.'.docx';
// get names of all form fields of type 'list' from xml file
$lists = (array) ComponentHelper::getJFormLists($template);
// get all field names from the xml file
$fields = (array) ComponentHelper::getJFormFieldsNames($template);
Initialize variables:
$doc =& JFactory::getDocument();
$doc->setMimeEncoding($output_mime);
// require phpdocx class
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'pclzip.lib.php');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'phpdocx.php');
$phpdocx = new phpdocx($template_path, $temp_dir);
bind form fields with user params:
foreach($params as $field => $value)
{
if(array_key_exists($field,$lists) && is_array($lists[$field]) && array_key_exists($value, $lists[$field]) )
{
// if the field is JFormInput with type "list" its value is not important but its label
$var = $lists[$field][$value];
} else {
$var = $value;
}
// use openxml carriage return on new lines
if(strpos($var, "\n")) {
$var = str_replace("\n", '<w:br/>', $var);
}
$fields[$field] = $var;
}
foreach application form fields:
foreach($fields as $field => $value)
{
// replace placeholder with form value
$phpdocx->assign($pl.strtoupper($field).$pl, $value);
}
// assign date for filled-in applications
if(!empty($date_placehold)
{
$phpdocx->assign($date_placehold, date($date_formt));
}
output the file:
$phpdocx->stream($filename, $output_mime);
return true;

Resources