Get previous set values of php array - php

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'

Related

How to determine that POST method more than 1000 variables by PHP default?

I have a table with multiple inputs in separate forms which would like each user has 15 from inputs to be passed. In this case I have around 80 users in the table and I have to post all the form inputs at once to the server site.
However, I received PHP warnings about receive more than 1000 input variables and suggest to increase the max cap for the input variables length. I only receive around 75 users form inputs in this case. The form inputs are passed through jQuery method .serialize()
I wonder how to calculate the input variables count in php... I've tried to use count($request->getParams()) and it returns 15 (outer layer keys count) which my returning variables is in this way:
name => array (
[0] => john
....
[79] => Serene
),
age => array (
[0] => 21,
....
[79] => 24,
),
....
In this case, is the variable count in 15 keys times with 80 key-value pair which is 1200 variables in total? Is this the way that PHP to calculate the input variables by calculate all the incoming form inputs?
I know how to count multidimensional array but I just wonder that the PHP whether it determine the input variables length by counting the outer layer keys count or all the keys in the input variables?
(p.s. the table has to post all user information form input due to the design of the code)
If posible post data in json format by serializing the form. And you can parse json on server side to get all fields. So you can post data in single parameter only
Below is jquery exapmle to serialize form data to json
var data = $('#myForm').serializeArray();
$.post("page.php", data);
On php side can get assosiateve array in key value form
$data = json_decode($_POST['data'], true);
You mean count($_POST, true) ?
count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
mode
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
I suppose this is more proper:
count($_POST, COUNT_RECURSIVE)
Special attention to recursively count the array
Of course by the time you can count them you may have already exceeded the limit, which is for HashDos (array hash table collision attacks).
I watched a good webinar by the Boss man "Rasmus Lerdorf" (the guy that invented PHP) a few years ago now on it ( on HashDos not counting arrays ... lol ).
*PS - if you didn't know count could take 2 arguments, I won't say how long it took me to figure that one out....
You can do following thing:
Sharing our experience of multiple rows having number of fields.
For every user row, add a checkbox Edit, by default unchecked.
And all of row's fields disabled.
If you want to edit user row, then click the checkbox.
Form elements from that row will be enabled.
Its not likely that user will add data to 75 to 80 rows in a form.
Therefore, only those rows will be posted which are enabled by the user.
Disabled form elements do not submit.
And the count will be most probably less than 1000.
try using this way hope it will help you
$count = 0;
foreach ($array as $type) {
$count+= count($type);
}
check this

inRandomOrder() query with ajax return same elements

I have a query with Laravel
$query = Work::inRandomOrder()->where('orientation', $request->get('orientation')->paginate(11);
And I have a "load more" button who call 11 others works with each click.
But, I would like display my data in a random order. But with this query, he repeats to me several data. So in my list of works, I have 2 or 3 times the same and obviously, it's not good. Is there a way with RandomOrder () to avoid duplicates?
Thank you
I believe data is randomized each time the script is loaded, including each time loading dynamicaly 11 more data fields. One way to achieve this it to randomize, store the data in a user's session variable and then get next elements from it. However this might be very heavy.
I would go to a some easily predictable mathemtics, which will look 'random' to the end-user. For example you can get each N-th entry of a query like 1-st, 5-th, 9-th, 13-th ... if N=4 and store just the number N in the user's session.

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.

array type of question

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.

PHP/MySQL: Best way to fetch new entries?

We've got some kind of groups at our site where group members could put messages. I want to notice the members of each group when there's new entries.
What's the best way to do this?
If you want to notify them immediately, you could just send them an email/whatever immediately as you store the message.
Otherwise you could store the highest 'read' messageid against each user, then you can fairly easily fetch any subseqent messages.
If there possible will be a lot of messages per group than it worth to have group-level field like LastNotificationTime and then schedule task to look for messages with created time later that current LastNotificationTime value (then send report about them to users) and update LastNotificationTime to current time.
Even better is to have user-level LastActivityTimeInGroup field and compare message creation date with it (maybe adding some minutes to it for smoother experience) so only the inactive at that time users will receive any messages and if any not more than 1 per task interval time.
I currently use a key store for this purpose (memcachedb). what you could do is to add a key such as 'messageread_{message.id}_{user.id}' set to whatever value you choose (i just use int 1), then use a memcached client to do a getmulti for all the messages the user has (as an array of keys posted above). any key that is returned is read :)
I use this method with a 60 second cache of this query itself to give users an unread message count with great results.
http://memcachedb.org/
i originally used a highest id type check and soon after switched to a multi-level comment system, thus making highest id moot in that context (as you could end up seeing a comment and miss one that is a reply). so far this method has been very fast.
to do something like this you would need to install the memcache or memcached client from pecl here http://pecl.php.net/package/memcache and here http://pecl.php.net/package/memcached respectively. do an install of memcachedb (will need a box with shell access), and start up the service.
client pseudo code would run something like this:
// get messages a user is part of
code...
// build an array of memcachedb keys from that list, set key to message_id to reference later
$keys = array();
foreach($mresult as $current){
$keys[$current['message_id']] = 'messageread_'.$current['message_id'].'_'.$myid;
}
// using the "memcached" php client
$result = $memcacheobj->getMulti($keys);
getmulti returns an associative array in the struct of 'memcachekey' => 'memcachevalue'
// loop over result, removing found results from keys
foreach($keys as $key => $val){
if(isset($result[$val])) unset($keys[$key]);
}
// cleanup to have array of unread messages, flip array to set values to message_id, reset array keys with array_values (optional)
$unread = array_values(array_flip($keys));
now you have an array of unread messages in the structure of:
array(
0 => 12,
1 => 23,
etc...
)
this is just a rough mockup of the process, im sure some cleaning up could be done to optimize this :)

Categories