I have a site that on the home page has a feature splash which consists of a couple of sentences of text.
Say if I had a file with about 5-6 different small blocks of text like the above that I wanted to echo out randomly each time someone hits my homepage, what is the best way to do this in php?
Thanks for your help
Initialize the text blocks in an array and choose one using the rand() function.
Read the documentation about file() and use array_rand():
$sentences = file('your-file.txt');
$keyNr = array_rand($sentences, 1);
var_dump($sentences[$keyNr]);
I would suggest storing your texts in a database and then selecting a random row from it with a query like the following:
select randomQuote from someTable order by rand() limit 1
This way you will never have to change your code, and you can simply update, insert new rows into the database or delete old ones etc.
Just use array_rand() of PHP
<?php
$strings = array('Welcome Ryan', 'Welcome John', 'Welcome Mark', 'Welcome Mike', 'Welcome Jenna');
echo $strings[array_rand($strings)];
Related
I have looked on stackoverflow for a solution to this however couldn't find a good answers which outlined the issues I was having; Essentially what I'm trying to achieve is to array out 15 of the most frequent tags used from all my users subjects.
This is how I currently select the data
$sql = mysql_query("SELECT subject FROM `users`");
$row = mysql_fetch_array($sql);
I do apologise for the code looking nothing like what I'm trying to achieve I really don't have any clue where to begin with trying to achieve this and came here for a possible solution. Now this would work fine and I'd be able to array them out and however my problem is the subjects contain words along with the hash tags so an example room subject would look like hey my name is example #follow me how would I only grab the #followand once I've grabbed all the hashtags from all of the subjects to echo the most frequent 15?
Again I apologise for the code looking nothing like what I'm trying to achieve and I appreciate anyone's help. This was the closest post I found to solving my issue however was not useful.
Example
Here is three room subjects;
`Hello welcome to my room #awesome #wishlist`
`Hey hows everyone doing? #friday #awesome`
`Check out my #wishlist looking #awesome`
This is what I'm trying to view them as
[3] #awesome [2] #wishlist [1] #friday
What you want to achieve here is pretty complex for an SQL query and you are likely to run in to efficiency problems with parsing the subject every time you want to run this code.
The best solution is probably to have a table that associates tags with users. You can update this table every time a user changes their subject. To get the number of times a tag is used then becomes trivial with COUNT(DISTINCT tag).
One way would be to parse the result set in PHP. Once you query your subject line from the database, let's say you have them in the array $results, then you can build a frequency distribution of words like this:
$freqDist = [];
foreach($results as $row)
{
$words = explode(" ", $row);
foreach($words as $w)
{
if (array_key_exists($w, $freqDist))
$freqDist[$w]++;
else
$freqDist[$w] = 1;
}
}
You can then sort in descending order and display the distribution of words like this:
arsort($freqDist);
foreach($freqDist as $word => $count)
{
if (strpos($word, '#') !== FALSE)
echo "$word: $count\n";
else
echo "$word: does not contain hashtag, DROPPED\n";
}
You could also use preg_match() to do fancier matching if you want but I've used a naive approach with strpos() to assume that if the word has '#' (anywhere) it's a hashtag.
Other functions of possible use to you:
str_word_count(): Return information about words used in a string.
array_count_values(): Counts all the values of an array.
I am making the dynamic website in PHP. While code is running good using pageid.
The url is now like www.google.com/pageid=1
Now, i want to change the url for 1 level pages as www.google.com/page1
for level 2 as www.google.com/page1/page2
for level 3 as www.google.com/page1/page2/page3
While unique address is stored in the my table as page1,page2,page3.
How can it be possible to change url at run time. Please give the examples and comments. So that it may helpful to understand.
Also i want to know if it is possible using the .htaccess file. If possible How .htaccess %{REQUESTED_FILE}% will reach out for my unique url's that are stored in the database.
$URL= "www.google.com/page1"
1) split the string with '/'
$data = explode("/",$URL);
$data[1] will have page1 value
2) replace the string page with ""
$pageId = str_replace("page","", $data[1]);
3) whatever is left is the page id
pageId has the value now.
Use that to query the database.
Another way is to use regex to extract the number from page1 and use it where-ever you want to use it.
I have a Mysql Forum database which I need to query all the posts in for a specific set of images, on a particular url.
The url's are of images hosted on a subdomain that we don't have access to like this "http://images.website.com/images/randomnumberhere.jpg".
I need a mysql query to pull these out and process them into a list which we can later loop through to grab them all and move them.(I got this part handled)
I'm a php/mysql programmer but this feels like a regex problem and i'm not so great with that yet.
The issue is we don't have a list of the images, and it's a big long random number (so far as I can see). So what I need is a string like "images.website.com/images/(randomnumbers).jpg" and then put them into a list.
You could get all fancy pants-like and use regular expressions,
but you could also try a simple
SELECT * FROM image_table WHERE image_source LIKE '%images.website.com/images/%'
Is this what you are looking for?
If you're looking to pull all of the text from the database, and then use PHP to create a list of the images, try something like this:
$image_list = array();
while($row = $sql->fetch_array())
{
$text = $row['text'];
/* Changed to preg_match_all */
if(preg_match_all("/http:\/\/images.website.com\/images\/[0-9]+\.(jpg|jpeg|png|gif)/i", $text, $matches))
{
$image_list[] = $matches[0];
}
}
Nothing fancy, and I didn't test it, but it should work. That's a hardcoded regex that matches the URL you're looking for specifically. You may want to modify it so that it can match multiple domains from an array, or something, but it should get you started.
EDIT: Should have mentioned that you could then loop through the $image_list array to display the images, or whatever you're going to do with them.
$rand = //rand() function or whatever you would like to create the random number, since you didn't give ranges, it might be an array aswell;
$string = "images.website.com/images/$rand.jpg";
Or even a simple loop:
for ($i = 1; $i < 100; $i++) {
echo $string = "images.website.com/images/$i.jpg";
}
It's up to you how would you use it with your database
I'm putting together an extremely simple ad server with php and mysql on a website. The site currently has 4 or 5 static pages with lots of dynamic content, so URLs look like this:
index.php?pid=1 or content.php?spec=2
What I'd like to do is add a field to my table of ads to keep track of that page(s) the ad is going to be displayed on.
Should I store URLs that have an ad as a list of comma separated values?
Once I retrieve this variable, what's the best way to separate the values into an array?
What's the best way to split a string so I can split the page name $_GET name and variable (as in 'index, pid, 1' or 'content, spec, 2' using the examples above.) ??
Additional Info:
As an example, doctors.php is structured something like this:
doctors.php Listing of Doctor Specialties
doctors.php?spec=# Listing of Doctors that have a particular
specialty
doctors.php?pid=# One specific Doctor's information
I have a few dozen specialties, and a few hundred doctors. I want to be able to place an ad on specific pages/URLs, say doctors.php?pid=7
But I also want to be able to place an ad based on, say, all of the doctors who have a specialty with the ID of 6. That could be 60+ pages, so it doesn't really make sense to have separate table rows. If I needed to change the link on the ad, I don't want to have to change it 60 times or search for it.
Don't store as a CSV.
Add separate database rows for each ad / URL combination.
Then retrieving content will be trivial.
Store URls one per line in simple file. Than you can use php function "file" to read this file as an array.
For url split use http://php.net/parse_url function
Here's what I think will work...
My ad table will have three variables, (a, b, c)
If I have an ad placed on doctors.php?spec=12, I'll store the following:
a = 'doctors';
b = 'spec';
c = '12';
If the ad was meant to display on ALL specialty pages, I'd store:
a = 'doctors';
b = 'spec';
c = NULL;
If something is NULL, it will simply indicate ALL of a set. It seems like an elegant solution, I'll post code if it works.
$url = "index.php?pid=1";
$pos = strpos($url, "?");
if ($pos != false) {
$pieces1 = explode("?", $url);
$pieces2 = explode("=", $pieces1[1]);
$array = array($pieces1[0], $pieces2[0], $pieces2[1]);
}else{
$array = array($url, '', '');
}
print_r($array);
You'll need to improve this code if you want it to work for multiple variables in your url for ex: index.php?v=hello&t=world
Also, i did not test this code. I just wrote it without checking the functions etc.
So I've created a autosuggest for my search engine similar to google using PHP/MYSQL and Ajax. If my MySQL has 2 different title of the same name how do i get only one of them to appear on autosuggest? For example: I have a field with title= ufc 131 and another with title=ufc 131 . When I search for UFC 131 how i get only one of them to show?
The code i use is..
<?php
include('conn.php');
$str = strtolower($_GET['content']);
if(strlen($str))
{
$sel = mysql_query("select * from Streams where title like '".trim($str)."%'");
if(mysql_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysql_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysql_fetch_array($sel))
{
$country = str_ireplace($str,"<b>".$str."</b>",($row['title']));
echo "<tr id=\"word".$row['title']."\" onmouseover=\"highlight(1,'".$row['title']."');\" onmouseout=\"highlight(0,'".$row['title']."');\" onClick=\"display('".$row['title']."');\" >\n<td>".$country."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
Well, you can use the DISTINCT function, you can use the GROUP BY function, or you can even put all of your search results in an array in PHP after fetching it from MySQL and then using the array_unique() function to filter out duplicates.
But none of that is as efficient as making sure that the database doesn't contain any duplicates. What I mean to say is that, since you are providing a suggestion, you want the 'SELECT' element to run as fast as possible. Any type of trickery, like the ones I listed above, will require a combination of more time, more memory, and more CPU. Therefore, what you want to do is make sure that the database is in a good condition so that the SELECT statements can be as smooth as possible. A good way to do this is to make the 'title' field in your 'Streams' table a UNIQUE index. However, what I personally have, is a FULLTEXT index on my 'suggestion field'. The UNIQUE index will make sure there won't be any duplicates in the database for sure, but all that does it let you get away with sloppy PHP code for the insert. If you use proper FULLTEXT search, you can do FULLTEXT searches (MATCH() AGAINST()). Since those searches uses the index, they are performed MUCH faster. Your query statement will with no type of index actually use the index.
On top of that, you probably also want to update your PHP (/ echo) code some bit, cause, though your code is really small, it is not written optimally (which again, is something you WANT to make sure, in the case of search suggestions).
your code needs to be revamped.
A good way for making autosuggestion is to use the minimum amount of data possible.
So in this case you can use JSON.
include('conn.php');
$str = strtolower($_GET['content']);
$str = mysql_real_escape_string($str); // escape to prevent sql injection
Now for your query, You can use the GROUP BY keyword in mysql to not have duplicate lines
$sel = "SELECT title FROM Streams
WHERE title LIKE '{$str}%'
GROUP BY title
LIMIT 10";
Now for the returned data you can return it in Javascript object notation JSON
$data = "{";
while($row = mysql_fetch_array($sel)) {
$data .= '"title":"'.$row['title'].'",';
}
$data .= "}";
now you can echo the content
echo $data;
In your javascript you can use a library like Jquery to make it easy to retrieve the lightweight json data
I hope this helps you make a very good autosuggestion box