PHP SQL - Random Select 1 Row, Where ID = x - php

I have a MySQL database and I need a PHP to pull a random row. I have successfully created
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
This successfully randomly pulls a row; however, it is not limited to where region=2.
I need to be able to:
pull randomly when region=UK
pull randomly when region=UK or ##
(where ## is actually another region, for example, YK = Yorkshire)
Basically I need it to select rows randomly but ONLY when region=UK.
region is a label for one of my fields/collumns, and UK is the content of the VARCHAR in that for a number of rows.
I have the rest of the code sorted.
I have a simple database and the php as follows:
<?php
//Sample Database Connection Syntax for PHP and MySQL.
//Connect To Database
$hostname="carbonmarketing.db.9606426.hostedresource.com";
$username="MarketReadOnly";
$password="Read0nly1";
$dbname="carbonmarketing";
$usertable="ClientList";
$advertfooter = "advertfooter";
mysql_connect($hostname,$username, $password) or die ("<html>%MINIFYHTML4333ddb1f6ba50276851b9f9854a5c817%</html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
$advertfooter = $row["$advertfooter"];
echo "$advertfooter";
}
}
?>
But, it's just pulling randomly for all values of the region column
Let me know if it would help for you to see the database.

Make and array with your regions and implode them:
$region = array('UK', 'YK');
$implode = implode("', '", $region);
$query = "SELECT * FROM `".$usertable."` WHERE `region` IN ('".$implode."') ORDER BY RAND() LIMIT 1";

$query = "SELECT * FROM $usertable
WHERE region IN ('UK','YK')
ORDER BY RAND() LIMIT 1";

Related

Do I need a left, natural or simple join in SQL?

I am new to PHP coding and just trying to fix some functionality on my site that was left over from the lead developer.
The site, [Vloggi], is a marketplace. So I need to show the name of the job poster in the assignments page . The table I have the jobs in only has the ID, not the name.
So I need a join, but I've tried and it breaks the entire site.
The SQL has 17 tables, I need to display the User Name (usr_name) contained in table 3, the organisation contained in table 7 (usrg_orgname) with the job posting user (vlop_usr_id) details in table 14.
The primary key is users.usr_id, which is linked to users_gor.usrg_usr_id and vlog-ops.vlog_usr_id.
Table 3: users
usr_id, usr_email, usr_password, usr_fbuser, usr_fbtoken, usr_name, usr_loc_name, usr_loc_lat1, usr_loc_lon1, usr_loc_lat2, usr_loc_lon2, usr_status, usr_gor, usr_vgr, usr_token, usr_regtoken,
table 7: users_gor
usrg_usr_id, usrg_creditops, usrg_creditvlog, usrg_creditvlogette, usrg_destination, usrg_orgname, usrg_orgtype, usrg_location, usrg_website, usrg_jobtitle, usrg_phone, usrg_address1, usrg_address2, usrg_state, usrg_postcode, usrg_country
Table 14: vlog-ops
vlop_id, vlop_title, vlop_description, vlop_tags, vlop_deadline, vlop_quantity, vlop_quantityposted, vlop_vser_id, vlop_usr_id,vlop_loc_name, vlop_loc_lat1, vlop_loc_lon1, vlop_loc_lat2, vlop_loc_lon2, vlop_campaign, vlop_rules, vlop_tips, vlop_status
So in main.php i have written the following Sql lookup
in main.php, I have the following SQL lookups:
$sql = "SELECT * FROM users_gor WHERE usrg_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_gor = $rows[0];
$sql = "SELECT * FROM users_vgr WHERE usrv_usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users_vgr = $rows[0];
$sql = "SELECT * FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT * FROM vlog-ops WHERE vlop_usr_id ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
$sql = "SELECT usr_name AS vlop_usr_name FROM users WHERE usr_id = ".$db->quote($user_info['usr_id'])." LIMIT 1";
$rows = $db->select($sql);
$users = $rows[0];
And then in the page template itself, I have written
<?php echo $vlop['vlop_vser_id'] ?>
<?php echo $vlop['vlop_usr_name'] ?>
The first one works, the second doesn’t. What I want eventually is to display the user name and the organisation name in a table.
Whenever I try a JOIN or a NATURAL JOIN or a LEFT JOIN it breaks and the entire site goes blank.
Any help for a newbie would be appreciated with a million thanks.
When you use JOIN you need to specify how you're joining them.
In the query below I'm assuming you're looking for the fields in bold from your question.
$query='SELECT u.usr_name, g.usrg_orgname, v.vlop_usr_id FROM users u
JOIN vlog-ops v on u.usr_id = v.vlop_usr_id
JOIN users_gor g on u.usr_id = g.usrg_usr_id';
I believe I got the name of the fields right but if not just replace them with the correct ones.
Once you have the data fetched, you just loop through the results:
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
echo 'User name = ' . $row['u.usr_name'];
echo 'Org name = ' . $row['g.usrg_orgname'];
echo 'Job posting user id = ' . $row['v.vlop_usr_id'];
}

MySQL move random row from one table to another

Is it possible to move a random row(with one column) to another table in that way so no one get this data even if will request it simultaneously?
For example: If you open my page, you get a data from MySQL that no one will get even if open this page simultaneously with you.
Now I do it this way:
mysql_query("INSERT INTO `ShowRow` SELECT * FROM `AllRows` WHERE 1 LIMIT 1");
mysql_query("DELETE FROM `AllRows` LIMIT 1");
Is it possible to do some another better way? Or how to SELECTsome specific row if there is only one column?
You can use the function RAND() to order rows randomly and take the first.
SELECT * FROM AllRows ORDER BY RAND() LIMIT 1, 1
Thank you to all, but I have come up to do it this way:
$accCount = mysqli_query($connect, "SELECT * FROM AllRows");
$accCount = mysqli_num_rows($accCount);
$RandAcc = rand(0, $accCount);
$result = mysqli_query($connect, "SELECT * FROM `AllRows`");
$ReplaceRandAcc = mysqli_result($result, $RandAcc);
mysqli_query($connect, "INSERT INTO `ShowRow` SELECT * FROM `AllRows` WHERE login='".$ReplaceRandAcc."'");
mysqli_query($connect, "DELETE FROM `AllRows` WHERE login='".$ReplaceRandAcc."'");
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}

PHP - MySql Join -

I was trying to get some details from MySql database, but i was working so long and tried so many ways that i am completely lost now :s
What i need to GET is two details which depend on information from 3 tables. I need to get $title and $siteurl (from table_sites) where current user did not click it before, AND siteurl owner still have remaining credits...
Here is my database:
USER:
id
username
password
credits
active
clicks
SITES:
id
userid
title
siteurl
clicks
active
weight
CLICKS:
id
siteid
byuserid
i tried with this MySql query:
include('db_con.php');
mysql_connect("$dbhost", "$dbusername", "$dbpassword")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$qrym = mysql_query("SELECT * FROM `users` WHERE username='$username' LIMIT 1") or die (mysql_error());
while($mem = mysql_fetch_object($qrym)){
$uid = $row->id;
}
$qrys = mysql_query("SELECT * FROM sites, clicks WHERE clicks.byuserid != '$uid' and sites.userid != '$uid' and sites.active = '1' ORDER BY sites.weight DESC, sites.id DESC LIMIT 1") or die (mysql_error());
if(mysql_num_rows($qrys)!=0){
while($row = mysql_fetch_object($qrys)){
$title = $row->title;
$siteurl = $row->siteurl;
echo "$title $siteurl";
}
} else {
echo "No more sites";
}
No errors, but whatever i try result is No more sites! How to JOIN this query correctly?
Maybe do
while($row = mysql_fetch_object($qrym)){
$uid = $row->id;
instead of
while($mem = mysql_fetch_object($qrym)){
$uid = $row->id;
You probably want a query like this:
SELECT [the columns you need]
FROM sites
LEFT JOIN clicks ON clicks.siteid = sites.id
AND clicks.byuserid = [current user id]
WHERE sites.active = 1 AND clicks.id IS NULL
ORDER BY sites.weight DESC, sites.id DESC
LIMIT 1
As gpojd noted above, you must must MUST sanitize your inputs before using them in a query. Fix your first query's code:
$qrym = mysql_query("SELECT * FROM `users`
WHERE username='" . mysql_real_escape_string($username) . "' LIMIT 1");
When fetching only a single row, as your first query does, there is absolutely NO need for a while() loop to retrieve the data.
That, and observe the comments in the code block:
$qrym = mysql_query("SELECT * FROM `users` WHERE username='$username' LIMIT 1") or die (mysql_error());
while($mem = mysql_fetch_object($qrym)){
^^^--- you fetch into $mem
$uid = $row->id;
^^^--- but try to retrieve from $row?
}
Try this instead:
$sql = "SELECT ...";
$qrym = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($qrym);
$uid = $row['uid'];

Php/MySQL help - random daily pick?

I'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");

Simple way to read single record from MySQL

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 :)

Categories