how to insert multiple lines in json array in database using php - php

I want to enter some details that included in JSON arrays to database.
Given below is my source code.
here is my data json array from the txt file
{
"reader_name":"Biboy Pogi",
"mac_address":"00:16:25:10:7E:85",
"tag_reads":[
{
"antennaPort":1,
"epc":"2015031687850100010105B5",
"tid":"E280110520005A8B952F0886",
"isHeartBeat":false
}
]
}
{
"reader_name":"Biboy Pogi",
"mac_address":"00:16:25:10:7E:85",
"tag_reads":[
{
"antennaPort":1,
"epc":"2015031687850100010105B5",
"tid":"E280110520005A8B952F0886",
"isHeartBeat":false
}
]
}

Assuming that you source data come in one json per row. You can do the iteration insert with the below sample code:
$fn = 'debug.txt';
$raw = file_get_contents($fn);
$raw = explode("\r\n", $raw);
foreach($raw as $row){
//force it to array for single item
if (substr($row, 0, 1) != '[')
$row = '[' . $row . ']';
$data_arr= json_decode($row, true);
foreach ($data_arr as $data){
$reader_name = $data['reader_name'];
$mac_address = $data['mac_address'];
$antennaPort = $data['tag_reads'][0]['antennaPort'];
$epc = $data['tag_reads'][0]['epc'];
$tid = $data['tag_reads'][0]['tid'];
$sql = "INSERT INTO tags(reader_name, mac_address, antennaPort, epc, tid)
VALUES('$reader_name', '$mac_address', '$antennaPort', '$epc', '$tid')";
if(!mysqli_query($con, $sql))
{
die('Error : ' . mysqli_error($con));
}
}
}

your json seems to be the problem.
try this:
[
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
},
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
}
]

You'r JSON is wrong and two times the same. Maybe you'll need it that way, but this one of them
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
}
And you can't reach $antennaPort = $data['antennaPort']; that way. You have to call it like this
$antennaPort = $data['tag_reads']['antennaPort'];
$epc= $data['tag_reads'][0]['epc'];
$tid= $data['tag_reads'][0]['tid'];
EDIT
Insert into you'r database like this
mysqli_query($con,$sql)
After that, you should check for errors
if(!mysqli_query($con, $sql))
die ('Error in query: ' . mysqli_error($con));
Or you go in one line
mysqli_query($con, $sql) or die(mysqli_error());

Related

How to parse json array from mysql?

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;
}

JSON for PHP + MYSQL error

My client sent me this JSON so I can loop and save the data in Mysql. I just can not get it because it's different from what I work at;
Can someone give me some hint and what is the difference from one format to another.
Error presented is: Warning: Invalid argument supplied for foreach () in line 28
foreach ($ json_data ['service_devices'] as $ key => $ value) {
Formator EX I've ever worked with:
{
"ordem_de_servico": [
{
"oser_numero_os": 23940493,
"oser_address_name": NAME;
CUSTOMER JSON
ordem_de_servico:
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
My last attempt
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webservice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
foreach($json_data['ordens_de_servico'] as $key => $value){
$os = $value["oser_numero_os"];
$data_abertura = $value["oser_dt_abertura"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
$valorParcelas = $row["total_fatura"];
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR FATURA"."<p>";
}else {
$sql = "INSERT INTO faturas (valorParcelas, numero_os) VALUES ('$valorParcelas', '$os')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$valorParcelas." - FATURA OK"."</strong>"."<p>";
} else {
echo "Error Fatura";
}
}
}
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR"."<p>";
}
else{
$sql = "INSERT INTO os (numero_os, data_abertura) VALUES ('$os', '$data_abertura')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$os." - GRAVADO"."</strong>"."<p>";
} else {
echo "Error";
}
}
}
$conn->close();
?>
Change the line:
foreach($json_data['ordens_de_servico'] as $key => $value){
To:
foreach($json_data as $key => $value){
Since the new data doesn't have the outer element ordens_de_servico
Or you could edit the JSON file and add that element (don't forget to add the closing braces at the end as well.
Edit the first two lines of the file:
ordem_de_servico:
{
To:
{
"ordem_de_servico": [
And change the end of the file:
}
To:
]
}
Your JSON is incorrect. The main problem is json data itself which is not valid for json_encode() to generate PHP array.
First Possible solution:Remove ordem_de_servico: from our customer json and that will gonna work.
For json_decode(); method the json data must be valid and valid data is
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
Second possible solution:What you can do is remove ordem_de_servico: string from your customer json data or make your json provider provide valid json data as follows with ordem_de_servico:.
{
"ordem_de_servico":{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
}
Look at the valid JSON format for json_decode() and there is not different types of json data only one type i.e. json.

Convert data from sql to json file in php

I have this php code that give data from database and then convert to a json text file, my database name is gengroup_testwebapp and my json file is jsonparsetutorial.txt :
<?php
// open a connection to mysql
$conn = mysqli_connect("localhost","gengroup_ali","GenGroup$2015","gengroup_testwebapp")
or die("Error is : ".mysqli_error($conn));
//fetching data to php
$sql = "select * from country_info";
$result = mysqli_query($conn , $sql) or die("Error is : ". mysqli_error($conn));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
// convert php array to json String and \n
//write to json file
$fp = fopen('jsonparsetutorial.txt', 'worldpopulation');
fwrite($fp, json_encode($emparray));
fclose($fp); ?>
I wanna convert this code to json array file. how can I convert its data to a json file like this:
{ "worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.gengroup.ir/testwebapp/flag/india.png"
},
{
"rank":3,"country":"United States",
"population":"315,761,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/unitedstates.png"
},
{
"rank":4,"country":"Indonesia",
"population":"237,641,326",
"flag":"http://www.gengroup.ir/testwebapp/flag/indonesia.png"
},
{
"rank":5,"country":"Brazil",
"population":"193,946,886",
"flag":"http://www.gengroup.ir/testwebapp/flag/brazil.png"
},
{
"rank":6,"country":"Pakistan",
"population":"182,912,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/pakistan.png"
},
{
"rank":7,"country":"Nigeria",
"population":"170,901,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/nigeria.png"
},
{
"rank":8,"country":"Bangladesh",
"population":"152,518,015",
"flag":"http://www.gengroup.ir/testwebapp/flag/bangladesh.png"
},
{
"rank":9,"country":"Russia",
"population":"143,369,806",
"flag":"http://www.gengroup.ir/testwebapp/flag/russia.png"
},
{
"rank":10,"country":"Japan",
"population":"127,360,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/japan.png"
}
] }
Simply do this.
$arr['worldpopulation']= $emparray[];
$fp = fopen('jsonparsetutorial.txt', "w");
fwrite($fp, json_encode($arr));
fclose($fp); ?>
Don't forget to mention mode of open like w for write.

Grouping JSON output according to specific mysql column

I have a mysql table (name:"messages") that has three columns as below:
messageID, fromUserID, content
I wish to have a json output using php script like following format; I need to seprate messages of each user (fromUserID column).
JSONOutput:
{
"newCount":"x",
"messages":
[
{
"fromUserID":"x",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"y",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"z",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
}
]
}
My PHP Script:
$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");
$outputArray = array();
$outputArray['hasNew'] = mysqli_num_rows($query);
$messagesArray = array();
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray['MessagesArray'][] = $MSGArray;
}
$outputArray['Messages'][] = $messagesArray;
}
echo json_encode($outputArray);
But with above script I give a wrong result as below:
{
"hasNew":6,
"Messages":
[
{
"fromUserID":"24",
"MessagesArray":
[
{"messageID":"4","content":"test"},
{"messageID":"3","content":"test"},
{"messageID":"6","content":"test"},
{"messageID":"5","content":"test"},
{"messageID":"1","content":"test"},
{"messageID":"2","content":"test"}
]
}
]
}
My PHP Script just using last fromUserID value to grouping messages !!!
Please let me know where I'm wrong ...
Try it
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;
}
foreach($messagesArray as $value) {
$outputArray['Messages'][] = $value;
}
}

Parse JSON To Create SQL Insert Statements in PHP

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')";
}

Categories