• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

How do I randomize quotes on a page (without using databases)

Engaged ,
Apr 23, 2024 Apr 23, 2024

Copy link to clipboard

Copied

Is there a way for a coding fraud like myself to easily implement a "random quote" for my site's front page that does not involve databases? I don't need it to rotate on a timer, I just need the page to display a different quote each time it's loaded. No frills.

 

I'm pretty comfortable with HTML/CSS at this point, but only know PHP includes & strings (so I can't really say I know PHP). Don't know any Javascript at all, beyond just placing existing code where I'm told to place it.

 

In a perfect world, the front page would pull from a sheet located where the web pages are; where every 2 lines is a new quote. So the odd lines would hold the quote, and the even lines the authors of those quotes. (Unless someone has a better idea, but this seemed the most obvious using only 1 sheet.)

 

I assume it would be preferable to do the quote-pulling in PHP since it can do it locally, right? (It's my understanding that this would allow the downloading of only the quote being used, instead of the full list, every time the front page is loaded). There should be between 50 and 200 quotes in all.

 

Could someone help me out with the code, or point me to a tutorial that will walk me through it?

 

Thanks!

 

 

TOPICS
Code , How to , Other

Views

407

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Apr 24, 2024 Apr 24, 2024

You have two approaches among many others :

so as not to flood this thread with code, you'll find links that mirror the pages (just explore the browser page code).

 

  • Either integrate all the quotations into your HTML code, making them all invisible, and activate by JS only the one that has been selected at random by JS
    https://demo.puce-et-media.com/UnderS/quote-1.html 

  • Or work with a JSON file, which is pretty much like a database (sorry that is not your initial request), and you inject the dat
...

Votes

Translate

Translate
Community Expert ,
Apr 24, 2024 Apr 24, 2024

Copy link to clipboard

Copied

You have two approaches among many others :

so as not to flood this thread with code, you'll find links that mirror the pages (just explore the browser page code).

 

 

Personally, I much prefer the second approach, which makes it easier to refresh the data and, above all, separates the structure from the injection using AJAX.

https://demo.puce-et-media.com/UnderS/quote-3.html 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Apr 24, 2024 Apr 24, 2024

Copy link to clipboard

Copied

"Database" means probably a SQL database system, and not a flat file. Many people think that a database needs to be a complex structure with a lot of overhead. But with 10 quotes or something there around, a flat file would do also the affair. 

 

My guess would be: 

  • create an XML file with the quote.
  • write code to read that XML file - that should be easy to find on the web. 
  • display a random quote at a predifined place on your page.
ABAMBO | Hard- and Software Engineer | Photographer

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Apr 24, 2024 Apr 24, 2024

Copy link to clipboard

Copied

You're right but JSON is almost a database some how, look MongoDB, FRD, Couchbase and so on... 

 

Using XML is an other way to go, but except if @Under S. use an XSLT (or other processing integration), XML should be parsed too... and so JSON is for what I think, more accurate for such a purpose, at least that's what seams more customary and contemporary. 

https://demo.puce-et-media.com/UnderS/quote-3.html  produce a complete and functionnal sample using an external JSON file.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 04, 2024 May 04, 2024

Copy link to clipboard

Copied

quote

You're right but JSON is almost a database


By @L e n a

JSON is OK. The problem is the term “database”. Anything that holds data in a structured way is a database. So even a flat, tab delimited file is a database.

ABAMBO | Hard- and Software Engineer | Photographer

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 06, 2024 May 06, 2024

Copy link to clipboard

Copied

quote

Anything that holds data in a structured way is a database. So even a flat, tab delimited file is a database.

By @Abambo

 

I understand the meaning you're trying to convey, and without wishing to be argumentative, I don't quite agree with your terminology. 

 

While a flat, tab-delimited file can technically hold structured data, it lacks the functionality and features of traditional databases, such as the ability to perform complex queries, enforce data integrity constraints, and scale efficiently.

On the other hand, data structures like PHP arrays and formats like JSON offer a middle ground, providing some level of structure and organization to data while remaining lightweight and flexible. However, they still don't provide the robustness and optimization capabilities found in dedicated database systems.

As far as I'm concerned, and with regard to data organization, the term “database” generally refers to more robust data management systems, such as relational or NoSQL databases.

 

This why in my previous comment I added :

quote
  • Or work with a JSON file, which is pretty much like a database (sorry that is not your initial request),
By @L e n a

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Apr 24, 2024 Apr 24, 2024

Copy link to clipboard

Copied

@L e n a Thank you for this, it's very appreciated. I especially like that you can style the quote and author differently in both examples. Obviously I am leaning towards the first answer, as I don't even know what JSON is.

 

However, I get the impression your first example requires that the end-user download ALL 200 quotes every time, rather than just the one they will be seeing on that specific page refresh. Do I have that wrong? If so, ignore what follows; but if not, is there a way to accomplish the same thing without downloading all the quotes on every page load? For example, by storing them in a server-side file that would act as a makeshift database (that a PHP file could then pull 1 random quote from BEFORE sending it [and only it] to the end-user).

 

PS: Off-topic, but how did this thread get marked as "solved" within 24h of it going up, when the OP (me) didn't have a chance to look at the answers yet? I'm not saying I wouldn't have made the same choice myself, only that this is the first chance I got to look at these replies and I wonder if prematurely marking the thread solved discouraged some from chiming in.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Apr 24, 2024 Apr 24, 2024

Copy link to clipboard

Copied

quote

PS: Off-topic, but how did this thread get marked as "solved" within 24h of it going up, when the OP (me) didn't have a chance to look at the answers yet? I'm not saying I wouldn't have made the same choice myself, only that this is the first chance I got to look at these replies and I wonder if prematurely marking the thread solved discouraged some from chiming in.


By @Under S.

 

That was me. I was going through the last dozen or so posts to see if they had been answered correctly. If so, I marked them as answered to help others determine whether to open the post or not. In this case, I was apparently too trigger happy. My apologies.

Wappler, the only real Dreamweaver alternative.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Apr 24, 2024 Apr 24, 2024

Copy link to clipboard

Copied

quote

@L e n a Thank you for this, it's very appreciated. I especially like that you can style the quote and author differently in both examples. Obviously I am leaning towards the first answer, as I don't even know what JSON is.

 

However, I get the impression your first example requires that the end-user download ALL 200 quotes every time, rather than just the one they will be seeing on that specific page refresh. Do I have that wrong? Ifso, ignore what follows; but if not, is there a way to accomplish the same thing without downloading alli the quotes on every page load? For example, by storing them in a server-side file that would act as a makeshift database (that a PHP file could then pull 1 random quote from BEFORE sending it [and only it] to the end-user).


By @Under S.

 

As its just text quotes it really shouldn't matter as the kb 200 quotes would consume would be minimal. If it were 200 images then you might want to consider your options......so storing the quotes as a json file or in a javascript object would be perfectly acceptable, although you have a point, why include 199 quotes which are not needed.

 

If you want a server side approach then use a php object to store the quotes which gets processed at run time and returns to the page only one quote at a time on page load.

 

Json file or javascript object approach is good if youre intending to cycle through the quotes without a page refresh but as you only want a static quote on each page load the php approach would be more appropriate.

 

A similar solution would. be to create an API (Application Program

Interface) end point to store the quotes in json format or javascript object then use something like the Fetch API to return one quote.

 

Plenty of options, it comes down to what you know and what you feel comfortable in deploying.

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Apr 25, 2024 Apr 25, 2024

Copy link to clipboard

Copied

I understand your concern, but for my part, if I had to process 200 quotes on a simple TXT file (which I wouldn't do, I'd use a database), I wouldn't ask myself about the weight, as @osgood_ said, a file containing, say, 200 quotes in the previous format (text, author, date) wouldn't wait, or just about 30 kb.

let's push purity to the limit, by limiting this gargantuan loading...

two schools of thought  :

  • the first would be to use a localstorage, so that once the X quotations have been loaded once, JS would dip into the browser's memory to extract a quotation at random,

  • the second, which seems to be what you want to do, would be to upload a TXT file to the server, containing on each line a quotation, its author and the date, all separated by a character, or series of characters, acting as a separator (of course, we could just as easily use XLS or CSV, but that would require libraries to read these formats, so let's stick with pure TXT).
    PHP could then read this TXT file, count the total number of lines, position its cursor at start of one of these lines at random (as far as I know, there is no way to natively retrieve it), and return the result in JSON format to the client page.

 

What would you like to do, so that we can help you in the best possible way? I must have this type of PHP routine somewhere in my development notes, which would only need basic adaptations to your needs.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
May 03, 2024 May 03, 2024

Copy link to clipboard

Copied

Sorry for taking so long to get back to this, I was under the weather.

 

That second option appeals to me a bit more because I'm already using PHP includes to assemble my pages (header, body, footer) as well as per-page PHP strings/variables to populate the <head> portion in the header file (each page starts with these strings, then includes the header file that will use said strings, then the body, then the footer via another include). But like I said, I only know enough PHP to do what I just described. I wouldn't know where to even begin to randomly fetch a quote from a .TXT file, but I suspect it would ostensibly be treated as just another include, right?

 

I was thinking odd lines for the quote, even lines for the author name, so it would be a pair of strings (to allow them to be styled individually on the output). But I can also do 1 per line if I style them in the TXT file, it just wouldn't be as elegant.

 

How much easier would this all be if I switched to making these quotes images, so we'd just have to load one of 200 such images stored in a given folder? With the same caveat of only loading the one, of course.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
May 04, 2024 May 04, 2024

Copy link to clipboard

Copied

I can't help thinking you are creating a mountain out of a mole hill. Since you use php and are comfortable with it then the simplest and best option in my opinion would be to store your quotes/authors in an organised php array of objects. It's just a simple matter of then using php to randomly select a quote/author from the array of objects on each page load. Everything is processed server side and only the 1 quote is returned to the page client side. The php array of objects acts more like a database of information without being one.

 

Shout out if you want an example of the code to use.

 

Also l cant help thinking that selecting just the 1 quote on page load is a bit simplistic these days. Quite often it's a bit more dynamic to cycle through a limited number of quotes whilst the user is on the page without them having to refresh the entire page to view another quote which is a limitation when using php. Of course you might have good reason to only want to load the 1 quote each time the page is loaded......just something to consider.

 

Using images is a poor option. Consider how many times you might have to export them in the case of spelling mistakes, mis-matched quotes/authors etc which tend to creep in regardless of how careful you are.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
May 04, 2024 May 04, 2024

Copy link to clipboard

Copied

I appreciate your trust in my PHP abilities, but I assure you, they are unfounded. 🙂 Yes, I use strings (a lot) and includes (a lot) but that's literally the totality of my PHP knowledge. I wouldn't even know where to begin to do this.

 

As for the images... like you, I also discourage my designers to use images when live text is an option (soooo much more flexibility w/ text); but in this case, there would be other benefits to it : for one thing, some of these quotes will also be shared on socials, so finding a spot for them on the front page would kill 2 birds with the same image. That's really the only reason I'm inquiring.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
May 05, 2024 May 05, 2024

Copy link to clipboard

Copied

quote

I appreciate your trust in my PHP abilities, but I assure you, they are unfounded. 🙂 Yes, I use strings (a lot) and includes (a lot) but that's literally the totality of my PHP knowledge. I wouldn't even know where to begin to do this.

 

By @Under S.

 

Start by producing an array of php objects, see sample php code below. You can store this array of objects in a seperate php include file, name it 'quotes.php'

 

$quotes = [
[
'quote' => 'A rose by any other name would smell as sweet.' ,
'author' => 'William Shakespeare'
],
[
'quote' => 'Tis better to have loved and lost than never to have loved at all.' ,
'author' => 'Alfred Lord Tennyson'
],
[
'quote' => 'He travels the fastest who travels alone.' ,
'author' => "Rudyard Kipling"
],
[
'quote' => 'No one can make you feel inferior without your consent.' ,
'author' => 'Eleanor Roosevelt'
]
];

 

At the end of the quotes array of objects, after the closing array bracket ]; and still in the 'quotes.php' includes file, add the following:

 

shuffle($quotes);
$selectedQuote = array_slice($quotes , 1);

 

The above shuffles the $quotes array of objects, like a pack of cards, on each page load. The next line selects the 1st object in the array of objects, after the array has been shuffled, so the quote is random. The more quotes obviously the more random the quote will be on each page load.

 

Once the 'quotes.php' includes file has been included/linked to your main page where you want the random quote to appear then in the main page add the following where you require the random quote to appear:

 

<blockquote>
<?php echo $selectedQuote[0]['quote']."<br><span>".$selectedQuote[0]['author']."</span>"; ?>
</blockquote>

 

Style the quote with some css, how you require it to look:

 

blockquote {
font-size: 20px;
}
blockquote span {
font-size: 15px;
font-weight: bold;
}

 

That's it! You should now have a random quote on each page load.

 

As a bonus, but not necessary, you can fade in the quote by adding the <script></script> below to your main page:

 

<script>
const blockquote = document.querySelector('blockquote');
setTimeout(function() {
blockquote.classList.add('fadeIn');
}, 500)
</script>

 

Then updating the css:

 

blockquote {
font-size: 20px;
opacity: 0;
transition: opacity 1s ease-in-out
;
}
blockquote span {
font-size: 15px;
font-weight: bold;
}
.fadeIn {
opacity: 1;
}

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 06, 2024 May 06, 2024

Copy link to clipboard

Copied

quote

How much easier would this all be if I switched to making these quotes images, so we'd just have to load one of 200 such images stored in a given folder? With the same caveat of only loading the one, of course.


By @Under S.

 

Note that images will be less accessible than pure text, will require more advanced support for their readability on small screens (if the quotations are long in terms of the number of words used, including author, date etc.) and their visual updating if necessary will necessarily require more logistical time than a simple CSS modification.

The solution proposed by @osgood_ is very simple to implement, effective and well worth a try. The only complexity will be in generating the PHP table, which can be time-consuming.

But this task will be roughly equivalent whatever the structured TXT file on which you base your logic (PHP array, XML, JSON....) the only file that would be flexible and easy to setup would be a CSV exportable from any spreadsheet program, if by any chance your quotes are already listed in a spreadsheet.

Anyhow, a handmade parser could also easly do the job, what ever the flat file will be, depending on how your datas are currently stored.

For the fun (because the @osgood_  solution requires far fewer lines of coding), I've provided an example (https://demo.puce-et-media.com/UnderS/quote-4.html) of a call to the quotes-500.txt file mentioned in a previous comment https://demo.puce-et-media.com/UnderS/quotes-500.txt. In this way, just a single quote can be loaded from the 500 available.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
May 06, 2024 May 06, 2024

Copy link to clipboard

Copied

LATEST
quote

But this task will be roughly equivalent whatever the structured TXT file on which you base your logic (PHP array, XML, JSON....) the only file that would be flexible and easy to setup would be a CSV exportable from any spreadsheet program, if by any chance your quotes are already listed in a spreadsheet.

By @L e n a

 

I agree, producing any file which contains more than just a few choices is going to take time to build and is prone to mistakes......one miss-placed comma, bracket etc and you have a dysfunctional file............which is why unless you are a methodical worker you should use a database for storing large volumes of data. 

 

200 quotes/authors l would personally use a database BUT it's certainly obtainable without one, you just have to be extra careful when structuring the information if it doesn't already exist in some other usable form whereby you could loop through the data to create a compatible workflow.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 03, 2024 May 03, 2024

Copy link to clipboard

Copied

In fact, instead of having even and odd lines, it's best to place all the quote information on a single line in the TXT file, separated by an alphanumeric character chain that won't appear in any of the strings, such as three pipes 

 

|||

 

In exemple for the following elements

 

The text of the quotation, regardless of the signs used such as , or ;
The author's name
The date

 

You can format them as follows

 

The text of the quotation, whatever signs are used such as , or ;|||The author's name|||The date

 

 

Then placing, in this TXT file, as many lines as potential quotations

For the exemple, and to generate this, I used https://generatedata.com/generator
Choicing to generate CSV, then on the result file , I used a search replace on “,” on “, on ", and finally on “ to be replaced by the |||

or directly with the regular expression (”\s*,\s*“)|(”\s*,)|(\s*,“\s*)|(”

 

The final example of the TXT, containing 500 quotes (lines), can be found at https://demo.puce-et-media.com/UnderS/quotes-500.txt

The question now is, do you want to use an include for the PHP algorithm or a JS invocation so that you can eventually reload a new quote from the host, without having to reload the entire hosting page (more flexible)?

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
May 04, 2024 May 04, 2024

Copy link to clipboard

Copied

quote

In fact, instead of having even and odd lines, it's best to place all the quote information on a single line in the TXT file, separated by an alphanumeric character chain that won't appear in any of the strings, such as three pipes 

 

Well, I'm sure embarrassed now. Using a divider instead of using odd/even lines never even occurred to me; but it makes all kinds of sense. Guess this is how the pros do it. Single-line is fine, then. 🙂

 

quoteThe final example of the TXT, containing 500 quotes (lines), can be found at https://demo.puce-et-media.com/UnderS/quotes-500.txt


I look forward to studying this in the next couple of days, thanks!

 

quote

The question now is, do you want to use an include for the PHP algorithm or a JS invocation so that you can eventually reload a new quote from the host, without having to reload the entire hosting page (more flexible)?

 

If I understand your question correctly, the JS invocation would be more useful if the quote was rotating on a timer instead of page refresh, right? I honestly don't have any plans to do that, once per reload is really the plan.

That being said, how difficult would it be for the code to randomize images the same way? 500 images in a folder, but loads only the 1 for the session. Could there be some sort of toggle between the two modes (text or images)? I could put root-relative paths to each image in the TXT file if that helps; unless the code is smart enough to bypass the TXT list and just pick a random JPG/PNG from a folder filled with them.

 

If this is even a little bit of a bother, let's ignore that. The images are more of a "nice-to-have" than a need. 🙂 Figured it wouldn't hurt to ask.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
May 04, 2024 May 04, 2024

Copy link to clipboard

Copied

quote

 I wonder if prematurely marking the thread solved discouraged some from chiming in.


By @Under S.

I doubt that a question marked with a correct answer does not attract different, additional answers. If someone has a nice solution, they will chime in. So no harm done.

 

Indeed, marking an answer correct in an early stage will help others searching for a similar topic. Many threads simply get forgotten, when they travel down the page, to the third or fourth page.

ABAMBO | Hard- and Software Engineer | Photographer

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines