import .CSV file with PHP using PDO - php

I'm having a problem importing .CSV data into a SQL database. I'm trying to use PDO in my PHP file to accomplish this and I can't seem to figure this out.
if (isset($_FILES['uploadedfile'])) {
// get the csv file and open it up
$file = $_FILES['uploadedfile']['tmp_name'];
$handle = fopen($file, "r");
try {
// prepare for insertion
$query_ip = $db->prepare('
INSERT INTO projects (
id, project_name, contact, pm, apm,
est_start, est_end, trips, tasks, perc_complete,
bcwp, actual, cpi, bcws, bac,
comments, status, project_revenue, profit_margin, pm_perc,
audited, account_id
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?
)');
$data = fgetcsv($handle,1000,",","'");
$query_ip->execute($data);
$count = $query_ip->rowCount();
fclose($handle);
} catch(PDOException $e) {
die($e->getMessage());
}
echo 'Projects imported ' . $count . ' rows were affected';
} else {
echo 'Could not import projects';
}
Now this works, kind of. It imports the data but as you may have guessed this is only inserting the first row of the .CSV file, which by the way is the column headers. So I need to skip the first row and loop through the rest of this .CSV file.
Obviously throwing me some code would solve this, but more than that I would like an explanation of how to do this properly with PHP Data Objects (PDO). All the examples I've come across either have huge flaws or don't use PDO. Any and all help is welcomed and appreciated.

The comments helped me come up with this answer. I used the following code
if (isset($_FILES['uploadedfile'])) {
// get the csv file and open it up
$file = $_FILES['uploadedfile']['tmp_name'];
$handle = fopen($file, "r");
try {
// prepare for insertion
$query_ip = $db->prepare('
INSERT INTO projects (
id, project_name, contact, pm, apm,
est_start, est_end, trips, tasks, perc_complete,
bcwp, actual, cpi, bcws, bac,
comments, status, project_revenue, profit_margin, pm_perc,
audited
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?
)
');
// unset the first line like this
fgets($handle);
// created loop here
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
$query_ip->execute($data);
}
fclose($handle);
} catch(PDOException $e) {
die($e->getMessage());
}
echo 'Projects imported';
} else {
echo 'Could not import projects';
}
I hope this helps future readers properly import their .CSV files using PDO. It should be noted this should not be used on a live server/site. This code has 0 protection against potentially harmful uploads.

error_reporting(E_ALL);
ini_set('display_errors', 1);
/* Database connections */
$_host = 'localhost';
$_name = 'root';
$_password = 'root';
$_database = 'TEST';
/* ========= Variables =========== */
/**
* Defines the name of the table where data is to be inserted
*/
$table = 'terms';
/**
* Defines the name of the csv file which contains the data
*/
$file = 'terms.csv';
/* =========== PDO ================= */
try {
$link = new PDO('mysql:dbname=' . $_database . ';host=' . $_host . ';charset=utf8', $_name, $_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$link->exec("set names utf8");
} catch (PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* ========= Load file content in an array ========== */
$rows = array_map('str_getcsv', file($file));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
/* ========= Insert Script ========== */
foreach ($csv as $i => $row) {
insert($row, $table);
}
function insert($row, $table) {
global $link;
$sqlStr = "INSERT INTO $table SET ";
$data = array();
foreach ($row as $key => $value) {
$sqlStr .= $key . ' = :' . $key . ', ';
$data[':' . $key] = $value;
}
$sql = rtrim($sqlStr, ', ');
$query = $link->prepare($sql);
$query->execute($data);
}
echo "Done inserting data in $table table";

Related

Insert a combination of strings and arrays into MYSQL

I have found similar questions on here, but nothing quite right for my situation. I need to make multiple entries to a database from a combination of values from a set of arrays and repeated strings. To give an example:
$sql = "INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES ('$venue', '$date', '1', '$info', '$title', '$repertoire_formatted', $time)";
$venue, $time, AND $date are arrays.
'1' should be added to EACH entry to the database without change.
$info, $title, AND $repertoire_formatted are strings that should be repeated, i.e., inserted without any variation, for each entry to the database.
So the following example shows what the contents of each variable might be:
$venue = array('venue1', 'venue7', 'venue50');
$date = array('2019-01-01', '2019-02-02', '2019-03-03');
$time = array('20:00:00', '19:00:00', '18:00:00');
$info = 'General info about this event';
$repertoire_formatted = 'Music that people will play at this event';
My SQL database is set up to take the different types of data for each input variable.
HERE is the code I have (not working):
session_start();
$_SESSION["servername"] = "localhost";
$_SESSION["username"] = "sonch_nB";
$_SESSION["password"] = 'hello';
$_SESSION["dbname"] = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');
$venue = ($_POST['venue']);
$date = ($_POST['date']);
$ensemble_id = '1'; //THIS WILL BE SET VIA LOGIN
$info = ($_POST['info']);
$title = ($_POST['title']);
//FORMAT INCOMING VARS CODE SKIPPED//
// Create connection
$conn = new mysqli($_SESSION['servername'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//NEED TO LOOP INPUT TO MYSQL NUMBER OF VALUES IN ARRAY
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time) VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
$stmt->execute();
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
You should use a prepared statement. In MySQLi (assuming your connection is $conn):
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
if ($stmt->execute() === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $conn->error;
}
}
$stmt->close();

PHP & SQL Server: how to insert data into 2 tables and insert multiple rows

I am trying to enter data from html into MSSQL database using php. I am unable to insert record in 2 different tables and unable to insert multiple records to a table, I have the code below
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$company = $_POST["company"];
$contact = (int)$_POST["contact"];
$worktitle = $_POST["worktitle"];
$industry = $_POST["industry"];
$V101 = $_POST["part2q1"];
$V102 = $_POST["part2q2"];
$V103 = $_POST["part2q3"];
$V104 = $_POST["part2q4"];
$V105 = $_POST["part2q5"];
$V106 = $_POST["part2q6"];
$V107 = $_POST["part3q1"];
$V108 = $_POST["part3q2"];
$V109 = $_POST["part3q3"];
$V110 = $_POST["part3q4"];
$V111 = $_POST["part3q5"];
$V112 = $_POST["part3q6"];
$V113 = $_POST["part4q1"];
$V114 = $_POST["part4q2"];
$V115 = $_POST["part4q3"];
$V116 = $_POST["part4q4"];
$V117 = $_POST["part4q5"];
$V118 = $_POST["part4q6"];
$V119 = $_POST["part5q1"];
$V120 = $_POST["part5q2"];
$V121 = $_POST["part5q3"];
$V122 = $_POST["part5q4"];
$V123 = $_POST["part5q5"];
$V124 = $_POST["part5q6"];
$V125 = $_POST["part6q1"];
$V126 = $_POST["part6q2"];
$V127 = $_POST["part6q3"];
$V128 = $_POST["part6q4"];
$V129 = $_POST["part6q5"];
$V130 = $_POST["part6q6"];
$V131 = $_POST["part7q1"];
$V132 = $_POST["part7q2"];
$V133 = $_POST["part7q3"];
$V134 = $_POST["part7q4"];
$V135 = $_POST["part7q5"];
$V136 = $_POST["part7q6"];
$V137 = $_POST["part7q7"];
$V138 = $_POST["part7q8"];
$V139 = $_POST["part8q1"];
$V140 = $_POST["part8q2"];
$V141 = $_POST["part8q3"];
$V142 = $_POST["part8q4"];
$V143 = $_POST["part8q5"];
$V144 = $_POST["part8q6"];
$currenttime = date("Ymd h:m:sa");
$server = "***";
$connOptions = array("Database"=>"**", "UID"=>"**", "PWD"=>"**!");
$conn = sqlsrv_connect($server, $connOptions);
if($conn){
$query="INSERT INTO dbo.profile (
name,
email,
company,
telephone,
worktitle,
industry,
createdate
)
VALUES (?, ?, ?, ?, ?, ?,getdate())";
$params = array(
$name,
$email,
$company,
$contact,
$worktitle,
$industry,
$currenttime
);
if(sqlsrv_query($conn, $query, $params)){
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
Im trying to insert records to another table like this continuing from the previous line:
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V101,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V102,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V103,$currenttime);
. . . . .
if(sqlsrv_query($conn, $query1, $params))
{
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
?>
I have been trying this, insert works for first table but not the second table, can anyone help please
The following worked for me to enter multiple records to second table. Thanks to Miken32
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params1=array(2,101,$V101,$currenttime);
if(sqlsrv_query($conn, $query1, $params1))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
if($conn){
$query2="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params2=array(2,102,$V102,$currenttime);
if(sqlsrv_query($conn, $query2, $params2))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}

multiple json data into mysql database table not inserting

I have this code.
<?php
// open mysql connection
$host = "localhost";
$username = "root";
$password = "";
$dbname = "jacklin";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));
// use prepare statement for insert query
$st = mysqli_prepare($con, 'INSERT INTO company_details(com_name, city, com_address, com_mno, com_lno, com_faxno, com_email, com_url, contact_person, com_img,
lat, lng, cat_src_pos, state, country, password, status, plan, token, pin, contact_person1, contact_person2,
com_mno1, com_mno2, fpass_token, adv_src_pos, alias, com_skype, cover)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssssssssssssissssssssssssisss', $id, $city, $com_address, $com_mno, $com_lno, $com_faxno, $com_email, $com_url, $contact_person, $com_img, $lat, $lng, $cat_src_pos, $state, $country, $password, $status, $plan, $token, $pin, $contact_person1, $contact_person2, $com_mno1, $com_mno2, $fpass_token, $adv_src_pos, $alias, $com_skype, $cover);
// read json file
$filename = 'empdata.json';
$json = file_get_contents($filename);
//convert json object to php associative array
$data = json_decode($json, true);
// loop through the array
foreach ($data as $row) {
// get the employee details
$id = $row['com_name'];
$city = $row['city'];
$com_address = $row['com_address'];
$com_mno = $row['com_mno'];
$com_lno = $row['com_lno'];
$com_faxno = $row['com_faxno'];
$com_email = $row['com_email'];
$com_url = $row['com_url'];
$contact_person = $row['contact_person'];
$com_img = $row['com_img'];
$lat = $row['lat'];
$lng = $row['lng'];
$cat_src_pos = $row['cat_src_pos'];
$state = $row['state'];
$country = $row['country'];
$password = $row['password'];
$status = $row['status'];
$plan = $row['plan'];
$token = $row['token'];
$pin = $row['pin'];
$contact_person1 = $row['contact_person1'];
$contact_person2 = $row['contact_person2'];
$com_mno1 = $row['com_mno1'];
$com_mno2 = $row['com_mno2'];
$fpass_token = $row['fpass_token'];
$adv_src_pos = $row['adv_src_pos'];
$alias = $row['alias'];
$com_skype = $row['com_skype'];
$cover = $row['cover']
// execute insert query
mysqli_stmt_execute($st);
}
//close connection
mysqli_close($con);
?>
and my empdata.json is like.
[{"com_id":"1","com_name":"SORENTO GRANITO PVT.LTD","city":"Morbi","com_address":"8-A National High WayOld ghuntu Road ,Morbi - 363 642 (Guj.) INDIA","com_mno":"+919377721600","com_lno":"02822 - 243783 \/ 84","com_faxno":"(02822) 243785","com_email":"marketing#sorentogranito.com","com_url":"www.sorentogranito.com","contact_person":"Mr. Bhagubhai Tulsiyani","com_img":"1403952411.png","lat":"22.824254","lng":"70.8606801","cat_src_pos":"400000","state":"Gujarat","country":"India","password":"91SORESGPL","status":"active","plan":"premium","token":"","pin":"363 642","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"400000","alias":"sorento-granito-pvt-ltd","com_skype":"","cover":"motto.jpg"},{"com_id":"3","com_name":"COTO CERAMIC PVT LTD","city":"Morbi","com_address":"8-A National Higway,B\/ h Makansar Panjarapore Weed...","com_mno":"+919099173713","com_lno":"+919099173713","com_faxno":"","com_email":"info#cotobathware.com","com_url":"www.cotobathware.com","contact_person":"Mr. SUMEET MARVANIYA","com_img":"d08687ba60bb3f0d1317e2fd8b10afd4.png","lat":"22.748123","lng":"70.9369573","cat_src_pos":"500000","state":"Gujarat","country":"India","password":"MAYANK8877","status":"active","plan":"basic","token":"","pin":"363621","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"500000","alias":"coto-ceramic-pvt-ltd","com_skype":"","cover":"motto.jpg"},{"com_id":"4","com_name":"GLORY CERAMIC PVT LTD","city":"Morbi","com_address":"8\/A , National Highway Lalpar Morbi","com_mno":"+919825228848","com_lno":"02822 - 650445\/ 652446","com_faxno":"","com_email":"gloryceramic#yahoo.co.in","com_url":"www.gloryceramic.com","contact_person":"Mr. Niraj Thakkar","com_img":"1403952443.png","lat":"22.7968786","lng":"70.8907196","cat_src_pos":"80000","state":"Gujarat","country":"India","password":"9227650445","status":"active","plan":"premium","token":"","pin":"363 641","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"80000","alias":"glory-ceramic-pvt-ltd","com_skype":"","cover":"motto.jpg"},{"com_id":"5","com_name":"SALON CERAMIC PVT.LTD.","city":"Morbi","com_address":"8-A National Highway, Olg Ghuntu Road, Morbi - 363 642(Guj.) INDIA","com_mno":"+91 9825223840","com_lno":"+91 2822 242115","com_faxno":"+91 2822 242116","com_email":"info#salonceramic.com","com_url":"www.salonceramic.com","contact_person":"Mr. Hiteshbhai","com_img":"1413397071.PNG","lat":"22.838649048614528","lng":"70.88279977525485","cat_src_pos":"400000","state":"Gujarat","country":"India","password":"123salon123","status":"active","plan":"premium","token":"252985240685b6f5b1728d0d31bc585b","pin":"363642","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"400000","alias":"salon-ceramic-pvt-ltd","com_skype":"","cover":"motto.jpg"}]
with 1000 of records.but when i run above code in my localhost it's not displaying any error and not inserting any record to database too. please tell me how to insert this type json to database.
Try a simple foreach loop to count the number of data, and then make a for loop for running the insert statement:
$file = file_get_contents('empdata.json');
$json = json_decode($file, true);
//echo '<pre>';
//print_r($json);
$num = array();//Open Blank array for number of data
foreach($json as $k => $v):
$num [] = $v; //number of data
endforeach;
$row= count($num);//Put number of data in $row
for($i=0; $i<$row; $i++){
//instead of putting the value in the statement, store them in variable
$com_name = $json[$i]['com_name'];
$city = $json[$i]['city'];
$com_address = $json[$i]['com_address'];
//Put the other variable like this and put them in insert statement
$stmt = mysqli_prepare($con, "INSERT INTO company_details VALUES (?, ?,?)");
mysqli_stmt_bind_param($stmt, 'sss', $com_name, $city, $com_address);
}
This is just a simple working solution( working demo with real database). I don't have no time for typing all the fields. For the second and third loop, there is no fax number, so if the data field default value cannot have null value, there will be some problem and your statement will not work properly and likely fails. I hope this will help.

Php Bulk insert

I have the code with php using bulk insert.,I run the code and there is no error., The Problem there is no OUTPUT with this code and blank page/screen appear .. All I want to do is to have the Output with the page and with the database using this code ..
<?php
$dbh = odbc_connect(
"DRIVER={SQL Server Native Client 10.0};Server=.;Database=ECPNWEB",
"sa", "ECPAY");
if (($handle = fopen("c:\\tblmcwd.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, "|")) !== FALSE) {
if (count($data) == 10) {
$sql = "INSERT INTO [dbo].[tblMCWD] (
[ID],
[ConsumerCode],
[ConsumerName],
[AccountStatus],
[AccountNumber],
[DueDate],
[CurrentBill],
[PreviousBill],
[TotalDiscount],
[TotalGrossAmountDue]
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(1, $data[0]);
$stmt->bindValue(2, $data[1]);
$stmt->bindValue(3, $data[2]);
$stmt->bindValue(4, $data[3]);
$stmt->bindValue(5, $data[4]);
$stmt->bindValue(6, $data[5]);
$stmt->bindValue(7, $data[6]);
$stmt->bindValue(8, $data[7]);
$stmt->bindValue(9, $data[8]);
$stmt->bindValue(10, $data[9]);
$stmt->execute();
}
}
fclose($handle);
}
?>
Try this:
....
$sql = "INSERT INTO [dbo].[tblMCWD] (
[ID],
[ConsumerCode],
[ConsumerName],
[AccountStatus],
[AccountNumber],
[DueDate],
[CurrentBill],
[PreviousBill],
[TotalDiscount],
[TotalGrossAmountDue]
) VALUES (
:ID, :ConsumerCode, :ConsumerName, :AccountStatus, :AccountNumber, :DueDate, :CurrentBill, :PreviousBill, TotalDiscount, TotalGrossAmountDue
)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ID', $data[0]);
$stmt->bindParam(':ConsumerCode', $data[1],PDO::PARAM_STR);
$stmt->bindParam(':ConsumerName', $data[2],PDO::PARAM_STR);
$stmt->bindParam(':AccountStatus', $data[3],PDO::PARAM_STR);
$stmt->bindParam(':AccountNumber', $data[4],PDO::PARAM_STR);
$stmt->bindParam(':DuaDate' , $data[5],PDO::PARAM_STR);
$stmt->bindParam(':CurrentBill', $data[6],PDO::PARAM_STR);
$stmt->bindParam(':PreviousBill', $data[7],PDO::PARAM_STR);
$stmt->bindParam(':TotalDiscount', $data[8],PDO::PARAM_STR);
$stmt->bindParam(':TotalGrossAmountDue', $data[9],PDO::PARAM_STR);
$stmt->execute();
if(!$stmt){ // Check if the query executed succesfull, if not, print the data...
$printedString = "ID: %1$s ConsumerCode: %2$s ConsumerName: %3$s"; // and so on....
$printedString = sprintf($printedString , $data[0],$data[1],$data[2]); // and so on...
} else{
echo "Everything executed succesfully!<br />";
}
More info can you find here: Link
And here: Link 2
And here: Link 3
Use PDO::PARAM_STR for strings and PDO::PARAM_INT for an integer, and give it an try

Retrieving array values from within a class

Working on my first OOP app and I am having some trouble accessing the values of an array returned by a public function within my class. Here is the function -
//Process new transaction
public function addTransaction($amount, $payee, $category, $date, $notes) {
global $db;
//Check to see if payee exists in Payee table
$checkPayee = $db->prepare("SELECT * FROM payees WHERE name = ?");
$checkPayee->execute(array($payee));
$checkPayeeNum = $checkPayee->fetchColumn();
$payeeDetails = $checkPayee->fetch();
if ($checkPayeeNum < 1) {
$insertPayee = $db->prepare("INSERT INTO payees (name, cat) VALUES(?, ?)");
$insertPayee->execute(array($payee, $cat));
} else {
if ($payeeDetails['cat'] == "") {
$updatePayee = $db->prepare("UPDATE payees SET cat=? WHERE name=?");
$updatePayee->execute(array($cat, $payee));
}
}
//Process the transaction
$proc = $db->prepare("INSERT INTO transactions (amount, payee, cat, date, notes) VALUES (?, ?, ?, ?, ?)");
$proc->execute(array($amount, $payee, $cat, $date, $notes));
//Prepare array for JSON output
$todaysTrans = $this->fetchDailyTotal();
$weeklyTotal = $this->fetchWeeklyTotal();
$accountBalance = $this->balanceAccount();
$jsonOutput = array("dailyTotal" => $todaysTrans, "weeklyTotal" => $weeklyTotal, "accountBalance" => $accountBalance);
return $jsonOutput;
}
Instantiating the object is not the issue, trying to figure out how to access the $jsonOutput array. How would one accomplish this?
Thanks!
// In some other PHP file...
include 'YourClass.php';
$yourObject = new YourClass();
$returnedArray = $yourObject->addTransaction(...);
// Access the returned array values
echo 'Daily Total: ', $returnedArray['dailyTotal'], "\n";
echo 'Weekly Total: ', $returnedArray['weeklyTotal'], "\n";
echo 'Account Balance: ', $returnedArray['accountBalance'], "\n";
Also, for what it's worth, it's very confusing for you to be returning a PHP array called $jsonOutput, as it's not JSON encoded, which is what most developers will expect it to be. If you're wanting it to be JSON encoded, use json_encode() (see here for more info).

Categories