I'm using CURL to request large XML Files from an API.
To prevent memory leaks I use this CURL option to stream the data and send it to the function curlCallback:
curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($splitter, 'curlCallback'));
In the curlCallback I prepare the incoming XML Stream and call the function below to store every main XML Node in the MySQL Database. Everything works well but:
I want to optimize the efficiency to store the data in the MySQL Database. This is the actual code:
public function processLine($str) {
$prdData = simplexml_load_string($str);
// connect to mysql db
$servername = "localhost";
$username = "";
$password = "";
$dbname = 'temp';
$db = new \PDO('mysql:host=' . $servername . ';dbname=' . $dbname . ';charset=utf8mb4',
$username,
$password,
array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => false
)
);
try {
$stmt = $db->prepare("INSERT IGNORE INTO Product (PRDNO, DSCRD ,DSCRF, DSCRLONGD, DSCRLONGF, PRTNO, SMCAT, DEL, BNAMD) VALUES (:prdno, :dscrd, :dscrf, :dscrlongd, :dscrlongf, :prtno, :smcat, :del, :bnamd)");
// MySQL Transaction
$db->beginTransaction();
$stmt->bindParam(':prdno', $prdData->PRDNO);
$stmt->bindParam(':dscrd', $prdData->DSCRD);
$stmt->bindParam(':dscrf', $prdData->DSCRF);
$stmt->bindParam(':dscrlongd', $prdData->DSCRLONGD);
$stmt->bindParam(':dscrlongf', $prdData->DSCRLONGF);
$stmt->bindParam(':prtno', $prdData->PRTNO);
$stmt->bindParam(':smcat', $prdData->SMCAT);
$stmt->bindParam(':del', $prdData->DEL);
$stmt->bindParam(':bnamd', $prdData->BNAMD);
$stmt->execute();
$db->commit();
} catch (PDOException $e) {
error_log(date("d.m.Y H:i:s") . ' | ' . $e->getMessage() . PHP_EOL, 3, '/var/www/html/log/import.log');
$db->rollBack();
}
}
How can I optimize this to just send one transaction including for example 100 Rows?
Related
I was using OCI_Connect to connect to my Oracle database.
Because of some internal plicies, i need to change it to PDO.
With OCI_Connect, i can read LOB data from database with "->load()" function in the result, something like this:
$this->Conn = oci_connect($this->User, $this->Pass, $this->Name, 'AL32UTF8');
$sql = "select field from table";
$s = oci_parse($this->Conn, $sql);
$res = oci_fetch_array($s, OCI_ASSOC + OCI_RETURN_NULLS)
echo $res[0]['FIELD']->load();
and it worked very well.
Now i need to do the same stuff with PDO, and because all my queries may change the number and name of the fields, i cannot bind the variables before executing it.
What i'm using now to connect:
$dbTns = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = $server)(PORT = $port)) (CONNECT_DATA = (SERVICE_NAME = $service_name) (SID = $sid)))";
$paramArray = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$this->PDO = new PDO("oci:dbname=" . $dbTns . ";charset=utf8", $db_username, $db_password, $paramArray );
With PDO, everything works fine, but i can't use the "->load()" function in the LOB field, as it does not exists here.
Is there an equivalent way to get the data after the query run?
Any suggestions are welcome.
(yes, i did search for a solution before posting that question here)
below is my we_connector file.php which is uploaded on server with customer add function
and my software is uploaded on a server. i want to add the online url but web connector is showing error "QuickBooks Web Connector could not verify the web application server certificate.".
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
if (function_exists('date_default_timezone_set'))
{
// * MAKE SURE YOU SET THIS TO THE CORRECT TIMEZONE! *
// List of valid timezones is here: http://us3.php.net/manual/en/timezones.php
date_default_timezone_set('America/New_York');
}
// Require the framework
require_once '../../QuickBooks.php';
$user = 'quickbooks';
$pass = 'password';
$map = array(
QUICKBOOKS_ADD_CUSTOMER => array( '_quickbooks_customer_add_request', '_quickbooks_customer_add_response' ),
);
// This is entirely optional, use it to trigger actions when an error is returned by QuickBooks
$errmap = array(
3070 => '_quickbooks_error_stringtoolong', // Whenever a string is too long to fit in a field, call this function: _quickbooks_error_stringtolong()
// 'CustomerAdd' => '_quickbooks_error_customeradd', // Whenever an error occurs while trying to perform an 'AddCustomer' action, call this function: _quickbooks_error_customeradd()
// '*' => '_quickbooks_error_catchall', // Using a key value of '*' will catch any errors which were not caught by another error handler
// ... more error handlers here ...
);
// An array of callback hooks
$hooks = array(
// There are many hooks defined which allow you to run your own functions/methods when certain events happen within the framework
// QuickBooks_WebConnector_Handlers::HOOK_LOGINSUCCESS => '_quickbooks_hook_loginsuccess', // Run this function whenever a successful login occurs
);
/*
function _quickbooks_hook_loginsuccess($requestID, $user, $hook, &$err, $hook_data, $callback_config)
{
// Do something whenever a successful login occurs...
}
*/
// Logging level
//$log_level = QUICKBOOKS_LOG_NORMAL;
//$log_level = QUICKBOOKS_LOG_VERBOSE;
$log_level = QUICKBOOKS_LOG_DEBUG;
//$log_level = QUICKBOOKS_LOG_DEVELOP; // Use this level until you're sure everything works!!!
// What SOAP server you're using
//$soapserver = QUICKBOOKS_SOAPSERVER_PHP; // The PHP SOAP extension, see: www.php.net/soap
$soapserver = QUICKBOOKS_SOAPSERVER_BUILTIN; // A pure-PHP SOAP server (no PHP ext/soap extension required, also makes debugging easier)
$soap_options = array( // See http://www.php.net/soap
);
$handler_options = array(
//'authenticate' => ' *** YOU DO NOT NEED TO PROVIDE THIS CONFIGURATION VARIABLE TO USE THE DEFAULT AUTHENTICATION METHOD FOR THE DRIVER YOU'RE USING (I.E.: MYSQL) *** '
//'authenticate' => 'your_function_name_here',
//'authenticate' => array( 'YourClassName', 'YourStaticMethod' ),
'deny_concurrent_logins' => false,
'deny_reallyfast_logins' => false,
); // See the comments in the QuickBooks/Server/Handlers.php file
$driver_options = array( // See the comments in the QuickBooks/Driver/<YOUR DRIVER HERE>.php file ( i.e. 'Mysql.php', etc. )
//'max_log_history' => 1024, // Limit the number of quickbooks_log entries to 1024
//'max_queue_history' => 64, // Limit the number of *successfully processed* quickbooks_queue entries to 64
);
$callback_options = array(
);
$dsn = 'mysqli://water_ways_user:zAEGQKI74YHyz6Do#localhost/water_ways';
if (!QuickBooks_Utilities::initialized($dsn))
{
// Initialize creates the neccessary database schema for queueing up requests and logging
QuickBooks_Utilities::initialize($dsn);
// This creates a username and password which is used by the Web Connector to authenticate
QuickBooks_Utilities::createUser($dsn, $user, $pass);
$primary_key_of_your_customer = 5;
$Queue = new QuickBooks_WebConnector_Queue($dsn);
$Queue->enqueue(QUICKBOOKS_ADD_CUSTOMER, $primary_key_of_your_customer,$priority);
}
$Server = new QuickBooks_WebConnector_Server($dsn, $map, $errmap, $hooks, $log_level, $soapserver, QUICKBOOKS_WSDL, $soap_options, $handler_options, $driver_options, $callback_options);
$response = $Server->handle(true, true);
function _quickbooks_customer_add_request($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $version, $locale)
{
$myHost = "localhost"; // use your real host name
$myUserName = "water_ways_user"; // use your real login user name
$myPassword = "zAEGQKI74YHyz6Do"; // use your real login password
$myDataBaseName = "water_ways"; // use your real database name
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword", "$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
// Fetch your customer record from your database
$name='';
$company_name = '';
$address1='';
$address2 ='';
$phone = '';
$contact = '';
$email = '';
$row = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM customer_info WHERE customer_info_id ='$ID'"));
//$sql=mysqli_query($con,"SELECT * FROM customer_info WHERE customer_info_id ='3'");
//if($row = mysqli_fetch_assoc($sql))
// {
// Create and return a qbXML request
$name=$row['customer_name'];
$company_name = $row['company_name'];
$address1=$row['address_1'];
$address2 =$row['address_2'];
$phone = $row['phone_number'];
$contact = $row['customer_name'];
$email = $row['email'];
$qbxml = '<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="2.0"?>
<QBXML>
<QBXMLMsgsRq onError="stopOnError">
<CustomerAddRq requestID="'.$requestID.'">
<CustomerAdd>
<Name>' . $name . '</Name>
<CompanyName>' . $company_name . '</CompanyName>
<BillAddress>
<Addr1>' . $address1 . '</Addr1>
</BillAddress>
<ShipAddress>
<Addr1>' . $address2 . '</Addr1>
</ShipAddress>
<Phone>' . $phone . '</Phone>
<Email>' . $email . '</Email>
<Contact>' . $contact . '</Contact>
</CustomerAdd>
</CustomerAddRq>
</QBXMLMsgsRq>
</QBXML>';
return $qbxml;
}
function _quickbooks_customer_add_response($requestID, $user, $action, $ID, $extra, &$err, $last_action_time, $last_actionident_time, $xml, $idents)
{
// Great, customer $ID has been added to QuickBooks with a QuickBooks
// ListID value of: $idents['ListID']
//
// We probably want to store that ListID in our database, so we can use it
// later. (You'll need to refer to the customer by either ListID or Name
// in other requests, say, to update the customer or to add an invoice for
// the customer.
$myHost = "localhost"; // use your real host name
$myUserName = "water_ways_user"; // use your real login user name
$myPassword = "zAEGQKI74YHyz6Do"; // use your real login password
$myDataBaseName = "water_ways"; // use your real database name
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword", "$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
mysqli_query($con,"UPDATE customer_info SET quickbooks_listid = '" . mysqli_escape_string($con,$idents['ListID']) . "',edit_sequence = '" . mysqli_escape_string($con,$idents['EditSequence']) . "' WHERE customer_info_id = " . (int) $ID);
}
this is my .qwc file which is on my local machine.
<?xml version="1.0"?>
<QBWCXML>
<AppName>Water Ways</AppName>
<AppID></AppID>
<AppURL>https://pcits.co.in/water_ways/quickbooks-php-master/docs/web_connector/web_connector.php</AppURL>
<AppDescription></AppDescription>
<AppSupport>https://pcits.co.in/water_ways/</AppSupport>
<CertURL>https://pcits.co.in/water_ways</CertURL>
<UserName>quickbooks</UserName>
<OwnerID>{90A44FB7-33D9-4815-AC85-AC86A7E7D1EB}</OwnerID>
<FileID>{57F3B9B6-86F1-4fcc-B1FF-967DE1813D20}</FileID>
<QBType>QBFS</QBType>
<Scheduler>
<RunEveryNMinutes>5</RunEveryNMinutes>
</Scheduler>
<IsReadOnly>false</IsReadOnly>
</QBWCXML>
and i am getting error as "QuickBooks Web Connector could not verify the web application server certificate."
This error message:
QuickBooks Web Connector could not verify the web application server certificate.
Means that your domain name (e.g. the domain shown in the AppURL):
https://pcits.co.in/
Does not have a valid SSL/TLS certificate.
Talk to your website hosting company/administrator, and ask them to issue/install/configure a secure SSL certificate.
I have been building a private web based app for my shopify store that caters more towards our business needs. While i am able to do a dump of "all-orders", or "all-products", etc to Mysql, i haven't been able to figure out executing the shopify order creation webhook to insert a new order when created in Shopify to a Mysql database.
Instead i would need to run my script every "x" times to see if there is a new order (This could if i'm not mistaken lead to exceeding my API limit if i am running other API calls concurrently).
I understand the process of events however i am struggling to execute!
1. New order created in Shopify by Customer &or Admin.
2. Triggers webhook and sends Json to desired url i.e(https://mydomain//new-order.php). -> [Struggling]
3. When this happens the Json is decoded. -> [Struggling]
4. Assigned to a variable. -> [This i can do]
5. Inserted into a Mysql database. -> [This i can do]
=> Question:
How do you once you have created the webhook (in Shopify) get it to trigger your code to run thereafter and execute?
below is the code that i have put together, but when i sent a test hook the database isn't being updated.
All in the [new-orders.php] file (Broken up to show my train of thought):
[1] Private app credentials for connecting to Shopify store.
<?php
$api_url = https://apikey:password#my-store.shopify.com';
$shopify = $api_url . '/admin/webhooks.json';
[2] Create an array for the webhook argumnets when the webhook is triggered & assign to variable $webhooks.
$arguments = array(
'topic' => 'order/creation',
'address' => 'https://mydomain//new-order.php'
);
$webhooks = $api_url . '/admin/webhooks.json', $arguments;
[3] Decode the webhook data.
$webhook_content = '';
$webhook = fopen('php://input' , 'rb');
while(!feof($webhook)){ //loop through the input stream while the end of file is not reached
$webhook_content .= fread($webhook, 4096); //append the content on the current iteration
}
fclose($webhook); //close the resource
$orders = json_decode($webhook_content, true); //convert the json to array
[4] Add the new order to the Mysql database table.
// not sure if a foreach loop is necessary in this case?
foreach($orders as $order){
$servername = "mysql.servername.com";
$database = "database_name";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$order_id = $order['id'];
$order_number = $order['name'];
$f_name = $order['billing_address']['name'];
$payment_gateway = $order['gateway'];
$financial_status = $order['financial_status'];
$order_value = $order['total_price'];
$order_status = $order['#'];
$shipping_province = $order['shipping_address']['province'];
$created_at = $order['created_at'];
$updated_at = $order['updated_at'];
$shipping_method = $order['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id, order_number, cust_fname, payment_gateway, financial_status, order_value, order_status, ship_to, created_at, updated_at, shipping_method)
VALUES ('$created_at', '$order_id', '$order_number', '$f_name', '$payment_gateway', '$financial_status', '$order_value', '$order_status', '$shipping_province', '$created_at', '$updated_at', '$shipping_method')");
}
?>
Any help would be greatly appreciated and i hope i have given enough context to the issue i am currently facing. If any other information is required i will try my best to explain why i have done something the way i have.
Regards,
Update, managed to figure this out and for those of you potentially struggling with the following this is how i solved.
There are 2 aspect here!
1. Setting up the webhook [Shopify -> Notifications -> webhooks].
2. The php file that processes the webhook.
1. -> Create Webhook in shopify and point to where you php url [example.com/Process-webhook.php]
2. -> Process-webhook.php
php code
// Load variables
$webhook_content = NULL;
// Get webhook content from the POST
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhook_content .= fread($webhook, 4096);
}
fclose($webhook);
// Decode Shopify POST
$webhook_content = json_decode($webhook_content, TRUE);
$servername = "server_name";
$database = "database";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
//Assign to variable
$order_id = $webhook_content['id'];
$order_number = $webhook_content['name'];
$f_name = $webhook_content['billing_address']['name'];
$payment_gateway = $webhook_content['gateway'];
$financial_status = $webhook_content['financial_status'];
$pick_status = $webhook_content['NULL'];
$pack_status = $webhook_content['NULL'];
$fulfill_status = $webhook_content['NULL'];
$order_value = $webhook_content['total_price'];
$order_status = $webhook_content['NULL'];
$shipping_province = $webhook_content['shipping_address']['province'];
// I wanted to insert the variant_id's and quantity as a string in one column. With this i can unserialise and use when needed
$items = [];
foreach($webhook_content["line_items"] as $item) {
$items[$item["variant_id"]]['quantity'] = $item["quantity"];
}
$items = serialize($items);
$created_at = $webhook_content['created_at'];
$updated_at = $webhook_content['updated_at'];
$shipping_method = $webhook_content['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id,
order_number,
cust_fname,
payment_gateway,
financial_status,
order_value,
order_status,
ship_to,
items,
created_at,
updated_at,
shipping_method)
VALUES ('$order_id',
'$order_number',
'$f_name',
'$payment_gateway',
'$financial_status',
'$order_value',
'$order_status',
'$shipping_province',
'$items',
'$created_at',
'$updated_at',
'$shipping_method')");
?>
We have an autoscaling group in AWS where upon launch database connections timeout. This is a Zend Framework 1 app using PHP 7.0.22-0ubuntu0.16.04.1 on Ubuntu 16.04.3 LTS
The code is baked into the AMI but during launch a userdata script will pull from git and phing configure the app. The database domain hasn't changed in years, the configure is mostly to take care of which elasticache instance to use. In other words, the baked in code already has the database configured and just gets overwritten with same value during configure step.
Once the ec2 instance is in the ELB, it begins getting hit on /health-check to see if things are OK by the load balancer. Inside this controller is the following code:
public function healthCheckAction() {
try {
/* #var $DBConn Zend_Db_Adapter_Pdo_Mysql */
$DBConn = Zend_Registry::get('multidb')->getDb();
// test guide service (most likely will be from memcache, unlikely to hit db)
$guideService = $this->_apiGuideService();
$guideService->isLoaded();
// this line fails and throws an exception
// I put host in here just so an error would include it in throw during this phase instead of catch phase (where it works)
// test raw db connection
$dbh = new PDO("mysql:host={$DBConn->getConfig()['host']};dbname={$DBConn->getConfig()['dbname']}", $DBConn->getConfig()['username'], $DBConn->getConfig()['password']);
$data = $dbh->query("SELECT '{$DBConn->getConfig()['host']}' as host, now()")->fetchObject();
// test database connectivity
// I put host in here just so an error would include it in throw during this phase instead of catch phase (where it works)
$sql = "SELECT '{$DBConn->getConfig()['host']}' as host, now()";
$DBConn->fetchRow($sql);
// test cache
/* #var $cache Zend_Cache_Core */
$cache = Zend_Registry::get('cachemanager')->getCache('default');
if (!$cache->load('health_check')) {
$cache->save(true, 'health_check');
}
echo 'Instance is healthy';
}
catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
echo 'Instance is unhealthy';
// get instance id
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://169.254.169.254/latest/meta-data/public-ipv4');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get instance ip
$ip = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://169.254.169.254/latest/meta-data/instance-id');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$instance = curl_exec($ch);
// email us some info
$message = "Instance $instance failed health check. ssh ubuntu#$ip to investigate<br><br>" . $e->getLine() . " " . $e->getCode() . "<br>" . $e->getMessage() . "<br>" . $e->getTraceAsString(). "<br><br>";
ob_start();
// this works and returns access denied, not timeout
$this->runCommand('mysql -u examplecom_platform -h sg-rds-example.us-east-1.rds.amazonaws.com');
echo "testing DB with php<br>";
try {
echo "write host: " . $DBConn->getConfig()['host'] . "<br>";
echo "read host: " . $DBConn->getConfig()['host'] . "<br>";
$dbh = new PDO("mysql:host={$DBConn->getConfig()['host']};dbname={$DBConn->getConfig()['dbname']}", $DBConn->getConfig()['username'], $DBConn->getConfig()['password']);
$data = $dbh->query('select now()')->fetchObject();
echo "query database without zend:<br>";
print_r($data);
// this line works and prints out
// stdClass Object
// (
// [now()] => 2018-01-09 14:47:12
// )
$dbh = null;
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "<br/>";
}
// this all work/show correct IP
$this->runCommand('nc -vz sg-rds-example.us-east-1.rds.amazonaws.com 3306');
$this->runCommand('host sg-rds-example.us-east-1.rds.amazonaws.com');
$this->runCommand('dig sg-rds-example.us-east-1.rds.amazonaws.com');
$debug = ob_get_contents();
ob_end_clean();
$message .= "<br><br>" . str_replace("\n", "<br>", $debug);
$mail = new Zend_Mail();
$mail->setSubject('[examplecom] Instance Failed Healthcheck v2')
->setFrom('noreply#example.com')
->addTo('alerts#example.com')
->setBodyHtml($message)
->send();
}
}
As I kept debugging things I would add more and more stuff to test the connection
The try statement throws an error of SQLSTATE[HY000] [2002] Connection timed out
But this exact same connection works in the catch and is able to query now() from the database.
This is where I am stumped, how could the same process timeout on first connection but work during the error catching?
Also I will only get 1 or 2 of these emails saying it cant connect, but then eventually by the time I can login to test some things it is working and connecting fine. Health-check reports happy and instance is kept in ELB.
Any ideas or suggestions to add more debugging?
I am new in using web service nusoap. When I try to run my program I got an error like this:
XML error parsing SOAP payload on line 1: Not well-formed (invalid
token)
Here is my client.php :
<?php
require_once('lib/nusoap.php');
$data = json_decode(file_get_contents("php://input"), true);
$doc_type = $data['doc_type'];
$transaction_date = $data['transaction_date'];
$file_name = $data['file_name'];
$file_path = $data['file_path'];
//create client instance
$client = new nusoap_client('http://computer_name:2224/WebService/webservice.php?wsdl' , true);
//to check if the request method is POST or not
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//check for error
$err = $client->getError();
if($err){
//Display error
echo '<h2>Constructor error </h2> <pre>' . $err . '</pre>' ;
}
//declare variables
$datas = array(
'doc_type' => $doc_type,
'transaction_date' => $transaction_date,
'file_name' => $file_name,
'file_path' => $file_path
);
//call the function InsertData and pass the parameters being instantiated
$result = $client->call('InsertData', $datas);
if($client->fault){
echo '<h2> Fault (Expect - The request contains an invalid SOAP body) </h2> <pre>';
print_r($result);
echo '</pre>' ;
}else {
$err = $client->getError();
if($err){
echo '<h2> Error </h2><pre>' . $err . '</pre>' ;
}else {
echo '<h2> Result </h2><pre>' ;
print_r($result);
echo '</pre>';
}
}
} else if ($_SERVER['REQUEST_METHOD'] != 'POST'){
echo "Method is not POST";
}
?>
webservice.php
<?php
// require the nusoap.php
require_once ('lib/nusoap.php');
//create new instance
$server = new soap_server();
//initialize WSDL support
$server->configureWSDL('Database Data Insertion', 'urn:Insert');
//character encoding
$server->soap_defencoding = 'utf-8';
// Registering different functions of your Web service
$server->register ('InsertData',
array(
'doc_type' => 'xsd:doc_type',
'transaction_date' =>'xsd:transaction_date',
'file_name' =>'xsd:file_name',
'file_path' =>'xsd:file_path'), //input values
array('return' =>'xsd:string'),
'urn:Insert', // Namespace
'urn:Insertwsdl#InsertData', //SoapAction
'rpc', //style
'literal' // can be encoded but it doesn't work with silverlight
);
// function for inserting data
function InsertData($doc_type,$transaction_date,$file_name,$file_path) {
//set initial values for connection
$db_host = 'localhost' ;
$db_username = 'root' ;
$db_password = '' ;
$db_name = 'sample' ;
//making connection
$conn = new mysqli($db_host, $db_username ,$db_password , $db_name);
//checking if connection is successful
if($conn->connect_error){
trigger_error('Database connection failed : ' .$conn->connect_error , E_USER_ERROR);
}
//inserting data in the edi_doc_type table
$sql = "INSERT INTO transaction_tbl (`transaction_date`,`edi_doc_type_id`,`file_name`,`file_path`,`creation_date`)
VALUES ('$transaction_date',( SELECT edi_doc_type_id FROM `edi_doc_type` WHERE doc_type = $doc_type ),'$file_name','$file_path',NOW()) " ;
//Checking query if it is successful
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
}
$HTTP_RAW_POST_DATA = isset ($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA: '' ;
$server->service($HTTP_RAW_POST_DATA);
?>
Now , when I try to run this I got the above error. so what could be the possible problem? By the way, I can still insert in my database , but the problem is it returns the above error and not all the data in the script can be inserted . When I check my php error logs I have this :
PHP Fatal error: Wrong SQL: INSERT INTO transaction_tbl
(transaction_date,edi_doc_type_id,file_name,file_path,creation_date)
VALUES ('2015-05-28 22:33:00',( SELECT edi_doc_type_id FROM edi_doc_type
WHERE doc_type = 997),'87749-20150528223345027_54423526_54423945.xfa','/home/sample/test/87749-20150528223345027_54423526_54423945.xfa',NOW())
Error: Subquery returns more than 1 row
C:\xampp\htdocs\WebService\webservice.php on line 65
Any help will be appreciated. Thanks :)