Cannot solve Requests_Exception_Transport_cURL [ PHP & Wordpress Error] - php

I'm getting "Undefined property: Requests_Exception_Transport_cURL::$status_code" error and failed to solve it.
private function do_bulk_api_call( $endpoint, $data=array(), $version=0 ) {
if( !$this->cmcapi['status'] )
return false;
$final_api_data = $bulk_requests = array();
$options = get_option( 'cmcapi' );
$version = $version ? $version : $this->cmcapi['version'];
$bulk_url = $this->cmcapi['url'] . $version . $endpoint;
if( $data && is_array($data) ):
foreach ($data as $k => $chunk) {
// TEMP condition
// if( $k > 0 )
// continue;
$bulk_requests[] = array(
'type' => 'GET',
'timeout' => 90,
'url' => $bulk_url,
'headers' => array(
'X-CMC_PRO_API_KEY' => $this->cmcapi['key'],
),
'data' => array( 'id' => implode(',',$chunk) )
);
}
endif;
$requests = Requests::request_multiple( $bulk_requests );
foreach ($requests as $key => $response) {
if($response->status_code !== 200) {
continue;
}
$res_decoded = json_decode($response->body);
$this->kte_shipment_api_results[$key] = array();
$final_api_data = array_merge( (array) $final_api_data, (array) $response->data );
if( !$res_decoded->status->error_code && is_object($res_decoded->data) ){
$final_api_data = array_merge( (array) $final_api_data, (array) $res_decoded->data );
}
}
return $final_api_data;
}
By the way, this code is from other teammate and he is gone now so I cannot ask to him.

Related

recursion function on tree data to get path

I want to write function which receive me path to top element, but I can't figure out how it should work..
My example data:
$data = array(
3546456 => array(
5345345,
12312312,
56456546,
),
12312312 => array(
34534534,
5675675,
8678678,
),
567978 => array(
234,
756756,
8678678,
),
);
//I have function to return parent.
$parents = getParents(8678678); // eg. $object_id = 8678678 - return [12312312, 567978] , $object_id = 12312312 - return [3546456]
// and my recursion function I tried.
function getObjectPath($object_id) {
if ($object_id == null) {
return [];
}
$parents = getObjectParents($object_id);
foreach ($parents as $parent) {
return array($object_id => getObjectPath($parent->nid));
}
}
It doesn't work way I need, on the return in getObjectPath(8678678) I'd like to have return array like that:
array(
3546456 => array(
12312312 => array(
8678678
)
),
567978 => array(
8678678
)
);
I think you almost got it, need to have some other check before returning
$data = array(
3546456 => array(
5345345,
12312312,
56456546,
),
12312312 => array(
34534534,
5675675,
8678678,
),
567978 => array(
234,
756756,
8678678,
),
);
//I have function to return parent.
$parents = getObjectPath(8678678, $data); // eg. $object_id = 8678678 - return [12312312, 567978] , $object_id = 12312312 - return [3546456]
echo "<pre>";
print_r($parents);
// and my recursion function I tried.
function getParents($object_id, $data) {
$return = [];
foreach($data as $key => $value) {
if(in_array($object_id, $value)) {
$return[] = $key;
}
}
return $return;
}
// and my recursion function I tried.
function getObjectPath($object_id, $data) {
$return = [];
$parents = getParents($object_id, $data);
foreach($parents as $parent) {
$temp = getObjectPath($parent, $data);
if(!empty($temp)) {
$return[key($temp)][$parent] = $object_id;
} else {
$return[$parent] = $object_id;
}
}
return $return;
}

PHP SoapClient not getting substructures

I'm trying to get the response of A SOAP Service, but I can't get the subcollections data.
When I call the ws method using a soap client software I get the next response:
<WSGLMSuit.METHODNAME xmlns="http://tempuri.org/">
<Sdtpolizadetalle>
<Empresa>1</Empresa>
<DscEmpresa>TEST</DscEmpresa>
<Rama>22</Rama>
<DscRama>COMBINADO FAMILIAR</DscRama>
<Poliza>000000</Poliza>
<DscRiesgo/>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Productor>3311</Productor>
<NombreProductor>TEST</NombreProductor>
<Tomador>
<CodTomador>336028</CodTomador>
<NombreTomador>TEST</NombreTomador>
<Domicilio>SAAVEDRA 1174 Dpto. 0</Domicilio>
<Localidad>TRES ARROYOS</Localidad>
<CodigoPostal>7500</CodigoPostal>
</Tomador>
<DscMoneda>PESOS</DscMoneda>
<CantidadCuotas>3</CantidadCuotas>
<Suplementos>
<Suplemento>
<Suplemento>0</Suplemento>
<TipoOperacion>02</TipoOperacion>
<SubTipoOperacion>000</SubTipoOperacion>
<DscOperacion>GENERAL</DscOperacion>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Prima>2515.95</Prima>
<Premio>3104.68</Premio>
<Cuotas>
<Cuota>
<NroCuota>1</NroCuota>
<Vencimiento>2019-03-18</Vencimiento>
<Estado>Pagada</Estado>
<Importe>519.68</Importe>
<NroCupon>1</NroCupon>
</Cuota>
<Cuota>
<NroCuota>2</NroCuota>
<Vencimiento>2019-04-18</Vencimiento>
<Estado>Vencida</Estado>
<Importe>517.00</Importe>
<NroCupon>2</NroCupon>
</Cuota>
<Cuota>
<NroCuota>3</NroCuota>
<Vencimiento>2019-05-18</Vencimiento>
<Estado>Impaga</Estado>
<Importe>517.00</Importe>
<NroCupon>3</NroCupon>
</Cuota>
</Cuotas>
</Suplemento>
</Suplementos>
</Sdtpolizadetalle>
<Sesionexpirada>false</Sesionexpirada>
</WSGLMSuit.METHODNAMEResponse>
So, I made a function in PHP with SoapClient class to make same request and get the result parsed as JSON but it doesn't giving me the "Suplementos" collection and its data.
{
"Sdtpolizadetalle": {
"Empresa": 1,
"DscEmpresa": "TEST",
"Rama": 22,
"DscRama": "COMBINADO FAMILIAR",
"Poliza": 129031,
"DscRiesgo": "",
"InicioVigencia": "2019-03-18",
"FinVigencia": "2019-09-18",
"Productor": 3311,
"NombreProductor": "TEST",
"Tomador": {
"CodTomador": 336028,
"NombreTomador": "TEST",
"Domicilio": "SAAVEDRA 1174 Dpto. 0",
"Localidad": "TRES ARROYOS",
"CodigoPostal": "7500"
},
"DscMoneda": "PESOS",
"CantidadCuotas": 3,
"Suplementos": {} // <--- HERE IS THE ISSUE
},
"Sesionexpirada": false
}
The PHP function is:
$wsdl = "http://wsdlservice.org?wsdl";
$params = $request->getParsedBody();
$options = array(
'soap_version' => SOAP_1_2,
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL,
'exceptions' => true,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE,
'encoding' => 'UTF-8'
);
$soap = new SoapClient($wsdl, $options);
$clientRes = $soap->METHODNAME($params);
return json_encode($clientRes, JSON_PRETTY_PRINT);
Finally I got a solution. I found a function for parsing XML string to Array. So what I do is get the response as XML, save it into a file and parse it with that function. Code better than words:
function xmlToArray($xml, $options = array())
{
$defaults = array(
'namespaceSeparator' => ':',
'attributePrefix' => '#',
'alwaysArray' => array(),
'autoArray' => true,
'textContent' => '$',
'autoText' => true,
'keySearch' => false,
'keyReplace' => false
);
$options = array_merge($defaults, $options);
$namespaces = $xml->getDocNamespaces();
$namespaces[''] = null;
$attributesArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
if ($options['keySearch']) $attributeName =
str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
$attributeKey = $options['attributePrefix']
. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
. $attributeName;
$attributesArray[$attributeKey] = (string)$attribute;
}
}
$tagsArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->children($namespace) as $childXml) {
$childArray = xmlToArray($childXml, $options);
list($childTagName, $childProperties) = each($childArray);
if ($options['keySearch'])
$childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
if ($prefix)
$childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
if (!isset($tagsArray[$childTagName])) {
$tagsArray[$childTagName] =
in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
? array($childProperties)
: $childProperties;
} elseif (
is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
=== range(0, count($tagsArray[$childTagName]) - 1)
) {
$tagsArray[$childTagName][] = $childProperties;
} else {
$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
}
}
}
$textContentArray = array();
$plainText = trim((string)$xml);
if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
return array(
$xml->getName() => $propertiesArray
);
}
$params = array('key' => 'value') // params needed to make the request
$options = array(
'trace' => 1,
'exceptions' => true
);
try {
$soap = new SoapClient($url, $options);
$soap->method($params); // replace method name
$xmlResponse = $soap->__getLastResponse();
} catch (Exception $e) {
die(
json_encode(
[
'error' => 'Cannot request to WS. ' . $e->getMessage()
]
)
);
// save the response into an xml file for parse
// it and return its content as json
if (file_put_contents('response.xml', $xmlResponse)) {
$xmlNode = simplexml_load_file($this->tempPath);
$arrayData = xmlToArray($xmlNode);
unlink('response.xml');
return json_encode($arrayData, JSON_PRETTY_PRINT);
} else {
return json_encode(['error' => 'Error saving the response into file.']);
}

How to separate php array result

I have a problem where I am coding a server status for my game server. It works fine, but there is one problem… The array output is in one line like this:
Array ( [online] => 1 [error] => [hostname] => chromaville.com [port] => 25565 [version] => 1.12 [software] => CraftBukkit on Bukkit 1.12-R0.1-SNAPSHOT [game_type] => SMP [game_name] => MINECRAFT [players] => 0 [max_players] => 1000 [player_list] => )
instead of a list like so:
Array (
[online] => 1
[error] =>
[hostname] => chromaville.com
[port] => 25565 [version] => 1.12
[software] => CraftBukkit on Bukkit 1.12-R0.1-SNAPSHOT
[game_type] => SMP
[game_name] => MINECRAFT
[players] => 0
[max_players] => 1000
[player_list] =>
);
Is it possible to somehow do it like this? Thank you! (Sorry if my spelling is bad, I haven’t slept in a long time and its 5:19 am currently…)
Here’s my code:
index.php:
<?php
require 'MCQuery.php';
$status = new MCQuery();
$array = ($status->GetStatus( 'chromaville.com', 25565 )-Response() );
print_r($array)
?>
mcquery.php:
<?php
class MCQuery
{
const STATISTIC = 0x00;
const HANDSHAKE = 0x09;
private $Socket;
private $error;
private $host;
private $Info;
private $Players;
//public methods
public function __construct()
{
}
public function GetStatus($Host='127.0.0.1', $Port=25565, $Timeout=2)
{
$this->Clear();
$this->host=$Host;
if( !is_int( $Timeout ) || $Timeout < 0 )
{
$this->error="Invalid timeout";
return $this;
}
$this->Socket = #fsockopen( 'udp://' . $Host, (int)$Port, $ErrNo, $ErrStr, $Timeout );
if( $ErrNo || $this->Socket === false )
{
$this->error="Socket error";
return $this;
}
#stream_set_timeout( $this->Socket, $Timeout );
#stream_set_blocking( $this->Socket, true );
$this->Query();
#fclose( $this->Socket );
return $this;
}
public function Response()
{
return array(
'online'=>$this->error==null?true:false,
'error'=>$this->error,
'hostname'=>$this->host,
'port'=>isset($this->Info['HostPort'])?$this->Info['HostPort']:null,
'version'=>isset($this->Info['Version'])?$this->Info['Version']:null,
'software'=>isset($this->Info['Software'])?$this->Info['Software']:null,
'game_type'=>isset($this->Info['GameType'])?$this->Info['GameType']:null,
'game_name'=>isset($this->Info['GameName'])?$this->Info['GameName']:null,
'players'=>isset($this->Info['Players'])?$this->Info['Players']:null,
'max_players'=>isset($this->Info['MaxPlayers'])?$this->Info['MaxPlayers']:null,
'player_list'=>isset($this->Players)?$this->Players:null,
);
}
//private methods
private function Clear()
{
$this->Socket=null;
$this->error=null;
$this->host=null;
$this->Info=null;
$this->Players=null;
}
private function Query()
{
//challenge
$Data = $this->WriteData( self :: HANDSHAKE );
if( $Data === false )
{
$this->error="Failed to receive challenge";
}
$challenge=pack( 'N', $Data );
$Data = $this->WriteData( self :: STATISTIC, $challenge . pack( 'c*', 0x00, 0x00, 0x00, 0x00 ) );
if( !$Data )
{
$this->error="Failed to receive status";
}
$Last = '';
$Info = Array( );
$Data = substr( $Data, 11 ); // splitnum + 2 int
$Data = explode( "\x00\x00\x01player_\x00\x00", $Data );
if( count( $Data ) !== 2 )
{
$this->error="Failed to parse server's response";
}
$Players = #substr( $Data[ 1 ], 0, -2 );
$Data = explode( "\x00", $Data[ 0 ] );
// Array with known keys in order to validate the result
// It can happen that server sends custom strings containing bad things (who can know!)
$Keys = Array(
'hostname' => 'HostName',
'gametype' => 'GameType',
'version' => 'Version',
'plugins' => 'Plugins',
'map' => 'Map',
'numplayers' => 'Players',
'maxplayers' => 'MaxPlayers',
'hostport' => 'HostPort',
'hostip' => 'HostIp',
'game_id' => 'GameName'
);
foreach( $Data as $Key => $Value )
{
if( ~$Key & 1 )
{
if( !array_key_exists( $Value, $Keys ) )
{
$Last = false;
continue;
}
$Last = $Keys[ $Value ];
$Info[ $Last ] = '';
}
else if( $Last != false )
{
$Info[ $Last ] = $Value;
}
}
// Ints
$Info[ 'Players' ] = $this->error==null?#intval( $Info[ 'Players' ] ):null;
$Info[ 'MaxPlayers' ] = $this->error==null?#intval( $Info[ 'MaxPlayers' ] ):null;
$Info[ 'HostPort' ] = $this->error==null?#intval( $Info[ 'HostPort' ] ):null;
// Parse "plugins", if any
if( #$Info[ 'Plugins' ] )
{
$Data = explode( ": ", $Info[ 'Plugins' ], 2 );
$Info[ 'RawPlugins' ] = $Info[ 'Plugins' ];
$Info[ 'Software' ] = $Data[ 0 ];
if( count( $Data ) == 2 )
{
$Info[ 'Plugins' ] = explode( "; ", $Data[ 1 ] );
}
}
else
{
$Info[ 'Software' ] = $this->error==null?'Vanilla':null;
}
$this->Info = $Info;
if( $Players )
{
$this->Players = explode( "\x00", $Players );
}
}
private function WriteData( $Command, $Append = "" )
{
$Command = pack( 'c*', 0xFE, 0xFD, $Command, 0x01, 0x02, 0x03, 0x04 ) . $Append;
$Length = strlen( $Command );
if( $Length !== #fwrite( $this->Socket, $Command, $Length ) )
{
$this->error="Failed to write on socket";
}
$Data = #fread( $this->Socket, 4096 );
if( $Data === false )
{
$this->error="Failed to read from socket";
}
if( strlen( $Data ) < 5 || $Data[ 0 ] != $Command[ 2 ] )
{
$this->error="Strlen error";
}
return substr( $Data, 5 );
}
}
?>
use echo "<pre>"; before your print_r function. Like as below:
<?php
require 'MCQuery.php';
$status = new MCQuery();
$array = ($status->GetStatus( 'chromaville.com', 25565 )->Response() );
echo "<pre>";
print_r($array)
?>
I think you were trying to debug your code, not trying to display production result by print_r

Data tables filters, search Not functioning mongodb php

In this code filter, search and pagination not functioning i have tried myself but it didn't work so please check the code give me any solution or any reference regarding to this query. Even any related to this code files or docs it will be helpful for me to pursue the concept
<?php
mb_internal_encoding('UTF-8');
$database = 'test';
$collection = 'user';
/**
* MongoDB connection
*/
try{
// Connecting to server
$m = new MongoClient( );
}catch(MongoConnectionException $connectionException){
print $connectionException;
exit;
}
$m_collection = $m->$database->$collection;
$input = $fields = $totalRecords = $data = array();
$input = & $_REQUEST;
$fields = array('id', 'name', 'email', 'gender,');
// Input method (use $_GET, $_POST or $_REQUEST)
/**
* Handle requested DataProps
*/
// Number of columns being displayed (useful for getting individual column search info)
$iColumns = & $input['iColumns'];
// Get mDataProp values assigned for each table column
$dataProps = array();
for ($i = 0; $i < $iColumns; $i++) {
$var = 'mDataProp_'.$i;
if (!empty($input[$var]) && $input[$var] != 'null') {
$dataProps[$i] = $input[$var];
}
}
$searchTermsAny = array();
$searchTermsAll = array();
if ( !empty($input['sSearch']) ) {
$sSearch = $input['sSearch'];
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ($input['bSearchable_'.$i] == 'true') {
if ($input['bRegex'] == 'true') {
$sRegex = str_replace('/', '\/', $sSearch);
} else {
$sRegex = preg_quote($sSearch, '/');
}
$searchTermsAny[] = array(
$dataProps[$i] => new MongoRegex( '/'.$sRegex.'/i' )
);
}
}
}
// Individual column filtering
for ( $i=0 ; $i < $iColumns ; $i++ ) {
if ( $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
if ($input['bRegex_'.$i] == 'true') {
$sRegex = str_replace('/', '\/', $input['sSearch_'.$i]);
} else {
$sRegex = preg_quote($input['sSearch_'.$i], '/');
}
$searchTermsAll[ $dataProps[$i] ] = new MongoRegex( '/'.$sRegex.'/i' );
}
}
$searchTerms = $searchTermsAll;
if (!empty($searchTermsAny)) {
$searchTerms['$or'] = $searchTermsAny;
}
$totalRecords =$m_collection->count();
$cursor = $m_collection->find($searchTerms, $fields);
/**
* Paging
*/
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
$cursor->limit( $input['iDisplayLength'] )->skip( $input['iDisplayStart'] );
}
/**
* Ordering
*/
if ( isset($input['iSortCol_0']) ) {
$sort_fields = array();
for ( $i=0 ; $i<intval( $input['iSortingCols'] ) ; $i++ ) {
if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
$field = $dataProps[ intval( $input['iSortCol_'.$i] ) ];
$order = ( $input['sSortDir_'.$i]=='desc' ? -1 : 1 );
$sort_fields[$field] = $order;
}
}
$cursor->sort($sort_fields);
}
foreach ( $cursor as $doc )
{ $name = ''.$doc['name'].'';
$data[] = array($name, $doc['email'], $doc['gender]);
}
/**
* Output
*/
$json_data = array(
"draw"=> intval( $input['draw'] ),
"recordsTotal" =>intval ($totalRecords),
"recordsFiltered" => intval($totalRecords),
"data" => $data
);
echo json_encode( $json_data );
And also i need to Join two tables as given below.
Table 1
Table 2
I am doing it like:
$('#datatable_emp_details').dataTable({
"sServerMethod": "POST",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "get_data.php"
});
get_data.php:
<?php
$mongo = new MongoClient();
$database = $mongo->selectDb('dbtest');
$collection = $database->selectCollection('empDetails');
$skip = (int)$_REQUEST['iDisplayStart'];
$limit = (int)$_REQUEST['iDisplayLength'];
$search = $_REQUEST['sSearch'];
$sortIndex = $_REQUEST['iSortCol_0'];
$sortArray = array('emp_id', 'first_name', 'last_name', 'position', 'email', 'office', 'start_date', 'age', 'salary', 'projects'
);
$sortByCol = $sortArray[$sortIndex];
$sortTypeTxt= $_REQUEST['sSortDir_0']; // asc/desc
$sortType = -1;
if( $sortTypeTxt == 'asc' )
{
$sortType = 1;
}
if( $search != '' )
{
$condtion = array(
'$or' => array(
array('emp_id' => $search),
array('first_name'=> new MongoRegex('/'. $search .'/i')), // i for case insensitive
array('last_name' => new MongoRegex('/'. $search .'/i')),
array('position' => new MongoRegex('/'. $search .'/i')),
array('email' => new MongoRegex('/'. $search .'/i')),
array('office' => new MongoRegex('/'. $search .'/i')),
array('start_date'=> new MongoRegex('/'. $search .'/i')),
array('age' => new MongoRegex('/'. $search .'/i')),
array('salary' => new MongoRegex('/'. $search .'/i')),
array('projects' => new MongoRegex('/'. $search .'/i'))
)
);
$resultSet = $collection->find($condtion)->limit($limit)->skip($skip)->sort(array($sortByCol => $sortType));
}
else
{
$resultSet = $collection->find()->limit($limit)->skip($skip)->sort(array($sortByCol => $sortType))->sort(array($sortByCol => $sortType));
}
$data = array();
if( count( $resultSet ) > 0 )
{
foreach ($resultSet as $document)
{
$data[] = $document;
}
}
$resultSet = $collection->find();
$iTotal = count($resultSet);
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data)) {
foreach ($data as $item) {
$rec['aaData'][$k] = array(
0 => $item['emp_id'],
1 => $item['first_name'],
2 => $item['last_name'],
3 => $item['position'],
4 => $item['email'],
5 => $item['office'],
6 => $item['start_date'],
7 => $item['age'],
8 => $item['salary'],
9 => $item['projects'],
10 => 'Edit | Delete'
);
$k++;
}
}
echo json_encode($rec);
exit;
?>
Github repository link

how to remove last comma (,) from this string without using built-in functions like "rtrim" and "substr"

How to remove last comma (,) from array?
without using inbuilt functions like rtrim and substr
public function update( $table_name="", $fields_value=array(), $where="" ){
//if( $table_name == "" || empty($fields_value) || $where == "" ) return false;
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$column_value_string = "";
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string .= " `$col_name`='$col_value' ,";
}
echo rtrim($column_value_string,",")."<br><br><br><br>";
return;
To create a comma-seprated list, put things into an array and then implode it:
$column_value = array();
foreach( $fields_values as $col_name => $col_value ) {
$column_value []= "`$col_name`='$col_value'";
}
$column_value_string = implode(", ", $column_value);
Also do note that you must escape values when generating SQL commands dynamically.
You can done this with counter in your loop Try
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$count = count($fields_values);
$i=1;
$column_value_string = "";
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string .= " `$col_name`='$col_value'";
if($i <$count) {
$column_value_string .= ',';
}
$i++;
}
echo $column_value_string;
output :-
`name`='Vikrant', `class`='MCA', `Section`='a', `Subject`='Ele'
$array = explode(",",$ TheArray);
$array = implode(",", $array);
Short, simple.. does the trick
<?php
$str = 'test,';
if($str[strlen($str) - 1 ] == ',') $str[strlen($str) - 1] = null;
echo $str; // test
?>
Hope this will help you......
public function update( $table_name="", $fields_value=array(), $where="" ){
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$column_value_string = array();
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string[] = " `$col_name`='$col_value'";
}
echo implode(',',$column_value_string);
You can achieve desired result by following
public function update( $table_name="", $fields_value=array(), $where="" ){
//if( $table_name == "" || empty($fields_value) || $where == "" ) return false;
$fields_values = array(
'name' => 'Vikrant',
'class' => 'MCA',
'Section' => 'a',
'Subject' => 'Ele'
);
$column_value_string = "";
foreach( $fields_values as $col_name => $col_value ) {
$column_value_string .= ($column_value_string == ""?'':', ')." `$col_name`='$col_value'";
}
echo $column_value_string."<br><br><br><br>";
return;
}

Categories