hi all im new ish to php and new to stack overflow but do have some knowledge in php what im trying to do is get one value from my returned array call from an api function is
$character->getSlot('head');
using print_r gives me:
Array (
[icon] => http://url to image location
[name] => Wizard's Petasos
[slot] => head )
if i echo $character->getSlot('head', 'name); gives me C:\xampp\htdocs\test\index.php on line 19 and just returns the word Array
here is the section of index.php
<?php
include('api.php');
// Call API
$API = new LodestoneAPI();
// Search for: Demonic Pagan on Sargatanas
$character = $API->get(array(
"name" => "Darka Munday",
"server" => "Ragnarok"
));
// Basic character data
echo "Character ID: " . $character->getID();
$ID = $character->getID();
$API->parseProfile($ID);
$Character = $API->getCharacterByID($ID);
echo $character->getSlot('head', 'name');
and the section of the api just in case
// GEAR
public function setGear($Array)
{
$this->Gear['slots'] = count($Array);
$GearArray = NULL;
// Loop through gear equipped
$Main = NULL;
foreach($Array as $A)
{
// Temp array
$Temp = array();
// Loop through data
$i = 0;
foreach($A as $Line)
{
// Item Icon
if (stripos($Line, 'socket_64') !== false) { $Data = trim(explode('"', $A[$i + 1])[1]); $Temp['icon'] = $Data; }
if (stripos($Line, 'item_name') !== false) { $Data = trim(str_ireplace(array('>', '"'), NULL, strip_tags(html_entity_decode($A[$i + 2])))); $Temp['name'] = htmlspecialchars_decode(trim($Data), ENT_QUOTES); }
if (stripos($Line, 'item_name') !== false) {
$Data = htmlspecialchars_decode(trim(html_entity_decode($A[$i + 3])), ENT_QUOTES);
if (
strpos($Data, " Arm") !== false ||
strpos($Data, " Grimoire") !== false ||
strpos($Data, " Tool") !== false
)
{ $Main = $Data; $Data = 'Main'; }
$Temp['slot'] = strtolower($Data);
}
// Increment
$i++;
}
// Slot manipulation
$Slot = $Temp['slot'];
if (isset($GearArray[$Slot])) { $Slot = $Slot . 2; }
// Append array
$GearArray['numbers'][] = $Temp;
$GearArray['slots'][$Slot] = $Temp;
}
// Set Gear
$this->Gear['equipped'] = $GearArray;
// Set Active Class
$classjob = str_ireplace('Two-Handed ', NULL, explode("'", $Main)[0]);
$this->Stats['active']['class'] = $classjob;
if (isset($this->Gear['soul crystal'])) { $this->Stats['active']['job'] = str_ireplace("Soul of the ", NULL, $this->Gear['soul crystal']['name']); }
}
public function getGear() { return $this->Gear; }
public function getEquipped($Type) { return $this->Gear['equipped'][$Type]; }
public function getSlot($Slot) { return $this->Gear['equipped']['slots'][$Slot]; }
the solution to this is probably really simple and im being really dumb but any help would be great :) thanks in advance
public function getSlot($Slot) {
return $this->Gear['equipped']['slots'][$Slot];
}
getSlot method have only one argument. You are passing another argument but getSlot method returns array.
You can do like this :
public function getSlot($Slot, $param = null) {
if(empty($param)) {
return $this->Gear['equipped']['slots'][$Slot];
} else {
if(isset($this->Gear['equipped']['slots'][$Slot][$param] )) {
return $this->Gear['equipped']['slots'][$Slot][$param];
} else {
return null;
}
}
}
OR
echo $character->getSlot('head')['name'] // If version is >= 5.4.*
If version < 5.4.*
$slot = $character->getSlot('head');
echo $slot['name'];
Related
I've faced funny bug when modifying the e-store engine:
// ...
$this->toolbar_title[] = 'Products';
// ...
print_r($this->toolbar_title);
/*
Array (
[0] => Products
)
*/
$this->toolbar_title[] = 'Filtered by: name';
print_r($this->toolbar_title);
/*
Array
(
[0] => Products
[2] => Filtered by: name
)
*/
// ...
wat??? where is the "1" index??
Tried to reproduce this in clean stand-alone php script - nope! the added element has index "1" as expected. but when doing the same within the engine code - new element has index "2".
There are no setters, no "[]" overloading found, even no any access to the $this->toolbar_title elements by index, only pushing via [];
What the magic is this? What and where should I seek to find the reason?
PHP 5.6, PrestaShop 1.6 engine.
Thanks a lot in advance for any clue.
UPD: the exact code fragment from engine
if ($filter = $this->addFiltersToBreadcrumbs()) {
echo'131-';print_r($this->toolbar_title);
$this->toolbar_title[] = $filter;
echo'132-';var_dump($this->toolbar_title);
}
where addFiltersToBreadcrumbs returns the string and make NO any access to toolbar_title
UPD2:
public function addFiltersToBreadcrumbs()
{
if ($this->filter && is_array($this->fields_list)) {
$filters = array();
foreach ($this->fields_list as $field => $t) {
if (isset($t['filter_key'])) {
$field = $t['filter_key'];
}
if (($val = Tools::getValue($this->table.'Filter_'.$field)) || $val = $this->context->cookie->{$this->getCookieFilterPrefix().$this->table.'Filter_'.$field}) {
if (!is_array($val)) {
$filter_value = '';
if (isset($t['type']) && $t['type'] == 'bool') {
$filter_value = ((bool)$val) ? $this->l('yes') : $this->l('no');
} elseif (isset($t['type']) && $t['type'] == 'date' || isset($t['type']) && $t['type'] == 'datetime') {
$date = Tools::unSerialize($val);
if (isset($date[0])) {
$filter_value = $date[0];
if (isset($date[1]) && !empty($date[1])) {
$filter_value .= ' - '.$date[1];
}
}
} elseif (is_string($val)) {
$filter_value = htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
}
if (!empty($filter_value)) {
$filters[] = sprintf($this->l('%s: %s'), $t['title'], $filter_value);
}
} else {
$filter_value = '';
foreach ($val as $v) {
if (is_string($v) && !empty($v)) {
$filter_value .= ' - '.htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}
}
$filter_value = ltrim($filter_value, ' -');
if (!empty($filter_value)) {
$filters[] = sprintf($this->l('%s: %s'), $t['title'], $filter_value);
}
}
}
}
if (count($filters)) {
return sprintf($this->l('filter by %s'), implode(', ', $filters));
}
}
}
For php, if you unset one index in array, the index will appear discontinuous growth.
$this->toolbar_title = array_values($this->toolbar_title);
will rebuild the index.
Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.
Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>
I recently inherited a RSS/XML parser, and while it seems to work really good, I'm finding some things are missing.
For instance, pulling in a RSS feed from a blog. It's missing all the categories in the items. It shows as each item having only one category when in reality it should show as having a multitude of categories.
Link to Demo: http://dev.o7t.in/rss/
Link to Actual Feed: http://o7thblog.com/feed/
You can see how the first item in the feed itself has 8 total categories in the first item. (may need to view source)
However, in the Demo you can see that it only shows 1 category
Here is my entire code for the class:
<?php
class o7thRssFeedPuller{
public $FeedUrl = ''; // URL of the feed to pull in
public $ReturnJson = false; // Return the array as a JSON encoded string instead?
public $MaxItems = 0; // 0 = unlimited (except by feed), only applicable to GetItems
// Internal holders
private $document;
private $channel;
private $items;
// Get the full RSS feed
public function GetRSS($includeAttributes = false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
return ($this->ReturnJson) ? json_encode($this->document) : $this->document;
}
// Return either an array or a json encoded string
return ($this->ReturnJson) ? json_encode($this->valueReturner()) : $this->valueReturner();
}
// Get the channel data
public function GetChannel($includeAttributes = false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
return ($this->ReturnJson) ? json_encode($this->channel) : $this->channel;
}
// Return either an array or a json encoded string
return ($this->ReturnJson) ? json_encode($this->valueReturner($this->channel)) : $this->valueReturner($this->channel);
}
// Get the items
public function GetItems($includeAttributes=false) {
// Pull in our feed
$this->loadParser(file_get_contents($this->FeedUrl, false, $this->randomContext()));
if($includeAttributes) {
// only if we are including attributes
$arr = ($this->MaxItems == 0) ? $this->items : array_slice($this->items, 0, $this->MaxItems);
return ($this->ReturnJson) ? json_encode($arr) : $arr;
}
// Return either an array or a json encoded string
$arr = ($this->MaxItems == 0) ? $this->valueReturner($this->items) : array_slice($this->valueReturner($this->items), 0, $this->MaxItems);
return ($this->ReturnJson) ? json_encode($arr) : $arr;
}
// -------------------------------------------------------------------------------------------------
// Internal Methods
private function loadParser($rss=false) {
if($rss) {
$this->document = array();
$this->channel = array();
$this->items = array();
$DOMDocument = new DOMDocument;
$DOMDocument->strictErrorChecking = false;
$DOMDocument->loadXML($rss);
$this->document = $this->extractDOM($DOMDocument->childNodes);
}
}
private function valueReturner($valueBlock=false) {
if(!$valueBlock) {
$valueBlock = $this->document;
}
foreach($valueBlock as $valueName => $values) {
if(isset($values['value'])) {
$values = $values['value'];
}
if(is_array($values)) {
$valueBlock[$valueName] = $this->valueReturner($values);
} else {
$valueBlock[$valueName] = $values;
}
}
return $valueBlock;
}
private function extractDOM($nodeList,$parentNodeName=false) {
$itemCounter = 0;
foreach($nodeList as $values) {
if(substr($values->nodeName,0,1) != '#') {
if($values->nodeName == 'item') {
$nodeName = $values->nodeName.':'.$itemCounter;
$itemCounter++;
} else {
$nodeName = $values->nodeName;
}
$tempNode[$nodeName] = array();
if($values->attributes) {
for($i=0;$values->attributes->item($i);$i++) {
$tempNode[$nodeName]['properties'][$values->attributes->item($i)->nodeName] = $values->attributes->item($i)->nodeValue;
}
}
if(!$values->firstChild) {
$tempNode[$nodeName]['value'] = $values->textContent;
} else {
$tempNode[$nodeName]['value'] = $this->extractDOM($values->childNodes, $values->nodeName);
}
if(in_array($parentNodeName, array('channel','rdf:RDF'))) {
if($values->nodeName == 'item') {
$this->items[] = $tempNode[$nodeName]['value'];
} elseif(!in_array($values->nodeName, array('rss','channel'))) {
$this->channel[$values->nodeName] = $tempNode[$nodeName];
}
}
} elseif(substr($values->nodeName,1) == 'text') {
$tempValue = trim(preg_replace('/\s\s+/',' ',str_replace("\n",' ', $values->textContent)));
if($tempValue) {
$tempNode = $tempValue;
}
} elseif(substr($values->nodeName,1) == 'cdata-section'){
$tempNode = $values->textContent;
}
}
return (!isset($tempNode)) ? null : $tempNode;
}
// Load in a random header to pass
private function randomContext() {
$headerstrings = array();
$headerstrings['User-Agent'] = 'Mozilla/5.0 (Windows; U; Windows NT 5.'.rand(0,2).'; en-US; rv:1.'.rand(2,9).'.'.rand(0,4).'.'.rand(1,9).') Gecko/2007'.rand(10,12).rand(10,30).' Firefox/2.0.'.rand(0,1).'.'.rand(1,9);
$headerstrings['Accept-Charset'] = rand(0,1) ? 'en-gb,en;q=0.'.rand(3,8) : 'en-us,en;q=0.'.rand(3,8);
$headerstrings['Accept-Language'] = 'en-us,en;q=0.'.rand(4,6);
$setHeaders = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'."\r\n".
'Accept-Charset: '.$headerstrings['Accept-Charset']."\r\n".
'Accept-Language: '.$headerstrings['Accept-Language']."\r\n".
'User-Agent: '.$headerstrings['User-Agent']."\r\n";
$contextOptions = array(
'http'=>array(
'method'=>"GET",
'header'=>$setHeaders
)
);
return stream_context_create($contextOptions);
}
}
?>
And for the demo page:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/rss/o7th.rss.feed.puller.php');
$fp = new o7thRssFeedPuller();
$fp->FeedUrl = 'http://o7thblog.com/feed';
$fp->MaxItems = 2;
echo '<table width="100%" cellpadding="0" cellspacing="0">';
echo ' <tr>';
echo ' <td>';
echo ' <textarea cols="120" rows="30">';
print_r($fp->GetItems());
echo ' </textarea>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
?>
So, I assume that the issue lies somewhere in either the valueReturner method or the extractDOM method, but I am just not sure where, nor what I can do to get all the categories in the returned array.
Can you help?
I would suggest using SimpleXML to parse the feed.
Here is how you can do it:
$feed_url = 'http://o7thblog.com/feed/';
$feed = simplexml_load_file($feed_url, null, LIBXML_NOCDATA);
$channel = $feed->channel;
echo "<h1>{$channel->title}</h1>\n";
echo "{$channel->description}\n";
echo "<dl>\n";
foreach ($channel->item as $item) {
echo "<dt>{$item->title}</dt>\n"
. "<dd style=\"margin-bottom: 30px;\"><div style=\"font-size: small;\">{$item->pubDate}</div>\n"
. "<div>{$item->description}</div>\n"
. "Categories: <strong>".implode('</strong>, <strong>', (array) $item->category) . "</strong>\n</dd>";
}
echo "</dl>\n";
Above shows you all categories.
You have written a custom parser for what you can do simply with one line of code!
$feed = (array) simplexml_load_file('http://o7thblog.com/feed/', null, LIBXML_NOCDATA);
Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks