I hope somebody could help me out, I have no idea how to solve this problem.
so first, here's a php array: http://pastie.org/private/s99d8w7cbhjd2yucdijw
if i do print_r for mysql ID=1, it would be like that: http://pastie.org/private/5b9n86dnxlp96afpiwvjeg
now i'm pushing data to javascript:
var sec_0_f = [];
<?php foreach ($action_events["2nd"]["0"]["Free"] as $key => $value) : ?>
sec_0_f.push('<?php echo $value; ?>');
<?php endforeach ?
and so on..
Array contains messages, which varies each time, depends on mysql ID call. However, I would need to make some sort of a sequence. So message would display in #notice ( http://pastie.org/private/ge5ceqpihkbl82hs3ya3g ). And then each #notice would trigger an animation, so #notice animation1, #notice animation2 etc, depends on number of messages.
So there would be max 20 javascript arrays filled with data..
Here comes the needed "system", which is splitted into 2 sections. So the 1nd one would sequentaly display 2 "Free" and 1 "Corner" message in #notice and each will trigger the function, but not in the exact order, if you know what i mean. For each messages of "Free", "Corner" etc, I have premade functions. Names of functions are "Event"+"Team"+"Number".
Here's example: http://pastie.org/private/9j6rcf5f8lb5jmegbbqtog
(would actually need to put some callback there, when it's done..). But for each mysql ID, the same function would need to be grabbed.. So I'm thinking about creating additional field under each ID which some data and make sure that each time calls the same..
Sorry for a long message, but I've been trying to come up with something for days, without success. Does anybody have any idea how should I approach this? Did I take the right method to do this?
If I get it right, is this (click for demo) what are you trying to do?
It basically fills the actions in an array (like you do in php), then steps in that array, takes the first object and display it, then waits a second, then goes to step into the next object, and so on till all the actions are sequentially displayed.
Related
For my current project I fill an array by using the sql query
"SELECT names FROM students";
and throwing every response into an array named $names_array.
Then I use
foreach($names_array as $value) {
echo "<option>".$value."</option>";
}
to fill up a datalist with options so you can find a name using the list autocomplete or enter a name that is not yet found in the array.
Now here is the issue, if I click on an existent name I need to take a couple of other pieces of data from the table and fill in other input fields automatically.
So lets say the database table per student also has their age, birth, guardians number & guardians email.
How do I check if the typed in student already exists and if they do, get their additional data from the table?
If I can somehow get the entered name in PHP I could just look through the table which would be a lot faster but I've tried doing this and I can't seem to get it done.
I was using a very inefficient method where I json_encode an array gathered from the sql query
"SELECT * FROM students";
and then use
echo "<script>var names = ".$names_json."</script>";
to be able to fetch it in js. Now after parsing it and looping through it I can find my neccesary data but considering the database table already has 6000 options and is still increasing it's starting to take a while to loop through it, especially if the name I'm searching for is near the end of the array. Now this can take anywhere from 1 to 15 seconds where the website is completely frozen and it looks like it crashed until it's done and does what I need to do with the data.
I've tried using the solution offered here but that doesn't seem to change anything.
Please, does anyone know of a better way to do what I'm essentially already doing without temporarily freezing the website? Or maybe a completely different way of getting the other pieces of data? Thanks in advance.
for prevent the script loading to freeze the website load, you can add defer attribute, like so:
echo "<script defer>...some long logic....</script>";
For search easily through the array, you can sort it by the searched value, then use binary search
Also, you can store it in literal object, where the key is the name, and the value is object of all the student data. it will require some memory space, but make the search super fast
At first on server side - pagination/limit, do not "select all"
SELECT names FROM students WHERE names LIKE ? ORDER BY names LIMIT 20;
Second on client side - lazy loading via ajax, but first after, for example, user typed 3 chars of name.
I guess I should answer this question if anyone else ends up stumbling onto the same issue.
I change the foreach loop slightly by adding the ID as a data-id to the options
foreach($names_array as $value) {
echo "<option data-id='".$value['names_id']"'>".$value['names_name']."</option>";
}
Through js (and jquery) you can obtain the id of the chosen student like this:
currentVal = $("#inputID").val();
currentID = $("#listID option[value='" + currentVal + "']".attr('data-id');
now you can find the index of the chosen student in the namesArray doing this:
if (currentID != undefined || currentVal != "" || currentVal != " ") {
arrayIndex = namesArray.findIndex(x => x.names_id == currentID);
currentArray = namesArray[arrayIndex];
}
where namesArray is the var 'names' json parsed which I echo in the script seen in the question and the if block prevents it from even checking the array if the id is undefined or the input is empty.
So i'm looking for an efficient way to work with the sql data i'm going to store.
For now it's pretty simple, i have a table with multiple attributes that i want to collect via js.
I don't know if putting this into an HTML table would be the best option, i don't think so since i believe it would make things harder to get rows with specific attribute.
The information i want to extract from the database would look like this :
Event1 ID1 start end duration week attribute1 .... attributeX
Event2 ID2 start end duration week attribute1 .... attributeX
..
If the user asks for events from week n°3 i want to connect to the database only once, get all the events from that week, and then i have to process that data so that specific events with specific attribute values would appear at some place in the page.
Do you guys know what's the best way to store the data in order to do that kind of thing ?
On the PHP side you can store your data like that :
$array = [];
$array[] = [
'event' =>Event1,
'id' => ID1,
'start' => start,
'end' => end,
'duration' => duration,
'week' => week,
'attributres' => [attribute1, ...., attributeX]
];
Then you should use the json_encode method to send it back to the AJAX. And like that you should have a nice and pretty JS Object that you can use to do hat you want.
Just as a memo for me, and eventually to help people out.
Found out this is the best way to do things yesterday :
while($row=$query->fetch()){
$data[]=$row;
}
echo json_encode($data);
Where $data is the array that will contain all the sql informations like so :
$data['0']['nameEvent'], $data['0']['id'] ..... $data['0']['attributeX']
...
$data['n']['nameEvent'] ....
This type of storage is very convenient and makes it easy to fully mess with the DB informations as i wish.
This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 6 years ago.
i've been experiencing a problem recently. A couple of months ago i developed this code and it was working, now i tried running the code again and it is simply not working. I will explain
I have a javascript file which queries data to a php file, that is supposed to query data from 3 tables, A, B, and C in form of an INNER JOIN. Like i said before it was working, and now it simply returns and error to my javascript due to that it returns and empty array and it gives me the JSON.parse error on my javascript.
Ok moving on, Whenever i push data obtained From tables A and B, the php returns a complete array, but if I push the results from table C, my php returns and empty array. I've tried running my sql to check if it is wrong, and my sql queries fine on my console. Its so frustrating because i see that the results are returned on the console form the 3 tables, but if i try to obtain them from my php file, it will return an array if it contains the data from tables A and B, but as soon as i include the results from table C, it simply returns empty.
It has happened to me before but i simply cannot find and answer as to why it is happening because in some files it does work when i query multiple tables as up to 5 tables long but on some it simply wont work.
Here is my php code:
<?php
if(!isset($_POST['Select']))
die("You Do Not Have Permission To Access This File");
require_once 'DB_Connect.php';
$db = new DB_Connect();
$conn = $db->connect();
$sql = "SELECT AssignedStudent.Student_ID, Programs.name, Student.name As StName, Student.email FROM AssignedStudent INNER JOIN Programs ON AssignedStudent.Programs_ID = Programs.ID INNER JOIN Student ON AssignedStudent.Student_ID = Student.ID WHERE AssignedStudent.status='Active' ORDER BY Programs.name, AssignedStudent.Student_ID ASC";
$resultsAssigned = mysqli_query($conn, $sql);
$data = array();
$data2 = array();
if(mysqli_num_rows($resultsAssigned)>0){
while($row = mysqli_fetch_assoc($resultsAssigned)) {
$StProgam = $row["name"];
$StID = $row["Student_ID"];
//$StName = $row["StName"];
//$StEmail = $row["email"];
$StName = "das";
$StEmail = "das";
//echo $StName."-".$StEmail."\n";
array_push($data, array("ProgramName"=>$StProgam,"StudentID" => $StID, "StudentName" => $StName, "StudentEmail" => $StEmail));
//$data[] = array("ProgramName"=>$StProgam,"StudentID" => $StID, "StudentName" => $StName, "StudentEmail" => $StEmail);
}
}
echo json_encode($data);
?>
To close off, if any body is reading this post, please focus on what is inside the While loop because everything else is working 100%, ive already tested it before. Inside the while loop i have some pieces of code commented which demonstrate my error that i was talking about. if I uncomment these two lines:
//$StName = $row["StName"];
//$StEmail = $row["email"];
my php will return an empty result to my javascript, but these two lines work fine:
$StName = "das";
$StEmail = "das";. As i mentioned before I access data from 3 separate tables, and as soon as i include data from table C, which are the variables that i metioned just now, my php simply wont return any value but as soon as i ommit them, it works just fine.
Only those 2 lines produce me the error, which basically is absurd because i obtain full results from my query, proven on my console, but as soon as i access them from row[] result and push it into the data array, it returns an empty array.
Moreover, i tried echoing the results when i obtain them from the row[] and it does return the results, but as soon as i push them into the array it stops working. To explain it i push $StName = "das"; $StEmail = "das"; into my array it works fine, but if i push $StName = $row["StName"]; $StEmail = $row["email"]; it wont work, yet if i echo the results in these variables, they do show.
The problem is i cant push into my array when the results in $row["StName"]; and $row["email"];
Here is a screen shot of the query from my console:
Lastly, im running the code on my localhost using xampp, i've uninstalled my xampp that was from 3 years ago and updated to the latest version and still have the same error. Its so frustrating. I know it might sound out of context but could it be hardware problem from my laptop?
P.S. This same code with the same database on my online server WORKS COMPLETELY FINE 100% but on my machine local host it gives me and empty array as result.
You say it works on one server, but not on your local server. Something's different between the two, maybe in the PHP configuration, maybe in the MySQL setup. But that may be difficult to diagnose unless you know what changes have been made between when it worked and now.
A simpler approach might be some simple debugging of the PHP script.
Try calling the php file directly from a browser (you'll have to comment out the security check) with some debugging echo statements added.
My suggestion is to add a debug line inside your while loop and echo the $row variable using print_r:
echo "<p>row:<pre>".print_r($row,true)."</pre></p>\n";
Then, at the end of the while loop, echo the $data array:
echo "<p>data:<pre>".print_r($data,true)."</pre></p>\n";
In your SQL statement, you alias one field (StName), but not the email field. Looking at what is returned by the first echo above will confirm the field names returned by the query. Looking at the results of the second echo may reveal some difference in the structure you are expecting. During testing, you may want to add a limit 0,4 statement to the SQL statement to limit the results to a manageable output size.
After some digging i found out that the problem to my php is that some records returned from the database contained some characters that were not supported by the json_encode, so what i did is i added the following line after establishing the connection to the server:
mysqli_set_charset($conn, "utf8");
and the problem was solved, it returned all of my records.
this time I'm looking for something really special.
In my PHP page, I got a table generated by a Javascript, here is the example :
Example Page
This table is racing game results. I didn't write the JS, and I can't change the format of the results.
What I need is to parse these results to get variables, to generate championship results giving points to guys, adding points of multiple series, etc...
I tried :
Parsing with DOMDocument, also substr, but as it's JS generated it can't work.
>>this solution<< which sounded good but it doesn't work.
Do you guys have any idea to get an exploitable array ?
If not, what do you suggest as alternative solution ? I'm not able to reproduce the JS in a PHP function, too hard.
Here is the JS : click
Thank you !
Here's how you'd be able to parse the initial array in PHP:
$url = 'http://mxs-concept.com/liveresults/test.php';
$page = file_get_contents($url); // fetch the page
preg_match('/resultslines=(.+)print_race_analysis/sim', $page, $matches); // find javascript array
$js = preg_replace('/,\s+\]$/', ']', $matches[1]); // fix last comma before "]"
$array = json_decode($js); // decode the array
var_dump($array); // see the exact array you had in javascript
However, after reading your edit, it seems that you'd need more work if you're taking the PHP way. You might want to try to install NodeJS and make it parse the JS but might be an overkill. If I would you, I'd translate the JS to PHP even if it will take a day just because NodeJS might take a week instead.
So I made a form using JavaScript that allows the user to put in how many ever inputs they want, but I ran into two problems. The first is that if they put extra fields and don't use them I run into errors on the other side since there is no input in those fields, and the second is that they cannot go back and edit the input if necessary. I am relatively new to JavaScript so I am not sure how to fix it, but if someone could help fix the input problem by auto deleting any empty fields that aren't used when submitted and add a protocol to be able to edit the input, I would be very grateful. Thanks so much for all your help and the code is below!
In your PHP you should always check to see that your request variables aren't empty before attempting to use them. The foreach loop should look more like this:
foreach ( $_POST['data']['address'] as $address ) {
if ( !empty( $address ) ) {
$addresses[$counter] = $address;
$counter++;
}
}
This will prevent the $addresses array from having empty fields.
As for the the users not being able to "go back" and edit input fields, it's not apparent from your code sample why that would be the case. If you mean you want your users to be able to change their data after it has been submitted and processed by the server you won't be able to do it with small modifications to your existing code. You'll need to add significantly more functionality to both the front and back ends.
There are few ways to handle this, but they involve re-structuring your application in a few ways.
Restrict the system so they can't add a new address until the previous ones are filled in.
Before submitting the form, run a sanity check and remove any blank addresses, renaming the fields as needed.
Convert the form to an Ajax object and submit that way. You'll need to rework the backend to make sure it accepts the JSON properly.
Make your PHP smarter and better with checking/validation of incoming data.
I would just check for an empty string, and continue if it is empty... trim the $address to weed out inputs that are just spaces.
foreach ($_POST['data']['address'] as $address){
if(empty(trim($address)) continue;
$addresses[$counter] = $address;
$counter++;
}