Xml to Mysql Fatal error - php

Im trying to get this working, but i do something wrong, im now trying 2 days to get it worked but no luck. Maybe someone can help me with the code
I have a xml file on the internet (see the example) and i want to put that xml in my mysql with php.
This is the example of my XML file
<AssignmentItems xmlns="http://server.my.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:schemaLocation="http://server.my.net/static/xsd/datafeed_assignments.xsd" total="29">
<Assignment>
<Id>253049101</Id>
<Status>Enroute</Status>
<Location>EBCI</Location>
<From>EBCI</From>
<Destination>EHGG</Destination>
<Assignment>1 PixCha Passer</Assignment>
<Amount>1</Amount>
<Units>passengers</Units>
<Pay>911.00</Pay>
<PilotFee>0.00</PilotFee>
<Expires>3 days</Expires>
<ExpireDateTime>2017-12-01 06:01:56</ExpireDateTime>
<Type>Trip-Only</Type>
<Express>False</Express>
<Locked>sharee</Locked>
<Comment/>
</Assignment>
</AssignmentItems>
i use this PHP code to send it to my MYSQL
<?php
$db = new PDO('mysql:host=localhost;dbname=test','root','');
$xmldoc = new DOMDocument();
$xmldoc->load('**XML URL**');
$xmldata = $xmldoc->getElementsByTagName('Assignment');
$xmlcount = $xmldata->length;
for ($i=0; $i < $xmlcount; $i++) {
$Id = $xmldata->item($i)->getElementsByTagName('Id')->item(0)->childNodes->item(0)->nodeValue;
$Status = $xmldata->item($i)->getElementsByTagName('Status')->item(0)->childNodes->item(0)->nodeValue;
$Location = $xmldata->item($i)->getElementsByTagName('Location')->item(0)->childNodes->item(0)->nodeValue;
$Fram = $xmldata->item($i)->getElementsByTagName('From')->item(0)->childNodes->item(0)->nodeValue;
$Destination = $xmldata->item($i)->getElementsByTagName('Destination')->item(0)->childNodes->item(0)->nodeValue;
$Assignment = $xmldata->item($i)->getElementsByTagName('Assignment')->item(0)->childNodes->item(0)->nodeValue;
$Amount = $xmldata->item($i)->getElementsByTagName('Amount')->item(0)->childNodes->item(0)->nodeValue;
$Units = $xmldata->item($i)->getElementsByTagName('Units')->item(0)->childNodes->item(0)->nodeValue;
$Pay = $xmldata->item($i)->getElementsByTagName('Pay')->item(0)->childNodes->item(0)->nodeValue;
$PilotFee = $xmldata->item($i)->getElementsByTagName('PilotFee')->item(0)->childNodes->item(0)->nodeValue;
$Expires = $xmldata->item($i)->getElementsByTagName('Expires')->item(0)->childNodes->item(0)->nodeValue;
$ExpireDateTime = $xmldata->item($i)->getElementsByTagName('ExpireDateTime')->item(0)->childNodes->item(0)->nodeValue;
$Type = $xmldata->item($i)->getElementsByTagName('Type')->item(0)->childNodes->item(0)->nodeValue;
$Express = $xmldata->item($i)->getElementsByTagName('Express')->item(0)->childNodes->item(0)->nodeValue;
$Locked = $xmldata->item($i)->getElementsByTagName('Locked')->item(0)->childNodes->item(0)->nodeValue;
$stmt = $db->prepare("insert into jobs values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bindParam(1, $Id);
$stmt->bindParam(2, $Status);
$stmt->bindParam(3, $Location);
$stmt->bindParam(4, $Fram);
$stmt->bindParam(5, $Destination);
$stmt->bindParam(6, $Assignment);
$stmt->bindParam(7, $Amount);
$stmt->bindParam(8, $Units);
$stmt->bindParam(9, $Pay);
$stmt->bindParam(10, $PilotFee);
$stmt->bindParam(11, $Expires);
$stmt->bindParam(12, $ExpireDateTime);
$stmt->bindParam(13, $Type);
$stmt->bindParam(14, $Express);
$stmt->bindParam(15, $Locked);
$stmt->execute();
printf($Id.'<br/>');
printf($Status.'<br/>');
printf($Location.'<br/>');
printf($Fram.'<br/>');
printf($Destination.'<br/>');
printf($Assignment.'<br/>');
printf($Amount.'<br/>');
printf($Units.'<br/>');
printf($Pay.'<br/>');
printf($PilotFee.'<br/>');
printf($Expires.'<br/>');
printf($ExpireDateTime.'<br/>');
printf($Type.'<br/>');
printf($Express.'<br/>');
printf($Locked.'<br/>');
}
?>
Than i get this error on my php page:
Notice: Trying to get property of non-object in
C:\xampp\htdocs\xml\xml.php on line 11
Fatal error: Uncaught Error: Call to a member function item() on null
in C:\xampp\htdocs\xml\xml.php:11 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\xml\xml.php on line 11
I hope someone can help with this error code
Michael

You can simply get whole XML data in PHP with simplexml_load_file function and then can add all XML data to database with for loop with MySqli Prepared Statements like below:
$xml=simplexml_load_file("http://www.example.com/sample.xml") or die("Error:
Cannot create object");
$count = count($xml->Assignment);
for($i=0;$i<$count;$i++)
{
$Id = $xml->Assignment[$i]->Id;
$Status = $xml->Assignment[$i]->Status;
$Location = $xml->Assignment[$i]->Location;
$Fram = $xml->Assignment[$i]->Fram;
$Destination = $xml->Assignment[$i]->Destination;
$Assignment = $xml->Assignment[$i]->Assignment;
$Amount = $xml->Assignment[$i]->Amount;
$Units = $xml->Assignment[$i]->Units;
$Pay = $xml->Assignment[$i]->Pay;
$PilotFee = $xml->Assignment[$i]->PilotFee;
$Expires = $xml->Assignment[$i]->Expires;
$ExpireDateTime = $xml->Assignment[$i]->ExpireDateTime;
$Type = $xml->Assignment[$i]->Type;
$Express = $xml->Assignment[$i]->Express;
$Locked = $xml->Assignment[$i]->Locked;
$stmt = $db->prepare("insert into jobs values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bindParam(1, $Id);
$stmt->bindParam(2, $Status);
$stmt->bindParam(3, $Location);
$stmt->bindParam(4, $Fram);
$stmt->bindParam(5, $Destination);
$stmt->bindParam(6, $Assignment);
$stmt->bindParam(7, $Amount);
$stmt->bindParam(8, $Units);
$stmt->bindParam(9, $Pay);
$stmt->bindParam(10, $PilotFee);
$stmt->bindParam(11, $Expires);
$stmt->bindParam(12, $ExpireDateTime);
$stmt->bindParam(13, $Type);
$stmt->bindParam(14, $Express);
$stmt->bindParam(15, $Locked);
$stmt->execute();
printf($Id.'<br/>');
printf($Status.'<br/>');
printf($Location.'<br/>');
printf($Fram.'<br/>');
printf($Destination.'<br/>');
printf($Assignment.'<br/>');
printf($Amount.'<br/>');
printf($Units.'<br/>');
printf($Pay.'<br/>');
printf($PilotFee.'<br/>');
printf($Expires.'<br/>');
printf($ExpireDateTime.'<br/>');
printf($Type.'<br/>');
printf($Express.'<br/>');
printf($Locked.'<br/>');
// Get all data in Variables and Execute MYSQLi Prepared Statements
// ---- //
}

I catch your error. The error is noticed when you try to access item in position 1 and there isn't an item in that position:
When you call this function $xmlcount = $xmldata->length; $xmlcount has a value of 2 so your for loop make an empty cycle with a null data. For avoid this fast without too much control make this:
$xmlcount = $xmldata->length - 1;
[Edit]
Your XML is not formatted correctly. You missed a closed tag of <AssignmentItems>

Related

Calling a function of a class does not work php

I have a php file called "purchases.controller.php" in which within a function called 'ctrCash' of the 'Purchases' class, I pass variables to a function called 'ctrNewCashPurchase' of the 'CartController' class that I have defined, but when I run the project, I get the message:
"Fatal error : Uncaught Error: Class 'CartModel' not found in ... "
If I do a var_dump inside the function ctrNewCashPurchase, I realize that I am entering that function, but it tells me that it does not recognize 'CartModel' and I do not understand why.
I share the code of the "purchases.controller.php" file:
class CartController{
static public function ctrNewCashPurchase($datos){
$tabla = "compras";
$respuesta = CartModel::mdlNewCashPurchase($tabla, $datos);
if($respuesta == "ok"){
$tabla = "comentarios";
ModeloUsuarios::mdlIngresoComentarios($tabla, $datos);
}
return $respuesta;
}
}
class Purchases {
public function ctrCash (&$arrayCompleto, &$usuario, &$direccion1, &$direccion2, &$dia, &$hora, &$email, &$telefono, &$sesion){
if(isset($usuario)){
//Here I create an array
for($i = 0; $i < count($arrayCompleto); $i++){
$datos = array("idUsuario"=> $sesion,
"idProducto"=> $arrayCompleto[$i]["idProducto"],
"metodo"=> "Efectivo",
"email"=> $email,
"direccion"=> $direccion1,
"detalleDireccion"=> $direccion2,
"diaEnvio"=> $dia,
"horaEnvio"=> $hora,
"telefono"=> $telefono,
"pais"=> "ARG");
}
$respuesta = CartController::ctrNewCashPurchase($datos);
}
}
}
I share the code of the "purchases.model.php" file, where I define the CartModel class:
class CartModel{
static public function mdlNewCashPurchase($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id_usuario, id_producto, metodo, email, direccion, pais, detalleDireccion, diaEnvio, horaEnvio, telefono) VALUES (:id_usuario, :id_producto, :metodo, :email, :direccion, :pais, :detalleDireccion, :diaEnvio, :horaEnvio, :telefono)");
$stmt->bindParam(":id_usuario", $datos["idUsuario"], PDO::PARAM_INT);
$stmt->bindParam(":id_producto", $datos["idProducto"], PDO::PARAM_INT);
$stmt->bindParam(":metodo", $datos["metodo"], PDO::PARAM_STR);
$stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);
$stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR);
$stmt->bindParam(":pais", $datos["pais"], PDO::PARAM_STR);
$stmt->bindParam(":detalleDireccion", $datos["detalleDireccion"], PDO::PARAM_STR);
$stmt->bindParam(":diaEnvio", $datos["diaEnvio"], PDO::PARAM_STR);
$stmt->bindParam(":horaEnvio", $datos["horaEnvio"], PDO::PARAM_STR);
$stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_INT);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt->close();
$tmt =null;
}
}
And I add this other file called 'aux.php' in case it influences something in the error that causes me. Here is how to send 'purchases.controller.php' parameters within the 'ctrCash' function
if(isset($_POST['usuario'])){
require ('purchases.controller.php');
$arrayCompleto = json_decode($_POST['arrayCompleto'], true);
$usuario = $_POST['usuario'];
$direccion1 = $_POST['direccion1'];
$direccion2 = $_POST['direccion2'];
$dia = $_POST['dia'];
$hora = $_POST['hora'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$sesion = $_POST['sesion'];
$payments = new Purchases();
$payments -> ctrCash($arrayCompleto, $usuario, $direccion1, $direccion2, $dia, $hora, $email, $telefono, $sesion);
}

Do While loop works well with echo but loops only once with a function inside loop

This code is supposed to insert 100 rows into the DB.
Yet when I run it, it loops only once, inserts one row and stops.
I replaced the function call with :
echo $keywords[4].'<br>';
It works perfectly. with no probleb
What is missing so that it will insert all rows into DB?
what should I change q add so that the code will insert all rows in the file
Here is the loop code:
do{
//Insert row content into array.
$keywords = preg_split("#\<(.*?)\>#", $row);
//Insert relevant data into DB
add_data($keywords);
}
else{
// If row is irrelevant - continue to next row
continue;
}
}while (strpos($row, 'Closed P/L') != true);
Here is the function
function add_data($keywords)
{
global $db;
$ticket =$keywords[2];
$o_time = $keywords[4];
$type = $keywords[6];
$size = $keywords[8];
$item = substr($keywords[10], 0, -1);
$o_price = $keywords[12];
$s_l = $keywords[14];
$t_p = $keywords[16];
$c_time = $keywords[18];
$c_price = $keywords[20];
$profit = $keywords[28];
try
{
$sql = "
INSERT INTO `data`
(ticket, o_time, type, size, item, o_price, s_l, t_p, c_time, c_price, profit)
VALUES
(:ticket, :o_time, :type, :size, :item, :o_price, :s_l, :t_p, :c_time, :c_price, :profit)";
$stmt = $db->prepare($sql);
$stmt->bindParam('ticket', $ticket, PDO::PARAM_STR);
$stmt->bindParam('o_time', $o_time, PDO::PARAM_STR);
$stmt->bindParam('type', $type, PDO::PARAM_STR);
$stmt->bindParam('size', $size, PDO::PARAM_STR);
$stmt->bindParam('item', $item, PDO::PARAM_STR);
$stmt->bindParam('o_price', $o_price, PDO::PARAM_STR);
$stmt->bindParam('s_l', $s_l, PDO::PARAM_STR);
$stmt->bindParam('t_p', $t_p, PDO::PARAM_STR);
$stmt->bindParam('c_time', $c_time, PDO::PARAM_STR);
$stmt->bindParam('c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam('profit', $profit, PDO::PARAM_STR);
$stmt->execute();
//return true;
}
catch(Exception $e)
{
return false;
echo 'something is wrong. Here is the system\'s message:<br>'.$e;
}
}

Call Oracle stored procedure using PDO PHP

I want to call procedure(written to insert data in table) using PDO PHP
,But procedure is not getting called.Don't know what Am I doing wrong
Below is my code,Can anyone suggest me best way to call Oracle Procedure using PDO PHP.
<?php
require("connection.php");
date_default_timezone_set('Asia/Kolkata');
$PARTY_C = 36317;
$CONN_NO = 479;
$EST_C = 86;
$STATUS = 'F';
$FAULTY_STATUS = 'PM';
$BILL_DT = date('d/m/Y');
$CURR_READ = 1000;
$PENALTY = 35;
$ADJSTMNT = 245;
$MTR_CHNG_DT = date('d/m/Y');
$OLD_MTR_READ = 900;
$METER_RES_DT = date('d/m/Y');
$PREV_OS_A_M = 1;
$PREV_INT_A_M = 34;
$PREV_PI_A_M = 45745;
$PARTY_M = 'abc';
$stmt = $conn->prepare("CALL PH_STATUS(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bindParam(1, $PARTY_C, PDO::PARAM_INT);
$stmt->bindParam(2, $CONN_NO, PDO::PARAM_INT);
$stmt->bindParam(3, $EST_C, PDO::PARAM_INT);
$stmt->bindParam(4, $STATUS, PDO::PARAM_STR);
$stmt->bindParam(5, $FALTY_STATUS, PDO::PARAM_STR);
$stmt->bindParam(6, $BILL_DT, PDO::PARAM_STR);
$stmt->bindParam(7, $CURR_READ, PDO::PARAM_INT);
$stmt->bindParam(8, $PENALTY, PDO::PARAM_INT);
$stmt->bindParam(9, $ADJSTMNT, PDO::PARAM_INT);
$stmt->bindParam(10, $MTR_CHNG_DT, PDO::PARAM_STR);
$stmt->bindParam(11, $OLD_MTR_READ, PDO::PARAM_INT);
$stmt->bindParam(12, $METER_RES_DT, PDO::PARAM_STR);
$stmt->bindParam(13, $PREV_OS_A_M, PDO::PARAM_INT);
$stmt->bindParam(14, $PREV_INT_A_M, PDO::PARAM_INT);
$stmt->bindParam(15, $PREV_PI_A_M, PDO::PARAM_INT);
$stmt->bindParam(16, $PARTY_M, PDO::PARAM_STR);
$stmt->execute();
print "procedure returned $stmt\n";
?>
As found here http://php.net/manual/en/pdo.prepared-statements.php, you have to use the bindParameter in another way or you have to use bindValue. (A good explanation can be found here Using pdo in php with stored procedure)
This should work:
...
$stmt->bindValue(1, $PARTY_C, PDO::PARAM_INT);
$stmt->bindValue(2, $CONN_NO, PDO::PARAM_INT);
$stmt->bindValue(3, $EST_C, PDO::PARAM_INT);
...

PDO INSERT statement not working inside counter loop

Can anyone let me know why this PDO Statement won't work inside the for loop? I'm trying to add one to the position for each new entry into the database. for some reason this is breaking. Any ideas on why?
Edit
Please ignore the next position, etc. For other reasons the gp_position can not be AUTO_INCREMENT and next position won't always start at 1. Please focus on why this PDO Statement won't work inside the loop.
$nextPosition = 1;
$imgID = 1;
$indb_gridID = 1;
$timesToRepeat = 33;
$indb_mem_id = ($this->user->is_logged_in()) ? $this->user->info['id'] : 1;
for($i=1; $i<=$timesToRepeat; $i++) {
// now add the image to the grid positions
$stmt = dbpdo::$conn->prepare("INSERT INTO grid_positions SET
gp_mem_id = :memID,
gp_g_id = :gridID,
gp_img_id = :imgID,
gp_position = :position");
$stmt->bindParam(':memID', $indb_mem_id, PDO::PARAM_INT);
$stmt->bindParam(':gridID', $indb_gridID, PDO::PARAM_INT);
$stmt->bindParam(':imgID', $imgID, PDO::PARAM_INT);
$stmt->bindParam(':position', $nextPosition, PDO::PARAM_INT);
$stmt->execute();
$nextPosition++;
}
Try this refactored code:
$nextPosition = 1;
$imgID = 1;
$indb_gridID = 1;
$timesToRepeat = 33;
$indb_mem_id = ($this->user->is_logged_in()) ? $this->user->info['id'] : 1;
// prepare the statement once:
$stmt = dbpdo::$conn->prepare("INSERT INTO grid_positions SET
gp_mem_id = :memID,
gp_g_id = :gridID,
gp_img_id = :imgID,
gp_position = :position");
$stmt->bindParam(':memID', $indb_mem_id, PDO::PARAM_INT);
$stmt->bindParam(':gridID', $indb_gridID, PDO::PARAM_INT);
$stmt->bindParam(':imgID', $imgID, PDO::PARAM_INT);
$stmt->bindParam(':position', $nextPosition, PDO::PARAM_INT);
for($i=1; $i<=$timesToRepeat; $i++) {
// exec statement with current values:
$stmt->execute();
$nextPosition++;
}

PDO Stored Procedure return value

I'm working with a SQL Server stored procedure that returns error codes; here is a very simple snippet of the SP.
DECLARE #ret int
BEGIN
SET #ret = 1
RETURN #ret
END
I can get the return value with the mssql extension using:
mssql_bind($proc, "RETVAL", &$return, SQLINT2);
However, I can't figure out how to access the return value in PDO; I'd prefer not to use an OUT parameter, as alot of these Stored Procedures have already been written. Here is an example of how I am currently calling the procedure in PHP.
$stmt = $this->db->prepare("EXECUTE usp_myproc ?, ?");
$stmt->bindParam(1, 'mystr', PDO::PARAM_STR);
$stmt->bindParam(2, 'mystr2', PDO::PARAM_STR);
$rs = $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Check out MSDN for info on how to correctly bind to this type of call
Your PHP code should probably be tweaked to look more like this. This may only work if you're calling through ODBC, which is honestly the strongly preferred way to do anything with SQL Server; use the SQL Native Client on Windows systems, and use the FreeTDS ODBC driver on *nix systems:
<?php
$stmt = $this->db->prepare("{?= CALL usp_myproc}");
$stmt->bindParam(1, $retval, PDO::PARAM_STR, 32);
$rs = $stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "The return value is $retval\n";
?>
The key thing here is that the return value can be bound as an OUT parameter, without having to restructure the stored procedures.
Just had this same problem:
<?php
function exec_sproc($sproc, $in_params)
{
global $database;
$stmnt = $database->prepare("EXEC " . $sproc);
if($stmnt->execute($in_params))
{
if($row = $stmnt->fetch())
{
return $row[0];
}
}
return -1;
}
?>
can't u use SELECT to return the results?
Then you can use a dataset (resultset in php?) to pick it up?
I don't know know PHP, but in c# its quite simple - use a dataset.
pretty sure PDO::exec only returns number of rows.. this would be $rs in your example
If I understand your question properly you shouldn't have to call fetchAll()...
$stmt = $this->db->prepare("EXECUTE usp_myproc ?, ?");
$stmt->bindParam(1, $mystr, PDO::PARAM_STR);
$stmt->bindParam(2, $mystr2, PDO::PARAM_STR);
$rs = $stmt->execute();
echo "The return values are: $mystr , and: $mystr2";
PDOStatement::bindParam
public function callProcedure($sp_name = null, $sp_args = []) {
try {
for($i = 0; $i < count($sp_args); $i++) {
$o[] = '?';
}
$args = implode(',', $o);
$sth = $connection->prepare("CALL $sp_name($args)");
for($i = 0, $z =1; $i < count($sp_args); $i++, $z++) {
$sth->bindParam($z, $sp_args[$i], \PDO::PARAM_STR|\PDO::PARAM_INPUT_OUTPUT, 2000);
}
if($sth->execute()) {
return $sp_args;
}
} catch (PDOException $e) {
this->error[] = $e->getMessage();
}
}
I had a similar problem and was able to solve it by returning the execute like so...
function my_function(){
$stmt = $this->db->prepare("EXECUTE usp_myproc ?, ?");
$stmt->bindParam(1, 'mystr', PDO::PARAM_STR);
$stmt->bindParam(2, 'mystr2', PDO::PARAM_STR);
return $stmt->execute();
}
All that is left is to call the function using a variable and then analyse said variable.
$result = my_function();
You can now analyse the contents of $result to find the information you're looking for. Please let me know if this helps!
Try $return_value

Categories