I have a project from my college. I need to make a site which will generate random data from database. But it will also need to generate a link. So that people can copy that link (as the website is generating different data, people can see the data they want by copying the URL).
I was thinking to use RAND(). But after joining stackoverlow, I see that RAND() is not a good way.
I can fetch random data using RAND() but it is not making any URL. Which is another problem too. I post this problem before. I think I shouldn't use the RAND() function.
this is the code I'm using at this moment:
<!--PHP code for fetching data from database-->
<?php
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xlsx_db", $con);
$result = mysql_query("SELECT * FROM sheet1 ORDER BY RAND() LIMIT 1");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_array($result);
echo "<b>Quote: </b>";
echo $row['quote']."<br>";
echo $row['by']."<br>";
?>
Anyone could please suggest me how to do that? Any kind of help will be very much appreciated.
Not sure if this is actually what you need, but:
<?php
$rand = true;
if (isset($_GET['id'])) {
if (is_int($_GET['id'])) {
$id = (int) $_GET['id'];
$q = 'SELECT * FROM table WHERE id = ?';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_num_rows($stmt) == 1) {
$rand = false;
// display
}
}
}
if ($rand) {
$q = 'SELECT * FROM table ORDER BY RAND() LIMIT 1';
// run query
$res = mysqli_fetch_array($r);
$url = 'www.example.com/index.php?id=' . $res['id'];
}
?>
The prepared statements aren't strictly necessary, since we already make sure that the $_GET['id'] value is an integer, but for the sake of completeness ;D
If you're selecting the data from multiple tables, you could have another table storing the combinations of data and then generate the url using the combination's ID as id parameter.
If you want to get a permalink, you will need to create another page. It will fetch an ID (or something that is identifying the data record you have chosen randomly) and display the specific data. You link to this at your random page.
Find a random row in your database.
Get the row's id.
Concatenate a URL with the id.
The URL should be pointing to a page that would extract the row with the id provided from the table.
I found this the other day and thought it to be pretty comprehensive:
http://mysql.rjweb.org/doc.php/random
Related
I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.
I'm using the following to inset a number into 'mviews' every time some map is viewed.
Question 1. Where in the following code do i add 'ON DUPLICATE KEY UPDATE mviews = mviews+ 1' so it can increment on duplicate?
Question 2. How do i limit counts to one IP?
Question 3. How can i limit this IP to only increment the 'mviews' only within 24 hours; only the first view will be counted on every 24 hours, the rest of the views within 24 hours after the first view are not suppose to be counted.
<?php
require_once 'db_conx.php';
$result = mysql_query( "UPDATE profiles SET mviews = '1' WHERE pid = '2' ") or die (mysql_error());
/*ON DUPLICATE KEY UPDATE mviews = mviews+ 1 */
if($result){
echo "Views + 1";
}
else {
echo "Views inser error";
}
mysql_close($con);
?>
DUPLICATE KEY UPDATE
is used with INSERT and not with UPDATE statement DOCS
count for one IP will be like this
SELECT COUNT(*) FROM profiles WHERE IP = "127.1.0.0";
[If you are not looking for what I have written above]
if IP address is your primary key then
INSERT INTO
profiles (ip,views)
VALUES ("127.1.0.0",1)
ON DUPLICATE KEY
UPDATE views=views+1;
If you want your Code to work properly[dont use mysql_* also escape user input]
<?php
require_once 'db_conx.php';
$result = mysql_query( "SELECT * FROM profiles WHERE pid =2") or die (mysql_error());
/*ON DUPLICATE KEY UPDATE mviews = mviews+ 1 */
if(mysql_num_rows($result) == 0){
mysql_query( "INSERT INTO profiles (views) value(1) ") or die (mysql_error());
}else {
mysql_query( "UPDATE profiles SET mviews = mviews +1 WHERE pid = '2' ") or die (mysql_error());
}
mysql_close($con);
?>
To both Eustatia & Arun Killu - THANK YOU!!! Because of your posted/edited solution, I was helped out of a mind-bending jam. I have to create an addendum (as my currently-resolved situation may be of help to someone reading this).
My situation was how to establish a click-tracking process for a variable-based hyperlink (i.e.);
<a target="_blank" href="<?php echo $link;?>"><b><?php echo $title;?></b></a>
I kept getting the link to echo out the representative information, open the correct, id-tagged link request (and not baffle user expectation of conventional click-behavior), but the ability to MULTIPLY log link clicks was solved by this post. NOTE TO THE SUPRA-FINICKY - YES! PDO IS THE DEFACTO STANDARD.
I apologize PROFUSELY for spreading the rank taint of deprecation, but if I understand what I'm doing now, I should be able to assimilate rudimentary PDO mastery in a 3 - 6 week period.
<?php
/** Connect to DB */
mysql_connect("localhost","database_user","pwd") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$id = mysql_real_escape_string($_GET['id']);
/** retrieve URL */
$result = mysql_query("SELECT * FROM `articles` WHERE ID = '$id'") or die(mysql_error());
/*ON DUPLICATE KEY UPDATE clicks = clicks+ 1 */
if(mysql_num_rows($result) == 0){
mysql_query("INSERT INTO `articles`(`clicks`) value(1)") or die (mysql_error());
}else {
mysql_query("UPDATE `articles` SET clicks=clicks+1 WHERE `id` = '$id'") or die (mysql_error());
}
$row = mysql_fetch_array($result);
mysql_close();
header("Location: " . $row['link']);
?>
I ended up changing the configuration of the link so the id passed the correct link to the target page;
<?php echo "<a href='pagetracking.php?id=" . $id . $link . "' target='_blank'>
<font color='#0000CC' size='5'><b>" . $row['title']. "</b></font></a>"; ?>
Thank you SO MUCH for posting Eustatia & Arun Killu, I really appreciate the tip. If anyone else here happening across this sees anything that's EXCEPTIONALLY unforgivable (even in this decrepit state, lol) - PLEASE, do - not - hesitate - to scream on it robustly. I need all the help I can get.
As promised for anyone who'd be in need of a WORKING version of this in PDO;
(this is adapted from an answer that I found here on SO, but, can't remember at the second, so I'll look it up for an edit to give the answerer credit.)
track.php
<?php
//Your database information
include '../includes/db.php';
// Fetch id (article_id) from $_GET parameter
$article_id = '';
if (isset($_GET['id'])) $article_id = intval($_GET['id']);
if (!$article_id) {
print "No article ID found!\n";
} else {
//
// Fetch Article ID
//
$sql = "SELECT * FROM `articles` WHERE article_id = :article_id";
$sth = $pdo->prepare($sql);
$sth->bindParam(":article_id", $article_id);
$sth->execute();
}
if (!$sth) {
// No article!
echo 'Invalid Article ID!\n';
} else {
// Article found!
//
// Update Clicks Column
//
$sql = "UPDATE articles SET clicks=clicks+1 WHERE article_id = :article_id";
$sth = $pdo->prepare($sql);
$sth->bindParam(':article_id', $article_id);
$sth->execute();
}
header('Location: view_article.php?id='.intval($_GET['id']));
?>
As this code is working flawlessly, for MY purposes, here's a little caveat for those looking to just blindly cut-and-paste...it updates the clicks column EACH TIME IT'S CLICKED, soooooo if you need to limit it to a certain amount of clicks or some other type of functionality, I wish you well in your endeavors (lol!). I just wanted to publish this as a current, working model of the PDO kind. In fact, I may have to end up using this solution as a basis of another mind-bending jam I'm in right now. In fact, I'm almost willing to bet dollars to donuts I'll be completely right about this move.
HTHSO
P.S. ...PDO is sooooooo annoyingly difficult...but worth it.
I'm new to php, here is my problem:
I want to select a row at random in which the same random value can be referenced later on in the page, i.e embedded in the youtube embed object. I have this working but it changes the value as the random selector is executed again (?)
mysql_connect("====","====","=====")or die(mysql_error());
mysql_select_db("yt")or die(mysql_error());
$result = mysql_query("SELECT * FROM utube ORDER BY RAND() LIMIT 1");
$results = mysql_fetch_assoc($result);
echo $results[id]; /* print youtube id */
echo '<br />'.$results[rating];
Can anyone help me to set up something that lets me reference the row so that I don't have different values for each part of the page where I'm using the random row from my database? Thanks
Save the row into a variable which won't change.
$result = mysql_query("SELECT * FROM utube ORDER BY RAND() LIMIT 1");
$results = mysql_fetch_assoc($result);
$saved_row = $results; //don't change $saved_row later on in the script
echo $saved_row['id']; /* print youtube id */
Pretty new to all this, so if I am going about my puzzle in a crazy way please tell me!
I have a table in a mySQL database with the columns title, hyperlink, imagelink
I want the php to select a row at random, then be able to save the title, hyperlink and imagelink as php variables. (so I can then output them into html)
so I could have for e.g
psuedoey code to get the idea
chosenNumber = randomNumber();
$chosenTitle = title[chosenNumber]
$chosenHyperlink = hyperlink[chosenNumber]
$chosenImagelink = imagelink[chosenNumber]
echo "<a href = $chosenTitle><img src= $chosenImagelink/> $chosenTitle </a>";
I think I need to use an assoc array like this here but I am very confused, because I looked through the various php mySQL fetch_assoc fetch_row etc and can't find which one to do what i need :(
What I have so far is
// database table name information
$number = "number";
$title = "title";
$hyperlink = "hyperlink";
$imagelink = "imagelink";
// sql to select all rows of adverts
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table";
//execute the sql
$data = mysql_query($sql, $link);
//count the number of rows in the table
$bannerCount = mysql_num_rows($data);
//generate a random number between 0 and the number of rows
$randomNumber = mt_rand(0, $bannerCount); //do I need to do bannerCount-1 or similar here?
$chosenNumber = $randomNumber;
//select data from a random row
First time post, be kind please, and thanks for any replies or explanations!
Using ORDER BY RAND() LIMIT 1 is a decent way to get a single row out of a smaller table. The downside to using this method is that RAND() must be calculated for every row in the table, and then a sort must be performed on this non-indexed value to calculate the row you want. As your table grows, ORDER BY RAND() becomes horribly inefficient. The better way to handle this is to first get a count of the number of rows in the table, calculate a random row number to read, and use the LIMIT [offest,] count option on your SQL query:
$sql = "SELECT COUNT(*) as rows FROM $table"
$res = mysql_query($sql);
if (!$row = mysql_fetch_assoc($res)) {
die('Error Checking Rows: '.mysql_error());
}
$rows = $row['rows'];
// now that we know how many rows we have, lets choose a random one:
$rownum = mt_rand(0, $rows-1);
$sql = "SELECT number, title, hyperlink, imagelink FROM $table LIMIT $rownum,1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
// $row['number'] $row['title'] etc should be your "chosen" row
This first query asks the SQL Server how many rows are available, then LIMITs the result set of the actual query to only return 1 row, starting at the random number row we picked.
I think if you use the "limit" clause, it would be quite efficient:
SELECT number, title, hyperlink, imagelink FROM $table order by rand() limit 1
Why do you set up variables for the table name and field names?
If you want to get records randomly, you can simply modify your sql query and each time you will get random ordering of records, just add order by rand() to your query and limit clause if you want to get just one random record:
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table
order by rand() limit 1";
Once you have done that, you need to use functions like mysql_fetch_array or mysql_fetch_object to get the rows actually:
$data = mysql_query($sql, $link);
while ($row = mysql_fetch_array($data))
{
echo $row['title'] . '<br />';
echo $row['hyperlink'] . '<br />';
echo $row['imagelink'] . '<br />';
}
With:
$row = mysql_fetch_array($data)
You have $row array available at your disposal to echo values at any place of your page like:
echo $row['title'];
echo $row['hyperlink'];
echo $row['imagelink'];
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)