How should I store array values in a MySQL database? - php

To give some background, I'm creating a web app using mostly jQuery. I scrape a number of values from a page on another domain; 3 arrays of integers and a date in string format. These values are then displayed on my page. Each of these arrays has 7 numbers.
It makes sense to me to store each array as a single entry in my MySQL database. My original idea was to store the values of each array as a JSON object and insert that into my entry in the DB from reading around SO this doesn't seem like the approach to take. I don't envisage having any need to sort the values at any stage in the future. I will just need the value of each integer and don't need to know how each integer in each array relates to one another.
Can someone point me in the right direction regarding the storing and retrieval of these values?

Usually arrays are kind of iffy to handle. In most cases arrays are values that I need to process later in the front end for the user with javascript (can't think of another use anyway). Therefore what I usually do is store them as text by using
$array = array('one', 'two', 'three');
$textToSaveinDB = implode(',', $array);
When I retrieve this you would just use the other way around
$textFromDB = "one,two,three";
$array = explode(textFromDB, ',')
Afterwards you can do whatever you need to do with the array. For example use JSON_encode() and send it to the user via ajax.

Maybe serialize() and unserialize() would help you. But I won't suggest this as the best approach.

Related

How can i write an array that holds multiple values for each product

I've been searching around php.net, w3schools and youtube for something that has multiple objects like "move1, movie2" where each of those objects has variables like "id, qty, price".
I prefer an array were I can leave the qty value empty so I can have the user input it though a <form>, but I will figure that out once I find a form that fits what I need.
Any kind of help would be much appreciated.
I just need a look at the kind of array I need and if I will be able to apply it to my code and figure out the and action=POST code later.
you can handle this in php (server side) which is more common, and also you can handle in client side with java-script which i do'nt recommand .
you can use key-value arrays in php, for example you can easily do as bellow:
$basket[0]['productName']='Movies1';
$basket[0]['qty']=1;
$basket[0]['price']=15;
$basket[1]['productName']='Movies2';
$basket[1]['qty']=2;
$basket[1]['price']=30;
in this way you will have an array which can hold all off required information about your products.

How to handle with array in mysql?

I have some questions about handling with array concerning storing in mysql.
I stored an array (of numbers) in my mysql database as text Like: COLUMN_ARRAY: [2,3,4,5,6,7]
( including [ and ] )
My first question: is this a good method or can I work with that for my further steps? or are there any other better methods for storing array in sql column?
My second question: how could it be possible to pick every single element, or go throu all elements in the array with php?
because I want to make a query like if COLUMN_ARRAY includes the number 3 then do blablabla...
maybe you can give me some hint, idea, link or tutorial :)
EDIT:
Ok I did some change and changed everything to something like that:
How to store arrays in MySQL?
the only problem is now: how can I handle with an array (like [1,2,3]) in php - to handle with every single element in that?

Extracting specific data from a large amount of data in a single "cell" of a mysql database

Long time reader first time questioner...
I'm attempting to use Drupal to create a set of variables, not the issue, it's all in place to set them and simple for the future operator to edit.
I then need to grab these values in php, still on the site but outside of Drupal to some extent. Again, although I'm a bit of a lightweight on PHP, I can get what I need. However drupal stores the data all in one "cell" (apologies, I've searched for what I'm after but I think my vocabulary is lacking to get the right result!). Here's an example of how it is stored:
a:3:{i:0;a:3:{s:5:"value";s:2:"38";s:5:"label";s:11:"Cost Per
M2";s:6:"weight";s:1:"0";}i:1;a:3:{s:5:"value";s:1:"7";s:5:"label";s:13:"Arch
Top
Cost";s:6:"weight";s:1:"1";}i:2;a:3:{s:5:"value";s:1:"5";s:5:"label";s:13:"Flat
Top Cost";s:6:"weight";s:1:"2";}}
So I can happily return the whole contents as above, but I haven't the slightest how to refine it down to a specific reference. I can work out the data is contained between certain sets of brackets so, one ref is:
{s:5:"value";s:2:"38";s:5:"label";s:11:"Cost Per M2";s:6:"weight";s:1:"0";}
What I really need is the "38" in the example, as this is a cost that a 2nd system uses a number of to calculate a final cost.
I hope this makes sense?
The value is serialised (see http://php.net/manual/en/function.serialize.php). What you want to do is unserialize it (see http://www.php.net/manual/en/function.unserialize.php). So it would be:
$deserializedValues = unserialize($values).
After that you can call the variables by doing:
$deserializedValues['value'] (if an array)
$deserializedValues->value (if an object)
Drupal returns JSON. The cleanest way to handle this would be to use PHP's json_decode() function:
http://php.net/manual/en/function.json-decode.php

Storing an array in a MySQL table

I have a 5 level multidimensional array. The number of keys in the array fluctuates but I need to store it in a database so I can access it with PHP later on. Are there any easy ways to do this?
My idea was to convert the array into a single string using several different delimiters like #* and %* and then using a series of explode() to convert the data back into an array when I need it.
I haven't written any code at this point because I'm hoping there will be a better way to do this. But I do have a potential solution which I tried to outline below:
here's an overview of my array:
n=button number
i=item number
btn[n][0] = button name
btn[n][1] = button desc
btn[n][2] = success or not (Y or N)
btn[n][3] = array containing item info
btn[n][3][i][0] = item intput type (Default/Preset/UserTxt/UserDD)
btn[n][3][i][1] = array containing item value - if more than one index then display as drop down
Here's a run-down of the delimiters I was going to use:
#*Button Title //button title
&*val1=*usr1234 //items and values
&*val2=*FROM_USER(_TEXT_$*name:) //if an items value contains "FROM_USER" then extract the data between the perenthesis
&*val3=*FROM_USER(_TEXT_$*Time:) //if the datatype contains _TEXT_ then explode AGAIN by $* and just display a textfield with the title
&*val4=*FROM_USER($*name1#*value1$*name2#*value2) //else explode AGAIN by $* for a list of name value pairs which represent a drop box - name2#*value2
//sample string - a single button
#*Button Title%*val1=*usr1234&*val2=*FROM_USER(_TEXT_$*name:)&*val3=*FROM_USER(_TEXT_$*date:)&*val4=*FROM_USER($*name1#*value1$*name2#*value2)
In summary, I am seeking some ideas of how to store a multidimensional array in a single database table.
What you want is a data serialization method. Don't invent your own, there are plenty already out there. The most obvious candidates are JSON (json_encode) or the PHP specific serialize. XML is also an option, especially if your database may support it natively to some degree.
Have a look at serialize or json_encode
The best decision for you is json_encode.
It has some advantages for json_encode beside serialize for storing in db.
taking smaller size
if you
must modify data manually in db there will be some problems with serialize, because this format stores size of values that has been serialized and modifying this values you must count and modify this params.
SQL (whether mySQL or any other variant) does not support array data types.
The way you are supposed to deal with this kind of data in SQL is to store it across multiple tables.
So in this example, you'd have one table that contains buttonID, buttonName, buttonSuccess, etc fields, and another table that contains buttonInputType and buttonInputValue fields, as well as buttonID to link back to the parent table.
That would be the recommended "relational" way of doing things. The point of doing it this way is that it makes it easier to query the data back out of the DB when the time comes.
There are other options though.
One option would be to use mySQL's enum feature. Since you've got a fixed set of values available for the input type, you could use an enum field for it, which could save you from needing to have an extra table for that.
Another option, of course, is what everyone else has suggested, and simply serialise the data using json_encode() or similar, and store it all in a big text field.
If the data is going to be used as a simple block of data, without any need to ever run a query to examine parts of it, then this can sometimes be the simplest solution. It's not something a database expert would want to see, but from a pragmatic angle, if it does the job then feel free to use it.
However, it's important to be aware of the limitations. By using a serialised solution, you're basically saying "this data doesn't need to be managed in any way at all, so I can't be bothered to do proper database design for it.". And that's fine, as long as you don't need to manage it or search for values within it. If you do, you need to think harder about your DB design, and be wary of taking the 'easy' option.

string / array format convert with php

i'm manually reading out database entries from a plugin (eventscalendar wordpress). there are user defined fields / custom fields stored in the database. excuse my ignorance - but i'm having trouble associating the format the data is stored in:
a:1:{s:3:"key";s:6:"extern";}
so in the end all i would need is the value of s:6:"" in a simple variable.
lets say $key = "extern"
any quick solutions?
thanks,
mark
Take a look at unserialize to get it back into an array: http://php.net/manual/en/function.unserialize.php
That is a serialized array-- note the a at the beginning. It also works on Objects.
It is created with PHP's serialize and converted back to proper array/object with unserialize.
It serves a similar purpose to the JSON format.

Categories