Hy, I designed an array, and I need some help because I've got aaaloot of headaches. Can anyone give me a simple idea how to work with this in a simple way?
Most of the errors when I try to add some values in my array are array offset error.
My array:
$info = array
(
"id" => "",
"city" => "",
"university" => array
(
"name" => "",
"address" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
"faculty" => array
(
"name" => "",
"adress" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
)
)
);
CODE:
<?php
// HTML DOM PARSER LIBRARY
include('hdp.php');
//error_reporting(false);
/*
* Returns an array with field associative name and
* extracted value, using a specified delimiter.
*/
function extractField($str, $delim)
{
$val = '';
// All possible fields
$posFlds = array
(
'Adresa' => 'address',
'Telefon' => 'phone',
'Fax' => 'fax',
'Email' => 'email',
'Website' => 'website',
'Tip' => 'type'
);
foreach($posFlds as $fldName => $assocName)
{
if(strstr($str,$fldName))
{
$val = #explode($delim,$str);
if (!$val[1])
{
print 'Delimiter `'.$delim.'` not found!';
return false;
}
return array($assocName, $val[1]);
}
}
return false;
}
// DB->Table query structure
$info = array
(
"id" => "",
"city" => "",
"university" => array
(
"name" => "",
"address" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
"faculty" => array
(
"name" => "",
"adress" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
)
)
);
// City identifier
$cityid = 0;
// Rows, columns and deep identifiers
$i = 0; $j = 0; $k = 0;
// Base, secondary and third crawl url
$baseUrl = 'XXX';
$secondaryUrl = ''; $thirdUrl ='';
// Html contents without stripped tags (as is)
$htmlCu = file_get_html($baseUrl);
$htmltUn = ''; $htmltFa = '';
// Selectors for third level deep check
$selectCu = $htmlCu->find('td[width="100%"] table td');
$selectUn = ''; $selectFa ='';
// Text formats (raw and cleaned)
$rtext =''; $ftext = '';
// Contoare
$a=0; $b=0; $c=0;
// Select each row from parent td -> child table -> child td
foreach($selectCu as $row)
{
// Skip first row result
if($i != 0)
{
$rtext = $row->plaintext;
$ftext = trim($rtext,' • ');
if($ftext != '-')
{
// If string contains a dot it is a city
if(strstr($rtext, '•'))
{
print "CITY = ".$ftext."<br>";
$cityid++;
$info[$a]["city"] = $ftext;
}
// If string is not a city, then is a university
else
{
$info[$a]["city"][$b]['university']['name'] = $ftext;
echo "<b>----ID [".$i."]; NAME:</b> ".$ftext."<br>";
$secondaryUrl = $row->find('a',0)->href;
$htmlUn = file_get_html($secondaryUrl);
$selectUn = $htmlUn->find('td[width="100%"] table tr');
foreach($selectUn as $col)
{
// Skip first row result
if($j != 0)
{
$rtext = $col->plaintext;
$ftext = trim($rtext,' • ');
echo "--------ID[".$j."] NAME: <b>".$ftext."</b>; TYPE: ".gettype($col)."<br>";
// key 0 -> associative name; key 1 -> value
$field = extractField($ftext,': ');
if($field)
{
echo "--------<b>Field name:</b> ".$field[0]."<b>, value:</b> ".$field[1]."<br>";
}
/////////////////////////////TESTTTTTT ZONEEEEEEEEEEEEEEE/////////////////////////////
// If string contains a dot it is a faculty
if(strstr($rtext, '•'))
{
$thirdUrl = $col->find('a',0)->href;
$htmlFa = file_get_html($thirdUrl);
$selectFa = $htmlFa->find('td[width="100%"] table tr');
foreach($selectFa as $deep)
{
$rtext = $deep->plaintext;
$ftext = trim($rtext,' • ');
//echo "------------id[".$k."] <-> <b>".$ftext."</b> <-> ".gettype($deep)."<br>";
$field = extractField($ftext,': ');
if($field)
{
echo "------------<b>Field name:</b> ".$field[0]."<b>, value:</b> ".$field[1]."<br>";
}
$k++;
}
echo "<br><br>";
}
}
$j++;
}
echo "<br><br>";
}
}
}
$i++;
if($cityid == 2) break;
}
print "<h1>".($i-1)."</h1>";
print_r($info);
You are accessing the array the wrong way in those calls:
$info[$a]["city"] = $ftext;
$info[$a]["city"][$b]['university']['name'] = $ftext;
Correct would be:
$info["city"] = $ftext;
$info["city"]['university']['name'] = $ftext;
It seems you want to handle multiple $info-arrays. For this you have to create an array of those info-arrays.
Final and working code, if anyone fiind this usefull:
// HTML DOM PARSER LIBRARY
include('hdp.php');
error_reporting(true);
// Session to know what last city was
session_start();
if (!$_SESSION['LAST']) $_SESSION['LAST'] = NULL;
/*
* Returns an array with field associative name and
* extracted value, using a specified delimiter.
*/
function extractField($str, $delim)
{
$val = '';
// All possible fields
$posFlds = Array
(
'Adresa' => 'address',
'Telefon' => 'phone',
'Fax' => 'fax',
'Email' => 'email',
'Website' => 'website',
'Tip' => 'type'
);
foreach($posFlds as $fldName => $assocName)
{
if(strstr($str,$fldName))
{
$val = #explode($delim,$str);
if (!$val[1])
{
print 'Delimiter `'.$delim.'` not found!';
return false;
}
return array($assocName, $val[1]);
}
}
return false;
}
// Trying to connect to local server
$conn = mysqli_connect("localhost","root","","educatie") or die("Could not connect to MySQL server!");
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// DB->Table Query structure
$info = Array
(
"city" => Array
(
"name" => "",
"university" => Array
(
"name" => "",
"address" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
"faculty" => Array
(
"name" => "",
"adress" => "",
"phone" => "",
"fax" => "",
"email" => "",
"website" => "",
"type" => "",
)
),
)
);
// City identifier
$cityid = 0;
// Rows, columns and deep identifiers
$i = 0; $j = 0; $k = 0;
// Base, secondary and third crawl url
$baseUrl = 'http://infoportal.rtv.net/informatii_universitati.html';
$secondaryUrl = ''; $thirdUrl ='';
// Html contents without stripped tags (as is)
$htmlCu = file_get_html($baseUrl);
$htmltUn = ''; $htmltFa = '';
// Selectors for third level deep check
$selectCu = $htmlCu->find('td[width="100%"] table td');
$selectUn = ''; $selectFa ='';
// Text formats (raw and cleaned)
$rtext =''; $ftext = '';
// Ignore tokens
$banned = array(" ","•","""," ");
// Counters A, B and C
$a=0; $b=0; $c=0;
// Temporary variables
$tmpVar = '';
// Select each row from parent td -> child table -> child td
foreach($selectCu as $row)
{
// Skip first row result
if($i != 0)
{
$rtext = $row->plaintext;
$ftext = trim($rtext,' • ');
if($ftext != '-')
{
// If string contains a dot it is a city
if(strstr($rtext, '•'))
{
if(($_SESSION['LAST'] !== $ftext) && ($_SESSION['LAST'] !== NULL)) continue;
print "<h1>-> Oras: ".$ftext."</h1><br>";
echo "SESSION:".$_SESSION['LAST']."|<br />";
$tmpVar = $ftext;
}
// If string is not a city, then is a university
else
{
$a--;
$info[$a]['city']['name'] = $tmpVar;
$info[$a]['city']['university'][$b]['name'] = $ftext;
$secondaryUrl = $row->find('a',0)->href;
$htmlUn = file_get_html($secondaryUrl);
$selectUn = $htmlUn->find('td[width="100%"] table tr');
foreach($selectUn as $col)
{
// Skip first row result
if($j != 0)
{
$rtext = $col->plaintext;
$ftext = trim($rtext,' • ');
// key 0 -> associative name; key 1 -> value
$field = extractField($ftext,': ');
if($field)
{
if(strstr($field[1],'de stat'))
$info[$a]['city']['university'][$b][$field[0]] = 'de stat';
else
$info[$a]['city']['university'][$b][$field[0]] = $field[1];
}
/////////////////////////////TESTTTTTT ZONEEEEEEEEEEEEEEE/////////////////////////////
// If string contains a dot it is a faculty
if(strstr($rtext, '•'))
{
$tempVar = trim(str_replace($banned,'',$ftext),' ');
$thirdUrl = $col->find('a',0)->href;
$htmlFa = file_get_html($thirdUrl);
$selectFa = $htmlFa->find('td[width="100%"] table tr');
foreach($selectFa as $deep)
{
$rtext = $deep->plaintext;
$ftext = trim($rtext,' • ');
$info[$a]['city']['university'][$b]['faculty'][$c]['name'] = $tempVar;
$field = extractField($ftext,': ');
if($field)
{
if($field[0]=='website')
{
$info[$a]['city']['university'][$b]['faculty'][$c][$field[0]] = $deep->find('a',0)->href;
}
else
{
$info[$a]['city']['university'][$b]['faculty'][$c][$field[0]] = $field[1];
}
}
$k++;
}
$facName = #$info[$a]['city']['university'][$b]['faculty'][$c]['name'];
$facAddr = #$info[$a]['city']['university'][$b]['faculty'][$c]['address'];
$facPhone = #$info[$a]['city']['university'][$b]['faculty'][$c]['phone'];
$facFax = #$info[$a]['city']['university'][$b]['faculty'][$c]['fax'];
$facEmail = #$info[$a]['city']['university'][$b]['faculty'][$c]['email'];
$facWeb = #$info[$a]['city']['university'][$b]['faculty'][$c]['website'];
$facTax = #$info[$a]['city']['university'][$b]['faculty'][$c]['type'];
echo "<b>ID UNIVERSITATE:</b> ".$a."<br />";
echo "<b>Nume facultate:</b> ".$facName."<br />";
echo "<b>Adresa:</b> ".$facAddr."<br />";
echo "<b>Telefon:</b> ".$facPhone."<br />";
echo "<b>Fax:</b> ".$facFax."<br />";
echo "<b>Email:</b> ".$facEmail."<br />";
echo "<b>Pagina web:</b> ".$facWeb."<br />";
echo "<b>Tip taxa:</b> ".$facTax."<br /><br />";
mysqli_query($conn,"
INSERT INTO faculty
VALUES ('$a','$facName','$facAddr','$facPhone','$facFax','$facEmail','$facWeb','$facTax')
");
$c++;
}
}
$j++;
}
$univCity = #$info[$a]['city']['name'];
$univName = #$info[$a]['city']['university'][$b]['name'];
$univAddr = #$info[$a]['city']['university'][$b]['address'];
$univPhone = #$info[$a]['city']['university'][$b]['phone'];
$univFax = #$info[$a]['city']['university'][$b]['fax'];
$univEmail = #$info[$a]['city']['university'][$b]['email'];
$univWeb = #$info[$a]['city']['university'][$b]['website'];
$univTax = #$info[$a]['city']['university'][$b]['type'];
echo "<b>ID UNIVERSITATE:</b> ".$a."<br />";
echo "<b>Oras:</b> ".$univCity."<br />";
echo "<b>Nume universitate:</b> ".$univName."<br />";
echo "<b>Adresa:</b> ".$univAddr."<br />";
echo "<b>Telefon:</b> ".$univPhone."<br />";
echo "<b>Fax:</b> ".$univFax."<br />";
echo "<b>Email:</b> ".$univEmail."<br />";
echo "<b>Pagina web:</b> ".$univWeb."<br />";
echo "<b>Tip taxa:</b> ".$univTax."<br />";
mysqli_query($conn,"
INSERT INTO university
VALUES ('$a','$univCity','$univName','$univAddr','$univPhone','$univFax','$univEmail','$univWeb','$univTax')
");
$b++;
echo "<br><br>";
}
$a++;
}
}
// SESSION IT, IF THIS JOB IS COMPLETE
if($tmpVar) $_SESSION['LAST'] = $tmpVar;
$i++;
}
print "<h1>".($i-1)."</h1>";
print_r($info);
Related
I am getting error while updating my sales order using for each.
foreach( $_POST['productId'] as $key => $val){
$invoice_arrs = array(
"product_name" => $_POST['productname'][$key],
"purchaseQty" => $_POST['purchaseQty'][$key],
"sellingPrice" => $_POST['sellingPrice'][$key],
"discount" => $_POST['discount'][$key],
"dis_type" => $_POST['discounttype'][$key],
"total" => $_POST['total'][$key],
"net_price" => $_POST['net_price'][$key]
);
$temp=UpdateRecords("sales_order","sales_order_id=$id",$invoice_arrs,1);
//here is my update record function
function UpdateRecords($table, $condition, $updata, $debug = "") {
global $conn;
foreach ( $updata as $key => $value ) {
if ($value != "now()") {
$fv [] = "$key = \"" . "$value" . "\"";
} else {
$fv [] = "$key = " . "$value" . "";
}
}
$fv_list = trim ( implode ( ", ", $fv ) );
$query = "UPDATE $table SET " . "$fv_list" . " WHERE $condition";
if ($debug == 1) {
echo $query;
}
$result = executeQuery( $query );
if (! mysqli_affected_rows ( $conn )) {
global $errormessage;
$errormessage = mysqli_error ( $conn );
if (! empty ( $errormessage ))
return 0;
}
return 1;
}
You can try below query -
INSERT INTO $table (product_name,
purchaseQty,
sellingPrice,
discount,
dis_type,
total,
net_price)
VALUES($_POST['productname'][$key],
$_POST['purchaseQty'][$key],
$_POST['sellingPrice'][$key],
$_POST['discount'][$key],
$_POST['discounttype'][$key],
$_POST['total'][$key],
$_POST['net_price'][$key])
ON DUPLICATE KEY UPDATE product_name = VALUES($_POST['productname'][$key]),
purchaseQty = VALUES($_POST['purchaseQty'][$key]),
sellingPrice = VALUES($_POST['sellingPrice'][$key]),
discount = VALUES($_POST['discount'][$key]),
dis_type = VALUES($_POST['discounttype'][$key]),
total = VALUES($_POST['total'][$key]),
net_price = VALUES($_POST['net_price'][$key]);
I have two days trying to fix this error with this XML code:
`<OTA_VehResRQ Version="1.00">
<POS>
<Source><RequestorID ID="22" Type="90"></RequestorID></Source>
</POS>
<BookingReferenceID>
<UniqueID_Type ID="338964670"></UniqueID_Type>
</BookingReferenceID>
<VehResRQCore>
<VehRentalCore PickUpDateTime="2017-01-10T10:00:00" ReturnDateTime="2017-01-11T16:00:00">
<PickUpLocation LocationCode="88" ExtendedLocationCode="CUN01"></PickUpLocation>
<ReturnLocation LocationCode="89" ExtendedLocationCode="CUN"></ReturnLocation>
</VehRentalCore>
<VehPref VendorCarType="MCMR">
<VehClass>MCMR</VehClass>
<VehType>Chevrolet Matiz</VehType>
</VehPref>
<RateQualifier VendorRateID="90" RateAuthorizationCode="51 || 52" PromotionCode=""/>
<Customer>
<Primary>
<PersonName>
<NamePrefix>Mr</NamePrefix>
<GivenName>Carlos</GivenName>
<Surname>Gomez</Surname>
</PersonName>
<Telephone PhoneTechType="001.PTT" PhoneNumber="01 123 4567"></Telephone>
<Telephone PhoneTechType="005.PTT" PhoneNumber="041 234 5678"></Telephone>
<Email>
<Value>xmlbooking#somedomain.com</Value>
</Email>
<Address>
<CityName>Cancun</CityName>
<StateProv>Quintana Roo</StateProv>
<CountryName>New Zealand</CountryName>
</Address>
</Primary>
</Customer>
<Fees>
<Fee Description="10% Airport fee" Purpose="049.VCP" Amount=""></Fee>
</Fees>
<VehicleCharges Purpose="022.VCP">
<VehicleCharge CurrencyCode="USD" >
<Calculation Quantity="4" UnitName="Day" UnitCharge="120" total="480"></Calculation>
<TaxAmounts>
<TaxAmount Description="IVA Tax" TaxCode="IVA" Total=""></TaxAmount>
</TaxAmounts>
</VehicleCharge>
</VehicleCharges>
<TPA_Extensions>
<SOE_ExtrasRequest>
<Extra Code="1" Quantity="1" Amount="26.25" Period="11"></Extra>
<Extra Code="2" Quantity="1" Amount="37.50" Period="NA"></Extra>
<Extra Code="3" Quantity="1" Amount="90" Period="NA"></Extra>
</SOE_ExtrasRequest>
<SOE_Comments>
<Comment Name="optional info 1">
<Text>Any other relevant information such as flight no</Text>
</Comment>
</SOE_Comments>
</TPA_Extensions>
</VehResRQCore>
<SpecificFlightInfoType>
<FlightNumber>123</FlightNumber>
<Airline>British airline</Airline>
</SpecificFlightInfoType>
</OTA_VehResRQ>
`
I'm reading with this method:
`public function actionIndex()
{
if (isset($_REQUEST["XML"])) {
$XML = $_REQUEST["XML"];
} else {
$XML = file_get_contents('php://input');
}
$xmlValidado = XMLReader::xml($XML);
$xmlValidado->setParserProperty(XMLReader::VALIDATE, true);
//header("Content-type: text/xml");
require_once("Array2XML.php");
if ($XML = simplexml_load_string($XML)) {
$Action = $XML->getName();
$POS = $XML->POS;
$Type = $POS->Source->RequestorID->attributes()->Type;
$UserName = $POS->Source->RequestorID->attributes()->ID;
$Password = $POS->Source->RequestorID->attributes()->MessagePassword;
header("Content-type: text/xml");
$this->{$Action}($XML);
} else {
header("Content-type: text/xml");
$Results = array();
$Results['#attributes'] = array(
'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
'lastUpdated' => date('c'),
);
$Results["ErrorMessage"] = utf8_encode("XML Invalido!");
$xml = Array2XML::createXML('Error', $Results);
echo str_replace("\n", "", (trim($xml->saveXML())));
}
exit();
}`
And I load a method called:
public function OTA_VehResRQ($XML){
$Results = array();
$Results['#attributes'] = array(
'Version' => '1.00',
'TimeStamp' => date('c')
);
$ctTextLoc = self::CT_TEXTLOC;
$ctLocations = self::CT_LOCATIONS;
$ctEstatus = self::CT_ST;
$RateId = (int)$XML->POS->Source->RequestorID->attributes()->ID;
$DateIn = (string)$XML->VehResRQCore->VehRentalCore->attributes()->PickUpDateTime;
$DateOut = (string)$XML->VehResRQCore->VehRentalCore->attributes()->ReturnDateTime;
$locpu_text = (string)$XML->VehResRQCore->VehRentalCore->PickUpLocation->attributes()->ExtendedLocationCode;
$locdo_text = (string)$XML->VehResRQCore->VehRentalCore->ReturnLocation->attributes()->ExtendedLocationCode;
$salutation = (string)$XML->VehResRQCore->Customer->Primary->PersonName->NamePrefix;
$nombre = (string)$XML->VehResRQCore->Customer->Primary->PersonName->GivenName;
$apellidos = (string)$XML->VehResRQCore->Customer->Primary->PersonName->Surname;
$email = (string)$XML->VehResRQCore->Customer->Primary->Email;
$telefono = ((string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneTechType == '001.PTT')?(string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneNumber : '';
$ciudad = (string)$XML->VehResRQCore->Customer->Primary->Address->CityName;
$celular = ((string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneTechType == '005.PTT')?(string)$XML->VehResRQCore->Customer->Primary->Telephone->attributes()->PhoneNumber : '';
$estado = (string)$XML->VehResRQCore->Customer->Primary->Address->StateProv;
$pais = (string)$XML->VehResRQCore->Customer->Primary->Address->CountryName;
$datePickup = date("Y-m-d", strtotime($DateIn));
$dateDropoff = date("Y-m-d", strtotime($DateOut));
$referencia = (string)$XML->BookingReferenceID->UniqueID_Type->attributes()->ID;
$tarifa_grupo = (string)$XML->VehResRQCore->RateQualifier->attributes()->RateAuthorizationCode;
$web_flota_acriss = (string)$XML->VehResRQCore->VehPref->VehClass;
$web_flota_similar = (string)$XML->VehResRQCore->VehPref->VehType;
$loc_pickup = (int)$XML->VehAvailRQCore->VehRentalCore->PickUpLocation->attributes()->LocationCode;
$loc_dropoff = (int)$XML->VehAvailRQCore->VehRentalCore->ReturnLocation->attributes()->LocationCode;
$loc_pickup_text = $ctTextLoc["$locpu_text"];
$loc_dropoff_text = $ctTextLoc["$locdo_text"];
$pickup_time_hr = date("H", strtotime($DateIn));
$pickup_time_min = date('i', strtotime($DateIn));
$dropoff_time_hr = date("H", strtotime($DateOut));
$dropoff_time_min = date('i', strtotime($DateOut));
$costo_dias = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->Calculation->attributes()->Unitcharge;
$costo_semana = 0;
$costo_horas = 0;
$total_dias = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->Calculation->attributes()->Quantity;
$total_semanas = 0;
$total_horas = 0;
$total_renta = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->Calculation->attributes()->total;
$total_extras = 0;
$imp_iva = (int)$XML->VehResRQCore->VehicleCharges->Vehiclecharge->TaxAmounts->TaxAmount->attributes()->Total;
$imp_aepto = (float)$XML->VehResRQCore->Fees->Fee->attributes()->Amount;
$total_total = "";
$moneda = (string)$XML->VehResRQCore->VehicleCharge->attributes()->CurrencyCode;
$extras = serialize($XML->VehresRQCore->TPA_Extensions->SOE_ExtrasRequest);
$st = "";
$flight_number = (string)$XML->SpecificFlightInfoType->FlightNumber;
$flight_airline = (string)$XML->SpecificFlightInfoType->Airline;
$comments = (string)$XML->VehresRQCore->TPA_Extensions->SOE_Comments->Comment->text;
foreach ($XML->VehresRQCore->TPA_Extensions->SOE_ExtrasRequest->attributes()->Amount as $item => $value){
$total_extras += $value;
}
$rInsert = new Reservacion;
$cInsert = new ReservacionCliente;
$cInsert->salutation = (string)$salutation;
$cInsert->nombre = (string)$nombre;
$cInsert->apellidos = (string)$apellidos;
$cInsert->email = (string)$email;
$cInsert->telefono = (string)$telefono;
$cInsert->celular = (string)$celular;
$cInsert->ciudad = (string)$ciudad;
$cInsert->pais = (string)$pais;
$cInsert->estado = (string)$estado;
$cInsert->save();
$ClienteID = $cInsert->cliente_id;
/*if ($r["total_horas"] > 0) {
$horas = (int) ($r["total_horas"] / $r["costo_horas"]);
} else {
$horas = 0;
}*/
$rInsert->referencia = (string)$referencia;
$rInsert->tarifa_grupo = $tarifa_grupo;
$rInsert->web_flota_acriss = (string) $web_flota_acriss;
$rInsert->web_flota_similar = $web_flota_similar;
$rInsert->web_sitio_id = 5;
$rInsert->prefijo = "RCC";
$rInsert->code = self::getNextId('code','web_reservacion',$condicion = array('prefijo'),$parametro = array('RCC') );
$rInsert->web_cliente_id = $ClienteID;
$rInsert->fecha = date("Y-m-d H:i:s");
$rInsert->pickup = $datePickup;
$rInsert->dropoff = $dateDropoff;
$rInsert->loc_pickup = $ctLocations[(string) $loc_pickup];
$rInsert->loc_dropoff = $ctLocations[(string) $loc_dropoff];
$rInsert->loc_pickup_text = $loc_pickup_text;
$rInsert->loc_dropoff_text = $loc_dropoff_text;
$rInsert->pickup_time_hr = $pickup_time_hr;
$rInsert->dropoff_time_hr = $dropoff_time_hr;
$rInsert->pickup_time_min = $pickup_time_min;
$rInsert->dropoff_time_min = $dropoff_time_min;
$rInsert->costo_dias = $costo_dias;
$rInsert->costo_semana = $costo_semana;
$rInsert->costo_horas = $costo_horas;
$rInsert->total_dias = (int)$total_dias;
$rInsert->total_semanas = (int) $total_semanas;
$rInsert->total_horas = (int) $total_horas;
$rInsert->total_renta = $total_renta;
$rInsert->total_extras = $total_extras;
$rInsert->iva = $imp_iva;
$rInsert->impuesto_aeropuerto = $imp_aepto;
$rInsert->extras = serialize($extras);
$rInsert->total = $total_total;
$rInsert->moneda = $moneda;
$rInsert->estatus = $ctEstatus[$st];
$rInsert->flight_number = $flight_number;
$rInsert->flight_airline = $flight_airline;
$rInsert->dominio = "Rental Cars";
$rInsert->agente_callcenter = 0;
$rInsert->comments = $comments;
if((string)$XML->VehResRQCore->VehicleCharges->attributes()->Purpose == '022.VCP'){
$rInsert->pagada = 1;
$rInsert->pago_fecha = date("Y-m-d H:i:s");
$rInsert->pago_detalle = $total_renta;
$rInsert->pago_observacion = 'Prepago de la renta, pendiente los adicionales';
}
if (!$rInsert->save()) {
$Results['Success'] = 'false';
$Results['VehResRSCore']['#attributes'] = array(
'ReservationStatus' => 'Not Committed'
);
} else {
$Results['Success'] = 'true';
$Results['VehResRSCore']['#attributes'] = array(
'ReservationStatus' => 'Committed'
);
$Results['VehResRSCore']['VehReservation']['VehSegmentCore']['ConfID']['#attributes'] = array(
'Type' => '014.UIT',
'ID' => 'RCC-' . $rInsert->code
);
}
$xml = Array2XML::createXML('OTA_VehResRS', $Results);
echo str_replace("\n", "", (trim($xml->saveXML())));
}
Is so weird because with another XML script works pretty well exe:
`<OTA_VehLocSearchRQ Version="1.00">
<POS>
<Source>`enter code here`
<RequestorID ID="22"></RequestorID>
</Source>
</POS>
</OTA_VehLocSearchRQ>`
To the method:
public function OTA_VehLocSearchRQ($XML)
{
$Results = array();
$Results['#attributes'] = array(
'Version' => '1.00',
'TimeStamp' => date('c')
);
if ($XML->POS->Source->RequestorID->attributes()->ID == 22) { // Sistema 22 = Rental Cars
$XML->POS->Source->RequestorID->attributes()->ID = 16; //Proveedor 16 = Rental Cars
}
if (isset($XML->VehLocSearchCriterion)) {
$Results["Success"] = true;
$Results["VehMatchedLocs"] = array();
$Locaciones = Yii::app()->db->createCommand()
->select('*, c.Name as Pais, c.Code2 as Country2L')
->from('cr_locaciones')
->join("Country c", "c.Code = locacion_pais")
->join("City", "ID = locacion_ciudad")
->where("locacion_proveedor = :proveedor AND locacion_id = :codigo", array(":proveedor" => (string)$XML->POS->Source->RequestorID->attributes()->ID, ":codigo" => $XML->VehLocSearchCriterion->RefPoint))
->queryAll();
} else {
$Results["Success"] = true;
$Results["VehMatchedLocs"] = array();
$Locaciones = Yii::app()->db->createCommand()
->select('*, c.Name as Pais, c.Code2 as Country2L')
->from('cr_locaciones')
->join("Country c", "c.Code = locacion_pais")
->join("City", "ID = locacion_ciudad")
->where("locacion_proveedor = :proveedor", array(":proveedor" => $XML->POS->Source->RequestorID->attributes()->ID))
->queryAll();
}
if (sizeof($Locaciones) > 0) {
$Results["VehMatchedLocs"]["VehMatchedLoc"] = array();
foreach ($Locaciones as $l) {
$lInfo = array(
"LocationDetail" => array(
"#attributes" => array(
"Code" => $l["locacion_id"],
"Name" => $l["locacion_nombre_en"],
"AtAirport" => (($l["locacion_tipo"] == 2) ? true : false),
"CodeContext" => "PickupLocation",
),
"Address" => array(
"AddressLine" => utf8_encode($l["locacion_direccion_linea_1"]),
"CityName" => utf8_encode($l["Name"]),
"PostalCode" => $l["locacion_cp"],
"CountryName" => array(
"#attributes" => array("Code" => $l["Country2L"]),
"#value" => $l["Pais"],
),
),
"Telephone" => array(
"#attributes" => array(
"PhoneNumber" => $l["locacion_telefono"],
"FormattedInd" => false,
),
),
)
);
array_push($Results["VehMatchedLocs"]["VehMatchedLoc"], $lInfo);
}
} else {
$Results["Success"] = false;
}
$xml = Array2XML::createXML('OTA_VehLocSearchRS', $Results);
echo str_replace("\n", "", (trim($xml->saveXML())));
}
Someone can give tips, I have researched and I could not find anything.
A million thanks.
I found the mistake, the problem was the "foreach" I was not iterating the array pretty well.
foreach ($XML->VehResRQCore->Customer->Primary->Telephone as $Telephone) {
switch((string) $Telephone['PhoneTechType']) { // Obtener los atributos como índices del elemento
case '001.PTT':
$telefono = $Telephone['PhoneNumber'];
break;
case '005.PTT':
$celular = $Telephone['PhoneNumber'];
break;
}
}
To serialize the extras:
foreach ($XML->xpath('//Extra') as $Extras) {
array_push( $extras,(string)$Extras['Code'],(string)$Extras['Amount'],(string)$Extras['observations']);
}
Is the first time I work with XML... anyway, I got it!
I answer my question if is helpful to another one!
How do I write this code without a foreach loop? I want to fetch the data from the database, but the key and value are stored in the database.
<?php
$options = get_payment_mode_options();
foreach ($options as $key => $value)
{
echo isset($form_data["personal_info"]) && $form_data["personal_info"]->payment_mode == $key ? $value : "";
}
?>
get_payment_mode_options() is function in helper,
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
Check this,
$options = get_payment_mode_options();
$paymentmode = isset($form_data["personal_info"]) ? $form_data["personal_info"]->payment_mode : '';
echo $options[$paymentmode];
helper function
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
<?php
function get_payment_mode_options()
{
return array(
"o" => "Online Payment",
"c" => "Cheque Payment"
);
}
// make a new function
function get_your_result($your_key)
{
if (!$your_key) {
return "";
}
$options = get_payment_mode_options();
if(!array_key_exists($your_key,$options)){
return "";
}
return $options[$your_key];
}
// dummy for test
$form_data["personal_info"] = new stdClass();
$form_data["personal_info"]->payment_mode = "o";
$k = $form_data["personal_info"]->payment_mode;
// ~dummy for test
// echo result
echo "----".PHP_EOL;
echo get_your_result($k).PHP_EOL;
echo "----".PHP_EOL;
I need help in fixing an issue in which I am using laravel 'in' validator to match a given input against multiple comma separated string of values. Now the issue is when there is a number in the input and it does not matches with any of the comma separated values then it gives an exception:
preg_match() expects parameter 2 to be string, array given
However it should simply give error message in validator object that input field does not match. instead it gives above mentioned exception. Following is my code:
if (!empty($program)) {
$institution_id = $program->InstitutionId;
$roster_users = $program->usersRosters()->where('ProfileType', 'Student')->get();
if (!empty($roster_users)) {
$rostered_users_ids = implode(',', $roster_users->lists('id'));
}
if (!empty($roster_users)) {
$rostered_users_usernames = implode(',', $roster_users->lists('UserName'));
}
$teacher_roster_users = $program->usersRosters()->where('ProfileType', 'External Staff')->get();
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_usernames = implode(',', $teacher_roster_users->lists('UserName'));
}
if (!empty($teacher_roster_users)) {
$teacher_rostered_users_data = $teacher_roster_users->lists('id', 'UserName');
}
}
$rules = [
'aasectionname.required' => '501 – AA section does not exist',
'aaid' => 'numeric|exists:users,id|in:' . $rostered_users_ids . '|aaidinstitutionmismatch:' . $institution_id,
'institutionid' => 'numeric|in:' . $institution_id,
'username' => 'exists:users,UserName|in:' . $rostered_users_usernames . '|usernameinstitutionmismatch:' . $institution_id,
'schoolid' => 'numeric',
'groupowner' => 'in:'.$teacher_rostered_users_usernames,
'remove' => 'in:0,1'
];
$messages = [
// InstitutionId
'institutionid.numeric' => '101 – Invalid Institution ID',
'institutionid.in' => '102 – Institution ID does not match Program',
// Usernames
'username.exists' => '201 – UserName does not exist',
'username.in' => '202 – UserName is not rostered to this program',
'username.usernameinstitutionmismatch' => '203 – User/Institution Mismatch - UserName is not assigned to this Institution',
// AAId
'aaid.numeric' => '301 – AA ID does not exist',
'aaid.exists' => '301 – AA ID does not exist',
'aaid.in' => '302 – AA ID is not rostered to this program',
'aaid.aaidinstitutionmismatch' => '303 – AA ID/Institution Mismatch – AAID is not assigned to this Institution',
// Mismatch
'bothmismatch' => '401 – AAID/UserName/SchoolID do not match (This is a combination of at least 2 of these items)',
// Teacher
'groupowner.in' => '501 – GroupOwner does not exist',
// Remove
'remove' => '601 – No Student record match to remove',
];
Excel::load($file, function($excel) use($program, $rules, $messages, $errors, &$errors_data, $teacher_rostered_users_data) {
global $totalmismatch;
$results = $excel->get();
$program_group_model = new ProgramGroup;
$option_model = new Option;
$group_default_status_id = key($option_model->getProgramsStatus(['Active']));
$groupVisibilityStatusId = $group_type = $option_model->getVisibilityOptions('Question Visibility','Private');
$data = [];
$lastSecId = null;
$groupSectionPreviousName = null;
$groupname = null;
$data['status'] = $group_default_status_id;
$data['program_id'] = $program->Id;
$groupname_lists = $program_group_model->with(['programs' => function ($query) use ($program){
$query->where('ProgramId','=',$program->Id);
}])->get()->lists('Name','Id');
foreach ($results as $key => $row) {
$inputs = $row->toArray();
$groupname = trim($inputs['usergroup']);
$errors = [];
// Stop reading the excel when aasectionname is empty
if (empty($groupname) || $groupname == null) {
$errors['remove'] = $messages['aasectionname.required'];
}
$validator = Validator::make($inputs, $rules, $messages);
if ($validator->fails()) {
$errors = $validator->messages()->toArray();
foreach ($errors as $error) {
foreach ($error as $e) {
$errors_data[] = [$key + 2, $e];
}
}
} else {
$aaid = intval($inputs['aaid']);
$groupowner_name = $inputs['groupowner'];
if (!empty($teacher_rostered_users_data[$groupowner_name])) {
$groupowner_id = $teacher_rostered_users_data[$groupowner_name];
$data['owner'] = $groupowner_id;
}
$remove = intval($inputs['remove']);
// Remove existing Student Roster
if (!empty($remove)) {
$removed = false;
$user_ids = is_array($aaid) ? $aaid : [$aaid];
$program_group = $program->programGroups()->where('Name', $groupname);
if (!empty($program_group)) {
$program_group = $program_group->first();
}
if (!empty($program_group)) {
$program_group = $program_group->users();
}
if (!empty($program_group) && !empty($user_ids)) {
$removed = $program_group->detach($user_ids);
}
if (!$removed) {
$errors['remove'] = $messages['remove'];
}
} else {
if (!in_array($groupname, $groupname_lists) || $groupSectionPreviousName != $groupname) {
$data['name'] = $groupname;
$data['group_id'] = array_search($groupname, $groupname_lists);
$data['group_type'] = $groupVisibilityStatusId;
$sectionId = $program_group_model->saveProgramGroup($data);
$data[$sectionId]['selected'][] = $aaid;
$groupname_lists[$sectionId] = $groupname;
} else {
$temp = array_flip($groupname_lists);
$data[$temp[$groupname]]['selected'][] = $aaid;
}
}
if ($totalmismatch === 2) {
$errors['bothmismatch'] = $messages['bothmismatch'];
}
foreach ($errors as $error) {
$errors_data[] = [$key + 2, $error];
}
}
$groupSectionPreviousName = $groupname;
}
$programAASectionModelForSectionUsers = new ProgramSectionUser();
$programAASectionModelForSectionUsers->saveProgramGroupUsers($data);
});
$rules
array:7 [
"aasectionname.required" => "501 – AA section does not exist"
"aaid" => "numeric|exists:users,id|in:28,29,32,33,25,24,27|aaidinstitutionmismatch:42"
"institutionid" => "numeric|in:42"
"username" => "exists:users,UserName|in:Kabeer,Ayaz,fddesaaweqq,fdawerascvdfc,haseeb,kamran,shahid|usernameinstitutionmismatch:42"
"schoolid" => "numeric"
"groupowner" => "in:externalstaff,rahat,uzma,sahar,haseebahmad,saimariaz,fredrick"
"remove" => "in:0,1"
]
I wrote an global function that getting array with keys and values, and inserting it to mysql db. something like this:
function insert_to_db($table, $data, $is_using_id) {
// I'm connecting to db before this code.
global $mysqli;
// .. Checking for errors ..
// .. if using id, remove the id from the values like this:
$columns = array_keys($data);
$values = array_values($data);
if ($is_using_id == true) {
unset($values[0]);
// Reorder the array after unset()
$values = array_merge($values);
}
// ..
// Generating text for use at the mysqli::prepare
$columns_text = "";
$i = 0;
while ($i < count($columns)) {
$column = $columns[$i];
if ($i == 0) {
$columns_text = $column;
} else {
$columns_text = $columns_text.", ".$column;
}
$i++;
}
unset($i);
unset($column);
$values_text = "";
// b_p_f is the $types string for mysqli-stmt::bind_param
$b_p_f = "";
// Generating text for use at the mysqli::prepare
$i = -1;
while ($i < count($values)) {
echo "\$i equals to {$i}<br>";
if ($is_using_id == true && $i == -1) {
// Null because id is calculated automatically by mysql
$values_text = "NULL";
} else if ($is_using_id == false && $i == 0) {
$value = $values[$i];
$values_text = "?";
if (is_numeric($value))
{
$b_p_f = 'i';
} else {
$b_p_f = 's';
}
} else {
$value = $values[$i];
$values_text = $values_text.", ?";
if (is_numeric($value))
{
echo "Value: {$value} Found as numberic<br>";
$b_p_f = $b_p_f.'i';
} else {
echo "Value: {$value} Found as non-numberic<br>";
$b_p_f = $b_p_f.'s';
}
}
$i++;
}
unset($i);
unset($value);
echo "b_p_f:";
var_dump($b_p_f);
echo " values:";
var_dump($values);
$stmt = $mysqli->prepare("INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
if (!$stmt) {
return array("error"=>"true", "error_mysqli"=>$mysqli->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
$stmt->bind_param($b_p_f, $values);
if ($stmt->execute()) {
return array("error"=>"false", "inserted_id"=>$mysqli->insert_id);
} else {
return array("error"=>"true", "error_stmt"=>$stmt->error, "MORE"=>"INSERT INTO ".$table." (".$columns_text.") VALUES (".$values_text.")");
}
}
Then I am calling to the function:
function hash_password($password) {
$options = [ 'cost' => 12 ];
return password_hash($password, PASSWORD_BCRYPT,$options);
}
$data = array(
"ID" => NULL,
"first_name" => "Alexander",
"last_name" => "Margolis",
"email" => "shay24590#gmail.com",
"username" => "smartDonkey",
"password" => "Incorrect",
"birthday" => "12-12",
"date_added" => time(),
"total_points" => 0,
"cafe_added" => 0,
"review_placed"=> 0);
$data["password"] = hash_password($data["password"]);
var_dump ( insert_to_db("user", $data, true) );
And I see on the screen
array(3) {
["error"]=> string(4) "true"
["error_stmt"]=> string(53) "No data supplied for parameters in prepared statement" ["MORE"]=> string(178) "..."
}
Why am I getting this? What is the problem?
Also, If I pass the value instead of ? to the mysql::prepare, it works! So - it means that the problem is with mysqli stmt bind_param..
I know that this question similar to others, but I didn't found one that helps my problem. and sorry for my english and for the long function. thank you!
I've moved to PDO, and instead of calling $stmt->bind_param($b_p_f, $values); you can call $pdo_stmt->execute($values) where $values is an Array.