Good Afternoon,
I am trying to get these results into arrays in PHP so that I can encode them into json objects and send them to the client. The results of the query look like this:
id name hours cat status
3bf JFK Int 24 pass open
3bf JFK Int 24 std closed
3bf JFK Int 24 exp open
5t6 Ohm CA 18 pass closed
5t6 Ohm CA 18 std closed
5t6 Ohm CA 18 std2 open
5t6 Ohm CA 18 exp open
...
I would like for the json objects to look like this:
{ "id": "3bf", "name": "JFK Int", "cats":
{ [ { "cat": "pass", "status": "open" },
{ "cat": "std", "status": "closed" },
{ "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
{ [ { "cat": "pass", "status": "closed" },
{ "cat": "std", "status": "closed" },
{ "cat": "std2", "status": "open" } ],
{ "cat": "exp", "status": "open" } ] }
I have succesfully connected to mysql and exported using json_encode using flat tables but this part I do not know how to do in PHP. Thanks.
This is the code that I have. This returns an array of json objects but it is flat, not nested:
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = $row;}
$json = json_encode($arr);
echo $json;
The data itself is from a view that combines the tables ports and cats.
what you could do (sorry, not the best code I could write... short on time, ideas, and energy ;-) is something like this (I hope it still conveys the point):
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
// You're going to overwrite these at each iteration, but who cares ;-)
$arr[$row['id']]['id'] = $row['id'];
$arr[$row['id']]['name'] = $row['name'];
// You add the new category
$temp = array('cat' => $row['cat'], 'status' => $row['status']);
// New cat is ADDED
$arr[$row['id']]['cats'][] = $temp;
}
$base_out = array();
// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
// IDs were necessary before, to keep track of ports (by id),
// but they bother json now, so we do...
$base_out[] = $record;
}
$json = json_encode($base_out);
echo $json;
Haven't had the time to test or think twice about it, but again, I hope it conveys the idea...
With thanks to #maraspin, I have got my below code:
function merchantWithProducts($id)
{
if (
!empty($id)
) {
//select all query
$query = "SELECT
m.id as 'mMerchantID', m.name as 'merchantName', m.mobile, m.address, m.city, m.province,
p.id as 'ProductID', p.merchantId as 'pMerchantID', p.category, p.productName, p.description, p.price, p.image, p.ratingCount
FROM " . $this->table_name . " m
JOIN by_product p
ON m.id = p.merchantId
WHERE m.id = :id
GROUP BY m.id";
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
// $this->id = htmlspecialchars(strip_tags($this->id));
// bind values
$stmt->bindParam(":id", $this->id);
try {
$success = $stmt->execute();
if ($success === true) {
$results = $stmt->fetchAll();
$this->resultToEncode = array();
foreach ($results as $row) {
$objItemArray = array(
"merchantID" => $row->mMerchantID,
"merchantName" => $row->merchantName,
"mobile" => $row->mobile,
"address" => $row->address,
"city" => $row->city,
"province" => $row->province,
"product" => array(
"productID" => $row->ProductID,
"pMerchantID" => $row->pMerchantID,
"category" => $row->category,
"productName" => $row->productName,
"description" => $row->description,
"price" => $row->price,
"image" => $this->baseUrl . 'imagesProducts/' . $row->image,
"ratingCount" => $row->ratingCount
)
);
array_push($this->resultToEncode, $objItemArray);
}
http_response_code(200);
$httpStatusCode = '200 OK';
$pass = true;
// return json_encode($resultToEncode);
} else {
http_response_code(204);
$httpStatusCode = '204 No Content';
$pass = false;
$this->resultToEncode = 'No Record Found';
}
} catch (PDOException $pdoEx) {
http_response_code(500); // internal server error.
$httpStatusCode = '500 Internal Server Error';
$pass = false;
$this->resultToEncode = $pdoEx->getCode();
} catch (Exception $ex) {
// return $ex->getMessage();
http_response_code(404); // 404 Not Found.
$httpStatusCode = '404 Not Found';
$pass = false;
$this->resultToEncode = $ex->getMessage();
}
} else {
http_response_code(400);
$httpStatusCode = '400 bad request';
$pass = false;
$this->resultToEncode = 'User id not specified';
}
echo json_encode(array('passed' => $pass, 'Response' => $httpStatusCode, 'result' => $this->resultToEncode));
}
Related
I'm trying to create an array of objects with data coming from multiple tables, lets say there is table that hold patient data and there is table that hold diagnosis, and medicine for every patient that admitted to clinic, and i need to create an array of objects with the following output.
Screen shot
And i have to write the following code
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'new_nhif');
define('USERNAME', 'root');
define('PASSWORD', '');
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
$sql = sprintf(
'SELECT
nh.MembershipNo,
nh.FullName,
nh.id as nhid,
lb.labrequest,
fd.diagnosis,
fd.DiseaseCode,
fd.CreatedBy as fdcrb,
dz.name
FROM nhif_data AS nh
LEFT JOIN laboratory AS lb ON lb.re_id = nh.id
LEFT JOIN foliodisease AS fd ON fd.re_id = nh.id
LEFT JOIN dawa_zilizotoka AS dz ON dz.re_id = nh.id
WHERE lb.re_id = nh.id
AND fd.re_id = nh.id
AND dz.re_id = nh.id
-- GROUP BY nh.MembershipNo
'
);
$obj = new stdClass;
$result = $connection->query($sql);
$vipimo = array();
$dawa = array();
$all = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// print_r(json_encode(['entities'=> $row],JSON_PRETTY_PRINT));
$obj->MembershipNo = $row['MembershipNo'];
$obj->FullName = $row['FullName'];
$id = $row['nhid'];
$sql2 = "SELECT * FROM foliodisease WHERE re_id ='$id'";
$result1 = $connection->query($sql2);
if ($result1->num_rows > 0) {
while($row2 = $result1->fetch_assoc()) {
$vipimo['diagnosis']= $row2['diagnosis'];
$vipimo['DiseaseCode']= $row2['DiseaseCode'];
$obj->FolioDiseases[] = $vipimo;
}
}
$sql3 = "SELECT * FROM dawa_zilizotoka WHERE re_id = $id";
$result3 = $connection->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$dawa['name']= $row3['name'];
$obj->FolioItems[] = $dawa;
}
}
$all[] = $obj;
}
print_r(json_encode(['entities'=> $all], JSON_PRETTY_PRINT));
}
?>
And it give out the following output
{
"entities": [
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
},
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
}
]
}
My tables are
nhif_data ----
nhif_data ,
laboratory ----
laboratory,
foliodisease ---
foliodisease ,
dawa_zilizotoka ----
dawa_zilizotoka
You don't need to create an object array for the desired output, 'json_encode()' basically objectifies anything, meaning, no matter what you store with 'json_encode()' function, 'json_decode()' will always return you an object/array of objects, and so on.
All you need to fetch the records off the database, make child nesting as required, append the record to an array, and just 'json_encode()'; with 'json_decode()', you will end up with an array of objects.
$JSONItem = []; // Initialize the array
while($Record = $Query->fetch_assoc()){ // Iterate through main recordset
...subsequent child query
// Iterate though child recordset
while($ChildRecord = $ChildQuery->fetch_assoc())$Record["Child"][] = $ChildRecord; // Append child node to main record
$JSONItem[] = $Record; // Append record for JSON conversion
}
var_dump(json_decode(json_encode($JSONItem))); // This should return an array of ojects
Following should allow a better understanding of the mechanism;
var_dump(json_decode(json_encode([
["ID" => 1, "Name" => "Apple", "Source" => ["Name" => "Amazon", "URL" => "http://Amazon.Com", ], ],
["ID" => 2, "Name" => "Banana", "Source" => ["Name" => "eBay", "URL" => "http://eBay.Com", ], ],
["ID" => 3, "Name" => "Carrot", "Source" => ["Name" => "GearBest", "URL" => "http://GearBest.Com", ], ],
])));
Or, with newer PHP version, I hope you can simply prepare/construct the array and objectify it with something like;
$JSON = (object) $JSONItem;
I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(
You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}
My database have three tables(category,catgory_details,questions), Now one category have many questions. I want to have a JSON response like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol",
"What is ur name?"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?",
"What is ur name?"
]
}
}
]
but my code is returning only one row from questions tables like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?"
]
}
}
]
Following is my php code:
<?php
header("Content-Type: application/json");
include('db.php');
$result = mysqli_query($conn,"SELECT * FROM categories ORDER BY id ASC");
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array();
$row_array['category'] = $row['category'];
$id = $row['id'];
$detail_query = mysqli_query($conn,"SELECT * FROM category_details WHERE category_id=$id");
$question_query = mysqli_query($conn,"SELECT * FROM questions WHERE category_id=$id");
if($question_query->num_rows !== 0){
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
);
}
}
}
else{
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$myid = $detail_fetch['id'];
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
);
}
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
?>
What changes should I make in order to get my required JSON response?
Instead of building $row_array['deatils'] within the question_fetch loop, you should do it within the detail_fetch loop, and then populate just the questions sub-array within the question_fetch loop
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => array(),
);
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils']['questions'][] = $question_fetch['question'];
}
}
Try to change :
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
to :
'questions' => $question_fetch['question'],
So you will have the full array of questions included in the response.
i am trying to remove the old value of an array i searched over the internet i just found the method unset() using this solution but my case it seems different some how here is my full code
<?php
header('Content-type: application/json; charset=utf-8');
$link = mysqli_connect("localhost","root","");
mysqli_query($link,"SET NAMES UTF8");
$db= mysqli_select_db($link,"Mirsa") or die("Cannot select Database.");
if (isset($_GET['Product_ID']) ){
$productId;
$Menu_ID =$_GET['Product_ID'];
$query = "SELECT
mirsaProductId,mirsaProductCode,mirsaProductDescription,
mirsaProductPcsInCartoon,mirsaProductWeight,mirsaProductVolume,
mirsaProductCodeBType,mirsaProductCodeCType,FK_mirsaCategoryId
from mirsaProduct WHERE FK_mirsaCategoryId='$Menu_ID'";
$result = mysqli_query($link,$query) or die(mysql_error($link));
$response["Products"] = array();
$products = array();
while ($row = mysqli_fetch_array($result)) {
$image[]=array()
$products["mirsaProductId"] = $row["mirsaProductId"];
$products["mirsaProductCode"] = $row["mirsaProductCode"];
$products["mirsaProductDescription"] = $row["mirsaProductDescription"];
$products["mirsaProductPcsInCartoon"] = $row["mirsaProductPcsInCartoon"];
$products["mirsaProductWeight"] = $row["mirsaProductWeight"];
$products["mirsaProductVolume"] = $row["mirsaProductVolume"];
$products["mirsaProductCodeBType"] = $row["mirsaProductCodeBType"];
$products["mirsaProductCodeCType"] = $row["mirsaProductCodeCType"];
$productId = $row["mirsaProductId"];
$query2 = "SELECT mirsaProductUrlImage FROM mirsaProduct,mirsaProductImages
WHERE FK_mirsaProductId = '$productId' GROUP BY mirsaProductUrlImage";
$result2=mysqli_query($link, $query2);
while ($row2 = mysqli_fetch_array($result2))
{
$image [] = $row2["mirsaProductUrlImage"];
$products["mirsaProductUrlImage"]=$image;
}
array_push($response["Products"], $products);
}
die(json_encode($response));
}
// echoing JSON response
else {
// no products found
$response["success"] = 0;
$response["message"] = "No Products";
die(json_encode($response));
}
?>
i am getting a response of this way
{
ProductId: "1",
ProductCode: "118.023",
ProductDescription: "NEM OVAL (Transparent)",
ProductPcsInCartoon: "10",
ProductWeight: "7.55 - 8.05(KG)",
ProductVolume: "0.104(m3)",
ProductCodeBType: "NA",
ProductCodeCType: "NA",
ProductUrlImage: [
"1.png",
"2.png"
]
},
{
ProductId: "2",
ProductCode: "118.024",
ProductDescription: "NEM OVAL (Opac)",
ProductPcsInCartoon: "10",
ProductWeight: "7.55 - 8.05(KG)",
ProductVolume: "7.55 - 8.05(KG)",
ProductCodeBType: "NA",
ProductCodeCType: "NA",
ProductUrlImage: [
"1.png",
"2.png"
]
the second JSON object is not containing these 2 url of image it takes the old value of the $image[] so i need to reinitialised or empty his value in a way i need your help guys you are always our support
I am going to take a stab. Since you never really initialize $image to be an array. Do you actually intend for:
$image[] = array()
to be:
$image = array();
That would cause the $image array to be reset each time through the first while loop.
I'm a newbie programmer trying to find my way in the world. I've got my hands on JSON data that I'm trying to parse out into SQL statements to populate multiple database tables. I would like to loop through each dimension of the array and pull out specific parts of it to create an INSERT statement I can just pass to MySQL. I'm not sure if this is the best way to populate separate tables with data from one JSON file but it's the only thing I can think of. MySQL tables are separated so there is a table for a person, a table for address type, a table for address, a table for phone, a table for email etc. This is to account for a person record having numerous phone numbers, email addresses etc.
I have been able to decode the JSON from an external URL. Here is the code and a sample of the output using print_r.
$json_string = 'http://....';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
1 Record Sample:
Array ( [objects] => Array ( [0] => Array ( [first_name] => Anthony [last_name] => Perruzza [name] => Anthony Perruzza [elected_office] => City councillor [url] => http://www.toronto.ca/councillors/perruzza1.htm [gender] => [extra] => Array ( ) [related] => Array ( [boundary_url] => /boundaries/toronto-wards/york-west-8/ [representative_set_url] => /representative-sets/toronto-city-council/ ) [source_url] => http://www.toronto.ca/councillors/perruzza1.htm [offices] => Array ( [0] => Array ( [tel] => 416-338-5335 ) ) [representative_set_name] => Toronto City Council [party_name] => [district_name] => York West (8) [email] => councillor_perruzza#toronto.ca [personal_url] => [photo_url] => ) ) [meta] => Array ( [next] => /representatives/?limit=1&offset=1 [total_count] => 1059 [previous] => [limit] => 1 [offset] => 0 ) )
JSON Code Sample:
{"objects": [
{"first_name": "Keith",
"last_name": "Ashfield",
"name": "Keith Ashfield",
"elected_office": "MP",
"url": "http://www.parl.gc.ca/MembersOfParliament/ProfileMP.aspx?Key=170143&Language=E",
"gender": "",
"extra": {},
"related": {
"boundary_url": "/boundaries/federal-electoral-districts/13003/",
"representative_set_url": "/representative-sets/house-of-commons/"
},
"source_url": "http://www.parl.gc.ca/MembersOfParliament/MainMPsCompleteList.aspx?TimePeriod=Current&Language=E",
"offices": [
{ "type": "legislature",
"fax": "613-996-9955",
"postal": "House of Commons\nOttawa, Ontario\nK1A 0A6",
"tel": "613-992-1067"
},
{ "type": "constituency",
"fax": "506-452-4076",
"postal": "23 Alison Blvd (Main Office)\nFredericton, New Brunswick\nE3C 2N5",
"tel": "506-452-4110"
}
],
"representative_set_name": "House of Commons",
"party_name": "Conservative",
"district_name": "Fredericton",
"email": "keith.ashfield#parl.gc.ca",
"personal_url": "",
"photo_url": "http://www.parl.gc.ca/MembersOfParliament/Images/OfficialMPPhotos/41/AshfieldKeith_CPC.jpg"
}
],
"meta": {
"next": "/representatives/house-of-commons/?limit=1&offset=1",
"total_count": 307,
"previous": null,
"limit": 1,
"offset": 0
}
}
Any help you can offer would be greatly appreciated. I've been pulling my hair out for the last few days trying to figure it out.
I've tried customizing code like the following to make it work but I haven't been able to hit the sweet spot. Please not, this code doesn't reference my data or variables. I deleted what didn't work for me. I'm just including it to give you an idea what I've tried.
foreach ($data as $item) {
echo $item->{'first_name'} . "<br/>";
echo $item->{'last_name'};
}
If you could point me in the direction of being able to parse out data from any level of the array it would be greatly appreciated.
Best,
S
AFAIK, it is not possible to insert into several tables with one insert. Moreover, you need to preserve data integrity, so related tables would have right foreign keys.
The general idea is to iterate through the data, insert records and remember inserted ids, then write them as corresponding foreign keys.
You iterate thru your objects, insert all primitive properties as fields, then get an id using mysql_last_insert_id, then while saving offices (or their details) put that id as their related object id.
E.g. we have the following JSON.
{"authors": [
{"first_name": "John",
"last_name": "Doe",
"books": [{
"title": "Capture the flag",
"ISBN": "123-456789-12345",
},{
"title": "Deathmatch",
"ISBN": "123-456789-12346",
}]
]}
Then we insert that data with the following code:
foreach ($data as $author) {
mysql_query("INSERT INTO `authors` (`first_name`, `last_name`), VALUES('{$author->first_name}', '{$author->last_name}') ");
$author_id = mysql_last_insert_id();
foreach ($author->books as $book) {
mysql_query("INSERT INTO `books` (`title`, `isbn`, `author_id`), VALUES('{$book->title}', '{$book->isbn}', '{$author_id}') ");
}
}
This is for case you have auto-increment for id's in tables.
Of course, you'll need to validate and escape data before insertion etc.
Here is something that you can use to get the structure of a json response. It works recursively so that it will create an entry to for each object as well as an entry in a separate table for each property of each object. I hope to get others feedback/enhancement on this as well to turn it into create sql statements.
class DataDriller {
var $ext_obj_to_parse;
var $ext_type_name;
var $data;
var $recurse;
var $ext_type_id;
var $ext_related_id;
var $type_id;
var $auto_create;
var $sql;
var $error;
var $controller;
var $ExtType;
var $ExtStructure;
var $link;
var $ext_source_id;
function init($ExtType, $ExtStructure) {
$this->ExtType = $ExtType;
$this->ExtStructure = $ExtStructure;
}
function setup($ext_obj_to_parse, $ext_type_name, $ext_type_id = false, $ext_related_id = false, $auto_create = true, $ext_source_id) {
$this->ext_obj_to_parse = $ext_obj_to_parse;
$this->ext_type_name = $ext_type_name;
$this->ext_type_id = $ext_type_id;
$this->auto_create = $auto_create;
$this->error = false;
$this->ext_related_id = $ext_related_id;
$this->ext_source_id = $ext_source_id;
if ($this->get_ext_type_data() === false) {
if ($this->type_handling() === false) {
$this->error_data();
}
}
if (gettype($this->ext_obj_to_parse) == "object" || gettype($this->ext_obj_to_parse) == "array") {
$this->to_struct();
} else {
//single variable and data
$this->data[$this->ext_type_name] = gettype($this->ext_obj_to_parse);
$this->sql = "replace into ext_structures (name, data_type, ext_type_id) values ('$this->ext_type_name', '" . gettype($this->ext_obj_to_parse) . "', " . $this->ext_type_id . ")";
$this->sql_it();
}
}
function get_ext_type_data() {
if (is_numeric($this->ext_type_id)) {
return true;
} else if (strlen($this->ext_type_name) > 0) {
$this->sql = "select id From ext_types where name = '" . $this->ext_type_name . "' limit 1";
$this->ext_type_id = $this->sql_it('id');
return $this->ext_type_id;
} else {
return false;
}
}
function type_handling() {
if ($this->auto_create == true && gettype($this->ext_type_name) === "string") {
//$this->sql = "replace into types (name) values ('$this->ext_type_name')";
//
//$this->type_id = $this->sql_it();
//if ($this->type_id !== 0) {
//if ($this->ext_related_id) {
$this->sql = "insert into ext_types (name, ext_source_id, parent_id) values ( '$this->ext_type_name', $this->ext_source_id, '$this->ext_related_id')";
$this->ext_type_id = $this->sql_it();
$this->sql = "replace into ext_type_rel (ext_type_id_1, ext_type_id_2) values ($this->ext_type_id, $this->ext_related_id)";
$this->sql_it();
/*} else {
$this->error = "Unable to obtain typeid from insert";
$this->error_data();
return false;
}*/
}
//}
}
function to_struct() {
//keys are not objects but values can be
//always display keys, when value object - increase spacer - call self - reiterate
// if value is not object complete
foreach ($this->ext_obj_to_parse as $key => $value) {
if (gettype($value) == "object" || gettype($value) == "array") {
//check to see if object exists within the database with the data definitions and methods
//there are no existing data structure insert
//recurse into the drill-down again if it does not exist
if (is_numeric($key) || $key == "data" || $key == "statuses") {
$this->recurse = new DataDriller();
if (!$this->ext_related_id > 0){ $this->ext_related_it = $this->ext_type_id; }
$this->recurse->setup($value, $this->ext_type_name, $this->ext_type_id, $this->ext_related_id, true, $this->ext_source_id);
} else {
$this->recurse = new DataDriller();
$this->recurse->setup($value, $key, false, $this->ext_type_id, true, $this->ext_source_id);
}
$this->data[$key] = $this->recurse->data;
unset($this->recurse);
//this is where we insert the relationship between objects here
} else {
//not an ojbect just a field of the existing object
$this->data[$key] = gettype($value);
$this->sql = "replace into ext_structures (name, data_type, ext_type_id) values ('$key', '" . gettype($value) . "', " . $this->ext_type_id . ")";
$this->sql_it();
}
}
}
function sql_it($field_name = false) {
$VARDB_server = '192.168.10....';
$VARDB_port = '3306';
$VARDB_user = 'user';
$VARDB_pass = 'pass';
$VARDB_database = 'db_name';
$this->link = mysql_connect("$VARDB_server:$VARDB_port", "$VARDB_user", "$VARDB_pass");
if (!$this->link) {
echo 'MySQL connect ERROR: ' . mysql_error();
die();
}
$res = mysql_select_db("$VARDB_database");
if (!$res) {
echo mysql_error();
}
$res = mysql_query($this->sql, $this->link);
if (mysql_error()) {
$this->error = mysql_error() . " MYSQL reported an error " . $this->sql;
CakeLog::write('datadriller', $this->sql . " error? " . mysql_error());
die();
}
if ($field_name === false) {
if (strpos($this->sql, 'insert') !== false || strpos($this->sql, 'replace') !== false) {
$id = mysql_insert_id();
return $id;
} else {
$this->error = "field name is requeired for getting results";
$this->error_data();
return false;
}
} else {
if (mysql_num_rows($res) > 0) {
$r = mysql_fetch_array($res);
mysql_free_result($res);
if (array_key_exists($field_name, $r)) {
return $r[$field_name];
} else {
$this->error = "field name does not exist in result set";
$this->error_data();
return false;
}
} else {
$this->error = "select statement returned no data ";
return false;
}
}
}
function error_data() {
echo "<B> $this->error MySQL error? <font color=red>" . mysql_error() . " </font> SQL: $this->sql </b><BR><BR>\n";
echo "DUMP DATA\n";
echo "<pre>";
var_dump($this->data);
echo "RECURSED OBJECT \n\n";
var_dump($this->recurse);
echo "</pre>";
}
function JSONTOInsertSQL($table,$obj){
$keys = implode('`,`', array_map('addslashes', array_keys($obj)));
$values = implode("','", array_map('addslashes', array_values($obj)));
return "INSERT INTO `$table` (`$keys`) VALUES ('$values')";
}