How do obfuscate JSON response when dealing with a DB query? - php

[
{
"businesscards_id":"12",
"X_SIZE":"1.75x3",
"X_PAPER":"14ptGlossCoatedCoverwithUV(C2S)",
"X_COLOR":"1002",
"X_QTY":"250",
"O_RC":"NO",
"F_PRICE":"12490",
"UPS_GROUND":"12000",
"UPS_TWODAY":"24000",
"UPS_OVERNIGHT":"36000"
}
]
This JSON encode response is seen in console of Chrome. This array is being returned from a DB query. It is showing my table column names. For security reasons I do not want to show my table column names. How can this JSON object be obfuscated or hashed and/or encoded or dynamically re-written to keep my table col names private?

Don't do anything to your JSON.
If you don't want your column names to be visible, just dont use your column names. Create a new array using new keys to send with JSON and then change that array back into one containing your column names afterwards.
But it really shouldn't be a problem people seeing them. Nobody has access to your database so letting people see column names isn't an issue.

It really depends on how you wish to use the record once it has been received. One strategy might be to return an array of the values only, discarding the keys. Then in your code, use your private knowledge of which array value you need when you process the record. Something like:
var result=[];
Object.keys(record).forEach(function(key){result.push(record[key]);});
And then in your code, use array indices to access the values.

SQL statement:
SELECT `col_name` AS 'something_else'
But also, as everyone else said, don't do this for security. It is pointless.

Related

How to store a array in a database?

I am trying to learn php databases and I have a question. How do I store an array in a database? I saw an answer on stackoverflow and there were they doing something with type double and in an other answer they were talking about creating a table for every user but I can't find a solution.
So summarized. I want to store an array in a database. I have acces to phpmyadmin so from there can I set the value type. and I would like to store that array in one column.
Can somebody help me solving the problem?
edit one: The things I want to store are music tags. So in code it would be something like this:
array('pop','rock','country');
I want to store It in one column to make it easy searchable
Rather than storing arrays, try this:
Table 'genres' :
id | name
1 | pop
2 | rock
Table 'songs' :
id | ...
1
Table 'songs_genres' :
song_id | song_genre
1 | 1
1 | 2
And use JOIN's to get the genres for each song (or whatever)
Usually you shouldn't store arrays in a single column in a db. It is preferable to have a table with tags and another one that links your entity with its tags. So, before try to store an array in a table just think if it is really the right thing to do in your specific case (usually not).
If you are sure you want to do that then you have serialize and unserialize functions.
UPDATE (after five years)
serialize and unserialize methods are inherently unsecure and should be avoided. It is preferable to store data in JSON format using json_encode and json_decode.
serialize() is one option here. You can serialize a PHP array into a string to store in the database, and when you return the string from the database you can unserialize() to convert it back from a string to an array.
[ Edit ]
After you've updated the question with an example of the data you plan to store, using a MANY:MANY relationship in the actual database structure is the correct way to go, as mentioned in #Alex M's answer
You can use json_encode to make a json string from the array, like so :
$jsonarray = json_encode($array);
then after retrieving the information you decode it.
$array = json_decode($jsonarray, true); // the true will turn it into an array,
otherwise it's an object.
but I'd advice against it. try making a database which has the proper columns and store your data trough there.
Every user can have one or more music tags. In later time they want to add or remove those tags. If you store all of their tags in one column you are pretty much left with string operation rather than database operation. create new table tbl_user_music_Tags and save each tag along with the user ID. this way you have full flexibility of adding, removing, updating and reading tags for a specific user.
You can store it as an string such as 'rock, pop, foo, ...'.
But if you want to manage tags, i think you should store tags in other table as #Alex M suggested.

how to save json string in a mysql field

I have a table with a text field. I received string as below:
"value": "{\"airwayBills\":[\"84498761\"],\"dockets\":[\"1652395\"],\"error\":false,\"muditaError\":[{\"actionType\":\"docket\",\"docketNo\":\"1652395\",\"errorMessage\":\"No thing error\",\"pieceList\":null,\"quantity\":\"1\"}],\"muditaManifestExtra\":\"Unknown\",\"thingDetails\":[{\"airline\":\"Unknown\",\"bookingDate\":\"19-05-2014 13:03:15+0530\",\"currentPiecesDelivered\":\"0\",\"currentPiecesManifested\":\"1\",\"destination\":\"GOI\",\"flight\":\"Unknown\",\"inScannedPieces\":[],\"locationId\":\"MUDDELHUB1\",\"mode\":\"Air\",\"number\":\"1652395\",\"ordinality\":\"0\",\"origin\":\"DEL\",\"outScannedPieces\":[],\"quantity\":\"1\",\"recipientEmailId\":\"Unknown\",\"serviceProvider\":\"Unknown\",\"shipper\":\"Vector E Commerce Pvt. Ltd.\",\"thingType\":\"docket\",\"totPiecesManifested\":\"1\",\"totalPiecesDelivered\":\"0\",\"weight\":\"11\"}]}",
This value get stored correctly inside a field in the table, but when I try to fetch this value and save it in another field of another table then some of the values like "airwayBills\":[\"84498761\"] are stored as "airwayBills\":["0"], this is causing the loss of data. There is one more strange behaviour that this is happening randomly with only some of the records. Some records are added correctly. For saving into another field I am just enclosing the string in a single quote to save the string as is.
Please help how to save it in a single field in Mysql. Please note that the above values are coming after a GROUP_CONCAT query on the first table.
Thanks in advance
Consider the variable name $json_string as the one that contains your json in the give state (in your post), try stripslashes before trying to insert it into the database.
Here's an extra question, are you building the json array manually using string concatenation or using php array and them json_encode ? (2nd one would make things easier for you, since when you need to add the json obtained after the first mentioned query ran you can just do json_encode and your done)

pulling serialized data from mysql

So, there's a field in the db in which I store serialized arrays.
$array = array('count1' => 10, 'count2' => 20, 'count3' => 4);
serialized:
a:3:{s:6:"count1";i:10;s:6:"count2";i:20;s:6:"count3";i:4;}
Would it be possible to pull count1+count2+count3 using a mysql query? I guess I'm looking for something like php's explode. Pretty sure this can't be done, but I thought I'd ask.
I need to pull the highest count1+count2+count3 rows and return the total count. Looping through each row and unserializing wouldn't work since there are TONS of rows.
If you need to access parts of your serialized data via SQL, you need to store them in separate columns.
While it might be possible to use techniques such as regular expressions to access those three values in this string, it would be extremely slow when used in a WHERE criterion as indexes would be useless - not to mention that it would be a huge mess, way worse than using goto in a programming language.
So the solution is to create a new columns and then iterate over all rows, unserialize them, and store the sum into the new column. That might take a while but you'll only need to it once.
Depending on your application it might be better to create three columns and store each value separately.

How do i store a field from a MySQL database as a string in PHP?

One of my fields in my data base is an array which has been converted to a string using the implode() function.
How do I retrieve the contents of this field (LESSONS) from the database and store it to a string when a user entered value is equal to the the value of the field NAME?
Thanks in advance for any help you may be able to provide.
Here you go:
$r = mysql_query('SELECT LESSONS FROM TABLE WHERE NAME=\'user_string\'');
$rows = mysql_fetch_assoc($r);
echo $rows['LESSONS'];
I don't know if I understood your question but... Take a look about Stored Procedures
If you used the implode function to convert your array into a string, then this data has lost any information about the array keys.
As far as you want to convert the data back, use the explode function:
$array = explode(',', $columnData);
But You can therefore not search for array keys within the database.
Next to that, the MySQL database (I assume you're using MySQL) can not search for array keys anyway.
You need to store the data in some other way into the mysql to search for it in an SQL later on.
For example, you can create a table that stores key/value combinations with a grouping index.
However MySQL has some string functions that can help you searching within the (now) string data in the MySQL database.
When searching for a value, before the comparison add a comma at the beginning and one at the end of the string. There is a MySQL string function that can concatenate strings. Then search within that expression for your value with a comma added in front and back as well.
Then you can lookop a single array element within the mysql database. MySQL String Functions.
This is a quick solution only, this won't work on large databases performant. However it might solve your problem w/o changing your database structure.

PHP & MySQL Tickers..Is this standard practice?

I currently have about 4 different database tables which output to html tables. Each of these tables uses a count query to calculate data from a 5th table.
That's no problem, but what about when I want to sort and order the data, and paginate etc (like with zend). If it were a one page table, I could probably sort an array.
My thought was, to use a ticker. But that would require a new column in all 4 tables and seems like overkill or like there could be a better way.
Sadly, I can't find much info on it (likely because I don't know what to search for).
Advice?
..and please take it easy, I'm new and learning.
Assuming youre using Zend_Db_Table_Row and that you dont need to persist any modifications you might make to these rowsets then you can just append the virtual columns to the row object and have them be accessible via array notation. So if youre doing it all in one query now just use that same query, and the column should be there.
OTOH, if youre using a Data Mapper pattern then simply adjust your hydration to look for this "virtual column" and hydrate it if it exists in the result data. Then in your getter for this property have it see if the property is null or some other negative specification, and if it is, to execute a calculation query on that single object or return the already calculated result.

Categories