array type of question - php

I'm trying to figure out a way to make a small "table" style system in php for about 10 data rows. Because it requires constant editing, I want to replace my mysql system for something in php directly.
The data is 10 rows of:
id
first name
last name
I give the php file the id and want to pull out the first name and last name.
I tried using a associative array, but that turned into a coding mess as my syntax was all over the place.
How can I set this one up properly so i can edit the data easily in a single place and get first and last name of a row by its $id?
edit - example:
id fname lname
1 john ter
2 mark laken
3 peter lars
4 vlad morch
Basically, how do I set that info above up in php such that I can add new rows without too much trouble and the code will still work, and such that it is possible to output the fname and lname from a $_GET of an id value...
Hope that makes sense!

I'm not understanding why you wouldn't want to store constantly changing data in the database, but here is how I would hardcode it:
$data = array(
'id01' => array(
'firstName' => 'Eric',
'lastName' => 'Smith',
),
'id02' => array(
'firstName' => 'John',
'lastName' => 'Turner',
),
...
);
If you were returning this data in an ajax call I'd do it along these line
echo json_encode($data[$id]);
Of course you should also test if the value in $id is in your data array.

I'm not totally sure I understand what you're looking for, but if you want to be able to edit something inline and save it on form input blur, you will have to look beyond PHP and into an AJAX solution. You will likely still want to back this with a database as PHP scripts don't have a continuous runtime, so you can't read all the data into memory and change it directly in memory through user interaction. So what you'll do is read all the data from the DB into a form, then using a little ajax, you will be able to save the form data back to the database everytime a value is changed.

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.

Get previous set values of php array

I have a method which creates an array of ten elements in php.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
After array is created (In a class via a method), half of the array elements (1 to 5) will be shown on page load and the remaining elements will be shown via AJAX one by one. How can I achive this in php?
Array is populated from random MySQL results.
You have a few options.
Once the original request is fulfilled, if you've only shown 5, the rest are not natively held in memory for you to just go back and get.
You'll need a bit of javascript or something to hold on to whatever the next index is, and go fetch it from the server.
You could, for example, hand the last index array off to javascript and then have it return to the server just to fetch one item.
You'll of course need to write some php to handle the ability to just fetch 1 item at a time specifically but that's on you.
Or, you drop all the images onto the page and just use javascript to hide and show the ones you want.
Your question also might be closed as "too broad" as there are a whole bunch of ways to accomplish what it sounds like you're trying to do and this sort of thing can be googled and answered fairly easily.
Pass the last key you have shown via AJAX and get the others that come after passed key.
For example if you have shown the results
'key', 'key2', ... , 'key5'
then pass the number 5 via AJAX and get the next item
'key' . 5 + 1 that is 'key6'
then pass the number 6 and get the next item
'key' . 6 + 1 that is 'key7'

SQL Database approach - I need your suggestion

Hello everyone and thank you for viewing this question.
Since someone asked what i am doing this for, here is the answer:
An artist asked me to make him a web app to store all his new concerts etc.. Now, when it comes to add the Instruments, artists etc, i could have 10 instruments, or maybe 100.. Everything is set into a form.. Some data is fixed like location, time etc, but this other fields are added dynamically using DOM..
I am building a system in which the user set up a form to be stored on a database like:
Name,Surname,field_1
//Lets say that this is the "fixed" part of the form
//But the user should be able to add 'n' other fields with no limit
//Therefore my problem is that i would end up with a row made of, lets say,
//4 colums
//And another one of, maybe, 100 columns
//
//Then i will need to access these rows, and row one should have 4 cols, row two 100..
//This can't be done in a "traditional" way since each row should have the
//same amount of cols
//
//I thought to create a new table for each submission
//but this doesn't really make that much sense to me..
//
//Storing all the possible fields in a single one and then
//access them through an array ? That would require too much, even since my fields
//should have the possibility to be edited..
//Each field is a mixture of variables then, like
//field1:a=12,field2:b=18.. too complex
Any help would be very appreciated
I would go the one field approach. You could have three columns, Name, Surname, and field_values. In the field_values column, store a PHP serialized string of an array representing what would otherwise be your columns. For example, running:
array(
['col1'] => 'val',
['col2'] => 'val1',
['col3'] => 'val2',
['col4'] => 'val3'
)
through serialize() would give you:
a:4:{s:4:"col1";s:3:"val";s:4:"col2";s:4:"val1";s:4:"col3";s:4:"val2";s:4:"col4";s:4:"val3";}
and you can take this value and run it back through unserialize() to restore your array and use it however you need to. Loading/saving data within this array is no more difficult than changing values in the array before serializing it and then saving it to the field_values column.
With this method you can have as many or few 'columns' as you need with no need for a ton of columns or tables.
In this case I would personally create a new table for each user, with new row inserted for ever new custom field. You must have a master table containing table names of each user table to access the data within later.

MongoDB update query where field name has a DOT (period) in it

So before I ask the question I want to say I do know that Mongo doesn't allow period i.e dot (.) in the field name.
The surprising part is that PHP was able to insert data to mongo with period in it as a field name in a multidimensional array. I use PHP version 5.4 Mongo driver 1.4.
So the array structure is somewaht like:
Array(
["field1"] => "value",
["field2"] => "123",
["field3"] => array( ["abc.def"] => array( ["test"] => "value" )
);
What I want to achieve is changing field2 value from string to integer.
Its huge data and application depends on it, i need to update the type from string to integer or from integer to string, I can control what application inserts in future but what has been entered cannot be changed, Please give me some workaround for the same.
In high hopes somebody will crack an idea upon this..!! ;)
The best workaround that I could find was to use db.collection.update(); though i had to go thru a long procedure of excel and making similar queries for each and every row just after which i realized I could have used db.collection.find().forEach();
So to cut down the solution use forEach to iterate and execute db.collection.update() with condition matching the data and field to update. I formatted the query as a string and then used eval();
If you found a shorter way please do lemme know..!!

More efficient way to format an array

I have a large set of results as an array from a cakePHP model for a csv export. I have been formatting using a loop as shown below. As the number of records grow, this is becoming too slow and giving time out errors. Is there a better way to do this using either cakephp hash or php array functions?
foreach($people as $person){
array_push($results, array(
'SchoolName'=> $person['School']['name'],
'SchoolRef' => $person['School']['ref'],
'firstName' => $person['Person']['firstname'],
'LastName' => $person['Person']['lastname'],
'Year1' => $person['Person']['year_1'],
'StudentID' => $person['Person']['studentid'],
'Email' => $person['Person']['email']
));
}
If you're just outputting to CSV, why not try outputting directly from MySQL (or whichever database you're using).
Eg. http://ariejan.net/2008/11/27/export-csv-directly-from-mysql/
Alternatively, if the data doesn't change, you might be able to presummarize the existing output. So, if you had 10,000 students the last time you outputted the CSV, you could save that CSV and just append the new records. If they do change, you could add a hash of all fields to each record.
Also, if the data doesn't have to be up to the minute accurate, you could presummarize on a daily basis (or whatever interval works for you).
However, without clear indication of where you're at (in terms of record sizes and timeouts), and without a clear idea of where you'd like to be, its difficult to make a specific recommendation.

Categories