Load random profile on index page, jQuery - php

The current site for which I'm re-designing and developing is http://www.gdi-brighton.co.uk/. Most of the changes are cosmetic, and I've stripped the nav down to 3 links: GDI-Brighton (home page), Profiles and News. The site uses a custom CMS built in PHP from a previous student.
When visiting the home page I'd like for a random student profile page to load. There is an id and name_url for each student, which you can see when clicking on one of the thumbnails for a student on the current site.
I'm familiar with Math.floor(Math.random()) but have no idea where to start concerning this.
Please let me know if you need any more information. Thanks for your help.
Ryan

If you are using a relational database and the ids of the student entities are following a sequence (e.g. increasing by 1 etc.), then you can get the current sequence number with a single simple query to your database (you can google for nextval() of a sequence on the web). Assign this number to a variable and use it as an upper limit when you are generating a random student id. To handle the cases where the generated random number doesn't correspond a valid student id, (i.e. some of the students might have been deleted from the database.), you can just use a while loop that contains the random id generation code but exists on a valid id generation. After that, just query the database with this valid random id and fetch the url of the profile of the corresponding student.

You can do this in your PHP. Here is the concept (not actual working code):
$result = mysql_fetch_row(mysql_query("SELECT MIN(id), MAX(id) FROM table"));
$min = $result[0]; $max = $result[1];
$id_to_retrieve = rand($min, $max);
$random_student = mysql_query("SELECT * FROM table WHERE id = {$id_to_retrieve} LIMIT 1");
Note that this does not check whether the record with that ID exists in the last query. If it doesn't exist you can get another random ID or get the closest ID that does exist.
After all this is done you output the random student card and retrieve the result with jQuery (with load() or something--you don't need to pass any variables to PHP for this).

You can pick a random url on the client-side, too with this code:
var url = $('li.illustration:eq('
+ Math.floor($('li.illustration').length * Math.random())
+')>a').attr('href')
But it feels too hackish and the server seems the best place to do it.

You could use something like this??
var randomnumber = Math.floor(Math.random() * 3);
if (randomnumber == 0) { DisplayProfile(0); }
if (randomnumber == 1) { DisplayProfile(1); }
if (randomnumber == 2) { DisplayProfile(2); }
DisplayProfile would contain your JQuery code that would organise your page to display the right info based on the information passed (in my example 0, 1 or 2)

Related

Defining an offset when using php array_search / array_column to find a value (eg ignore 1 matching result, find the next)

I have two main tables for rail schedules, which are
Timetabled visits - a list of planned call times for services
Actual visits - contains a list of realtime reports for visits , ie the actual visit times.
Timetabled visits, containing a list of locations being called at, can have the same location more than once
(in the event that the service goes into a terminus station to reverse, passing one or more of the previously passed locations on the way back out)
A column in the timetabled visits table, contains an instance count, which will be null unless the service has passed this location earlier in the timetable, in which case the value of this "visit instance" column would be 2 , because it is the second visit.
Now what I am doing is I am displaying a list of the visits, their planned call times, and their actual call times.
The way I am doing this is I am storing all of the planned calls and call times into an array such as that below.
(This is the result of a mysqli prepared query, shortly after the results have been binded to a variable.
while($stmt->fetch()){
$reports[$count]['tiploc_code'] = $tiploc_code;
$reports[$count]['stanox'] = $stanox;
$reports[$count]['fn'] = $fn;
$reports[$count]['arrival'] = $arrival;
$reports[$count]['departure'] = $departure;
$reports[$count]['pass'] = $pass;
$count = $count + 1;
}
Then im doing another query to select the realtime performances for the above. This realtime performance table does have different column names.
while($stmt->fetch()){
$call[$calls]['tps'] = $tps;
$call[$calls]['stanox'] = $loc_stanox;
$call[$calls]['next'] = $next_stanox;
$call[$calls]['actual'] = $actual;
$calls = $calls + 1;
}
Now im using the array search feature of PHP.
Note that this is inside a while loop for the html table which I am displaying the visits. For each visit, I am populating the first part of the array_search with "stanox" - a unique number which is the location ID.
Then in array_column im looking up the realtime call which has the same location ID as in $reports ID, thereby, getting the realtime data for that location visit.
$search_index = array_search($reports[$index]['stanox'], array_column($call, 'stanox'));
Now in the html table, show the actual call time.
$actual = $call[$newid]['actual'];
echo $actual;
My problem?
Well as mentioned earlier, the same location can be called at twice.
So instead, what I want to do is use the "visit instance" field, as an offset.
If this is the second location call, I want to ignore the first, and show only the most recent call time based on instance. Likewise, if its the third time it has visited this location, I need to ignore the first 2 reports.
Is this possible?
Many thanks in advance.

How to limit mysql rows to select newest 50 rows

How to limit mysql rows to select newest 50 rows and have a next button such that next 50 rows are selected without knowing the exact number of rows?
I mean there may be an increment in number of rows in table. Well I will explain it clearly: I was developing a web app as my project on document management system using php mysql html. Everything is done set but while retrieving the documents I mean there may be thousands of documents.
All the documents whatever in my info table are retrieving at a time in home page which was not looking good. So I would like to add pages on such that only newest 50 documents are placed in first page next 50 are in second and so on.
But how come I know the exact number of rows every time and I cannot change the code every time a new document added so... numrows may not be useful I think...
Help me out please...
What you are looking for is called pagination, and the easiest way to implement a simple pagination is using LIMIT x , y in your SQL queries.
You don't really need the total ammount of rows you have, you just need two numbers:
The ammount of elemments you have already queried, so you know where you have to continue the next query.
The ammount of elements you want to list each query (for example 50, as you suggested).
Let's say you want to query the first 50 elements, you should insert at the end of your query LIMIT 0,50, after that you'll need to store somewhere the fact that you have already queried 50 elements, so the next time you change the limit to LIMIT 50,50 (starting from element number 50 and query the 50 following elements).
The order depends on the fields you are making when the entries are inserted. Normally you can update your table and add the field created TIMESTAMP DEFAULT CURRENT_TIMESTAMP and then just use ORDER BY created, because from now on your entries will store the exact time they were created in order to look for the most recent ones (If you have an AUTO_INCREMENT id you can look for the greater values aswell).
This could be an example of this system using php and MySQL:
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 50;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM your_table LIMIT " . $offset . "," . $items_per_page;
I found this post really useful when I first try to make this pagination system, so I recommend you to check it out (is the source of the example aswell).
Hope this helped you and sorry I coudn't provide you a better example since I don't have your code.
Search for pagination using php & mysql. That may become handy with your problem.
To limit a mysql query to fetch 50 rows use LIMIT keyword. You may need to find & store the last row id(50th row) so that you can continue with 51th to 100th rows in the next page.
Post what you have done with your code. Please refer to whathaveyoutried[dot]com
check this example from another post https://stackoverflow.com/a/2616715/6257039, you could make and orber by id, or creation_date desc in your query

Safest way to save data for paginating a query

I have a query which uses a list of IDs as input (eg. "WHERE XX IN (1,2,3,4) ) and the results are too many to be shown on a single web page. What I plan to do is to limit the results and paginate them. With MySql I added "LIMIT X OFFSET Z".
My problem is now how to pass the information to every single page. I could generate the pagination links with the list of IDs in it (eg. <a href='link.php?i=1,2,3&page=1>1</a> ) or I could store them somewhere. Since I'm using php I was thinking to use SESSION to store them or write them in a cookie for now. Using a DB is overkill? I can make a simple solution with cookies for now and change it later. Having IDs in a cookie isn't a security problem. Even if an user add ids to that list doesn't matter.
There are some answer on SO, but none seems to address all various possibilities.
Yes, using the database is overkill. Depending on you web app both Session and URL are good ways to solve this.
I think that the best solution of these two is to include pagination in the URL. This will help a lot when sharing links to your app. (Immagine sending a co-worker a link to a page in your app... and you are using sessions for pagination)
Have a constant in your code for the "page size" and then multiply it by the page number in the query string to get the offset. Here is a simplified code sample to illustrate:
<?php
$limit = 30; // records per page to have more/less change this
$page = 0; // if not set, $page is 0 (first page)
if (isset($_GET['page']) {
$page = (int)$_GET['page']; // cast to int, to drop funny chars etc.
}
$offset = $page * $limit;
$query = "SELECT * FROM a_table WHERE some_col IN (1,2,3,4)";
// ... then, to add offset data to your query:
$query += " LIMIT $limit OFFSET $offset"; // mind the single space
Your links then should include the page arg: echo "link.php?i=1,2,3&page=".$page+1; incrementing for next page (or have a loop for printing links to the next n pages).
A word of warning:
Do not use cookies to store pagination data. Cookies are data that needs to be sent (sometimes unnecessarily) back-and-forth between request-response lifecycles. And you shouldn't trust cookies in the first place ;)
It looks like your are getting the data for WHERE XX IN (1,2,3,4) from your query string. Be aware that doing this wrong, leaves you wide open to sql injection.

how to use predefined formula from database and use it in javascript?

I have a page where user can select and define their own formula for calculating "WORKLOAD" of lecturers
For example, (Jobtypevalue + Creditpoint) * Number of Students
I store this defined formula by the user in database.
Now, I want use this formula in another page which are fields (textbox) through which user can enter any number and at the bottom I need to calculate by using values entered by user based on the predefined formula from the database
If user enters Jobtypevalue = 7, Creditpoint = 3 and Number of students = 10
Then, at the bottom of page, I need calculate [(7+3)*10] and display "Workload = 100"
How can I do this using javascript ? Since, I have the formula on pageload from database and values are entered by user later, thought it is better to calculate the workload using javescript(client side)
You can try like this but your variable name should follow proper naming convention
//values in variables
var Jobtypevalue =7;
var Creditpoint = 3;
var Number_of_Students=10;
//use eval to evalute.
alert(eval("(Jobtypevalue + Creditpoint) * Number_of_Students"));
You can check this DEMO

Jquery - finding range between two unique id's in mysql

Another question which has me perplexed:
I have a table which enables users to enter as many rows as they like based on their userid and unique id (auto incremental).
I need to be able to get this information from mysql and place the previously entered information into the fields on the web application (they may need to be edited before confirming that they're correct).
I store the total number of records for that user so far in one variable, and the total number of records for all users in another variable.
The question is: how do I get the range of ids for the records the user has already enterered.
Example: User 1 has 2 records in the database and there is 7 in total (5 by another user). How would I get the unique IDs of the 2 records that already exist?
Thanks for any suggestions you may have!
I'm not entirely sure what you mean, so this may or may not be helpful.
This SQL should give you the record ids:
SELECT id FROM tableofuserrows WHERE userid = [User Id]
You can then fetch this from the database with PHP, e.g.
$q = mysql_query('SELECT id FROM tableofuserrows WHERE userid = ' . (int) $_GET['userid']) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($q)) {
$result[] = $row['id'];
}
mysql_free_result($q);
echo json_encode($result);
So if you wanted to fetch these IDs from the browser using jQuery:
$.getJSON("http://url", { userid: 3 }, //set userid properly
function(data){
$.each(data, function(i,id){
//do something with the recordid
alert(id);
});
}
);
Do you have to do this dynamically using jquery or can you load the fields in the web form with the rest of the page using php ?
Either way, you're going to need to query the database table for all rows where userid = a certain user. Once you get these results, you'll need to create a page you can call and get results from using jquery if you're going that route.
Someone just posted what I'm saying with code examples :-)
I decided to use MIN(id) in the select statement, counting how many rows there are and then populating the form fields accordingly, starting with the min value and adding the counted rows. Works well ;)

Categories