Random URL redirect using PHP and MySQL - php

I have a question about adding a link to my website that when 'clicked' will send the user to a random URL stored in my MySQL database.
My database is titled "movie" and I would like to be able to have the user click on a link and it would send them to one of the movie page URLs stored in my database.
EX: The user clicks the "Random" link and gets taken to a movie page from my database(I have about 110 URLs listed with a unique Id).
Would I use something like:
header('Location: 'xxxxx);
To accomplish this?
I know I should be able to accomplish this task using PHP, I am just having trouble figuring this one out. Any help would be great! Thanks.

I'm assuming the query you posted selects one random movie, and that the field where the url is stored is called 'url'.
$result = mysql_query("SELECT url FROM movie ORDER BY RAND() LIMIT 0, 10")
or die(mysql_error());
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
header('Location: '.$row['url']);
This should redirect to the url in the database.

try this:
mt_rand("", ""); // this creates random numbers and use it in a variable as:
$id= mt_rand("1", "110");
// hatever id number is generated it will put out that one in the query but it is only for one if you want multiple put $id in a for loop than print the result in while loop.
$result = mysql_query("SELECT url FROM movie WHERE id= '$id' LIMIT 0, 10")
or die(mysql_error());
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
header('Location: '.$row['url']);

Related

Creating fusioncharts from database with variable where-condition

I'm creating FusionCharts with data from my database. It works if I set a static where-condition with a variable set in the code ($kommunenr = '3001';). But I would like the user of the website to choose which data the chart is based on, by inserting a number in a form field, i.e. 3018. So the value of the variable should come from the user's choice. But when I test the variable seems empty.
My code is based on these tutorials:
https://www.fusioncharts.com/dev/using-with-server-side-languages/tutorials/php-mysql-charts
https://www.youtube.com/watch?v=nqavhILvBVU
https://a1websitepro.com/jquery-ajax-form-submit-with-php-processing/2/
I have the following files:
valginfo.php (the main page)
skjema.js (get the data (the number) from the form on the main page)
chart_sample.php (lists the data from the database)
app.js (creates the chart)
I have tried to find the error by both posting the content from chart_sample.php in a div on the mainpage, and in an iframe. And of course googling.
My query in my chart-data.php (choosing the data to use in making the chart):
$query = "SELECT * FROM valg19_kommune WHERE kommunenr = $kommunenr AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500";
It works if the variable is static, set like this:
$kommunenr = '3001';
But when I set the variable like this, it looks empty:
$nr=$_POST['nr1'];
$kommunenr=$nr;
I expect the posted number to be stored as the value of the variable and beeing part of the query, but it is not. When I echo the query and the result from chart_sample.php into a div on the main page, I looks perfect:
SELECT * FROM valg19_kommune WHERE kommunenr = 3018 AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500
[{"label":"Fremskrittspartiet","value":"42","color":"#000099","tooltext":"Elisabeth Stene"},{"label":"H\u00f8yre","value":"64","color":"#3366ff","tooltext":"Benedicte Dyvik"},{"label":"Kristelig Folkeparti","value":"56","color":"#ffff00","tooltext":"Brynjar H\u00f8idebraaten"},{"label":"Senterpartiet","value":"45","color":"#00cc00","tooltext":"Reidar Kaabbel"},{"label":"Arbeiderpartiet","value":"44","color":"#ff3300","tooltext":"Kai Guttulsr\u00f8d"},{"label":"SV - Sosialistisk Venstreparti","value":"39","color":"#ff4d4d","tooltext":"Tore Andersen"},{"label":"R\u00f8dt","value":"37","color":"#cc0000","tooltext":"Martin Werner Olsen"}]
But in my iFrame this is displayed:
SELECT * FROM valg19_kommune WHERE kommunenr = AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500[]
The iframe content is not updated when I submit the number.
How can I make sure the chart is made based on the number entered by the user?
Before I enter a number in the form field
After I entered the number
If I set the variable as this $kommunenr = '3001'; and remove the echo og the query.
Now I feel really stupid! I should use sessions and globals!
Start each page with session_start(); and first set and then use the global variables:
$_SESSION["kommunenr"] = $kommunenr;
$kommunenr = $_SESSION["kommunenr"];

Individual Username from a Database

I have a database running and I'm currently printing out in a website, in a "php block" the usernames of the database. I achieved it with this
if ($db_handle) {
print "Database ISSSSS Found ";
$SQL = "SELECT * FROM `database.com`.`users`";
$result = mysql_query($SQL);
//print $result;
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['username'] . "<BR>";
}
mysql_close($db_handle);
}
However this gives me a giant string of all the users (I currently have 4). How do I make it so its just the individual user accessing their profile through the website
Typically, when someone logs in, you would store non sensitive information about the user in the session. This way, you can get to it quickly without needing to make database calls on every page. For instance, if you wanted to show their username in the pages header, you would always have their username handy to do so. Then, when they go to view their profile, you can use that username you stored as part of your SQL WHERE clause to pull in information pertaining only to that specific user.
Use WHERE username = 'yourusername' in your SQL query.
That shall fix your problem

PHP how to build the page based on URL

I've got rendered page with lots of items and i want to have item-specific page accessed by clicking the link
while($row = mysqli_fetch_array($result))
{
echo "<h3>".$row['Brand']." ".$row['Model']."</h3>";
//more details
}
So by clicking $row['Brand']-$row['Model'] I'd like to be redirected to the page with this item. Can i do that somehow? As the only way i know - is to insert new .php file and pass some unique item's id from SQL via URL or post request by that is not SEO-friendly way, so I'd like to avoid that.
You'll need to use the rewrite in apache(assuming that's your webserver) This is a nice tutorial. Or look into using a framework that handles that for you. Something simple like CodeIgniter or Laravel.
You have to do it from the mysql_query function using where clause pointing to the column you to be filter the results.
echo "<h3>".$row['Brand']." ".$row['Model']."</h3>";
$brand = (isset($_GET['brand'))?mysql_real_escape_string($_GET['brand']):'';
$model = (isset($_GET['model'))?mysql_real_escape_string($_GET['model']):'';
$query = "SELECT * FROM cars WHERE brand='$brand' AND model='$model'";
$result = mysql_query($query);

Printing an HTML page with unique number

I am having a php page in which i have captured different values from the previous page, There is also a print button, Which prints all these fields including the unique number. When user clicks on the print button record will be inserted in database and print window displays on the screen. But the problem is there is a unique number on html page, For example if two persons are login at the same time, The will get same unique number, and both will be able to print the same page having same unique number.
How i can control this issue, I also tried to redirect the user to the previous page but its not working.
Here is my php page, Which i am calling using ajax
<?php
$conn = mysql_connect('localhost','','') or die ("");
mysql_select_db("") or die ("Database Problem");
$query = "select * from print where a = $a;
$result = mysql_query($query);
if(mysql_num_rows($result) == 0)
{
$query = "INSERT INTO print () VALUES ()
$result = mysql_query($query) or die();
if(mysql_affected_rows()<>1)
{
header ("Location:mainpage.php?uniquenumber=xy");
}
}
you can use unisid http://php.net/manual/en/function.uniqid.php
To generate an unique id
What is this uniquenumber needed for in the client side? I mean having it accessible and editable for the users is kinda dangerous if it's an important value.
If you just need this number to tell apart the different entries in the print table, why not just use and auto_increment index for this table?
Another solution would be session variables. When a user succesfully logs in generate this unique ID based on multiple variables (username, time, browser), that will ensure there won't be repeated values for this ID. Then store the variable like this:
session_start();
$_SESSION['ID']=$unique_ID;
You can then read it in any other PHP script like this:
session_start();
$unique_ID=$_SESSION['ID'];
You can validate the unique number before inserting to database ( Before Printing also ). If the unique no is exist, throw a error message "unique no is already used " and give another unique number ( By loading the HTML Page again or doing something else ).

PHP Link Click counter

I want to write simple counter for links/tags. So I have tags and random displayed them to the website
$zmienna = "SELECT name, link FROM tag_content ORDER BY RAND() LIMIT 4";
$result2 = mysql_query($zmienna);
echo $result2;
while($row=mysql_fetch_array($result2)){
echo "<a href='http://www.simplelink.xx/tag/".$row['link']."'>".$row['name']."</a><br>";
}
And now I want to count how many users clicked tags. I created another row named "wys" and tried to write SQL stuff
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE id=2";
$result3=mysql_query($wtf);
As u can see it only works for tag id = 2. And now the problem: how to make it work for all tags?
For example: I have 4 tags with different id. How to make counter "read" the actual clicked tag and make it add "1" to the "wys"?
Thx for help and let me know if u need more information (like code etc.)
As the link field is unique, you can simply use it as an identifier instead of id.
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE link='".$something."";
where $something is a last part of page URL (you should parse it). Of course you also need to check this variable before you use it, because you got it from client side and it could have code for SQL-injection.
You need a way to get the id of all links. Either provide it as a query parameter for the link, or use parse out the name and url from the clicked link and make a relevant SELECT to get the id to loop over.
Use jquery :eq() selector to find out the exact link and then make an ajax request for updating the count

Categories