Purpose of this query is to retrieve a true image plus 3 random generated images from same table, then show them randomly. User(child) have to select correct image.
Thanks
$sql= "SELECT * FROM `login` WHERE `user` = '$word'";
" UNION"
"SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3";
$row2=mysql_query($sql);
$i=1;
while ($r = mysql_fetch_array($row2))
{
echo '<td> ';
echo '<img src="sigg/'.$r['img'].'" width="130" height="130" /><br>';
echo $r['user'];
echo '</td>';
$i++;
}
Use the UNION clause:
$sql = "(SELECT * FROM `login` WHERE `user` = '$word')";
$sql.= " UNION";
$sql.= " (SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3)";
$sql.= " ORDER BY RAND()";
To get the results you can use for example MySQLi (poseted before OP added his code with mysql_* functions):
$MySQL=new mysqli("localhost", "username", "password", "database");
$query = $MySQL -> query($sql);
while ($entry = $query -> fetch_row())
{
// $entry is an array with the results, use for example:
echo $entry[0]; // will return the first column of your table
echo $entry[1]; // will return the second column of your table
// try also:
var_dump($entry); // outputs everything for testing purposes
}
Please, don't use the mysql_* functions, they are deprecated and will be removed in the future versions of PHP. Use MySQLi or PDO instead. See Why shouldn't I use mysql_* functions in PHP? for more details.
Your request is not clear enough to provide a solid answer, so I'll try to answer it the best I can.
You should use Union in your query to get one big list of entries. However, just doing
SELECT * FROM `login` WHERE `user` = '$word'
UNION
SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3
will give you a list of entries where user = $word in the first part and random 3 other entries.
As I said, I don't know the exact purpose of this, but I think you're better of querying the entire list from your database server.
Here's the php code:
$connection = mysql_connect(HOST, USER, PASSWORD);
mysql_select_db(DATABASE_NAME, $connection);
$sql = "SELECT img, user FROM `login` WHERE `user` = '{$word}' UNION SELECT img, user FROM `login` WHERE `user` != '{$word}' ORDER BY RAND() LIMIT 3";
$results = mysql_query($sql, $connection);
$rows = array();
// Insert results in a new array to shuffle it
while ($row = mysql_fetch_array($results)) {
$rows[] = array(
'img' => $row['img'],
'user' => $row['user']
);
}
shuffle ($rows); // Randomize order
// Construct HTML
$html = '';
foreach ($rows as $entry) {
$html .= '<td><img width="130px" height="130px" src="sigg/' . $entry['img'] . '">
$html .= $user . '</img></td>';
}
echo $html;
You will need to replace capitalized words with what's necessary.
A few explanations:
replace * with only what you need from tables (use fewer memory)
first insert results in an array so you can randomize the order (from MySQL you'll always have the first line the results from first query)
construct the html and output it all at once (executing multiple echo relies on the buffering to not send it to the browser, but that option might be off: What is output buffering).
Related
I have a MySQL database with 6 columns in a table. There will eventually be about 100 rows, for now I have 3.
Column titles: FirstName, SecondName, Sentence1, Sentence2, Sentence3, Sentence4
All tables are set to VARCHAR
I want to use php on a web page to call random data from each row, eg mix and match row1 FirstName with row3 SecondName and row2 Sentence1 etc.
I read it is quicker to randomise using php but I really can't grasp how to do this despite searching.
I can connect to my MySQL database and get results returned using this code:
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['FirstName'] . "<br />";
}
// Close the database connection
mysql_close();
?>
but this just returns one column of data. I need the random code to be returned in the webpage using something like:
echo $firstname . $lastname . $sentence1 . $sentence2 . $sentence3 . $sentence4;
Note, this will be repeated for another 3 or 4 rows afterwards too
echo $firstname_2 . $lastname_2 . $sentence1_2 . $sentence2_2 . $sentence3_2 . $sentence4_2;
I'm not too hot on arrays but if someone can get me started it would be great, thanks.
All those telling you to use rand in the SQL query have not read the question. To those people: the asker wants a random combination of data from the rows, not a random row.
Something like this. It will take all the results from the database and echo a totally random combination. I couldn't avoid using arrays as they are super useful.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error ());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>
Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them
there are several methods to get random data from db in php
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
another method: -
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` ");
$range_row = mysql_fetch_object( $range_result );
$random = mt_rand( $range_row->min_id , $range_row->max_id );
$result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
one more method:-
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
SELECT * FROM `Users` ORDER BY RAND() LIMIT 0,1;
Use ORDER BY RAND() for random records selection.
Split it into two tables,
one for the user
Users:
id | firstname | lastname
Sentences:
id | userId | sentence
Join both at the "id / userId" and do a ORDER BY RAND() probably followed by a LIMIT 20
Trying to implement this but taking an entry from every column (14 at present) instead of a small random number. Would love to have Matthew McGovern's opinion since his code suited me except that it only called a few entries...
Here: Random Sentence Using PHP & MySQL
I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop
I trying to make tag cloud system and i enter the tags in one table with "name" and "product_id".
I make that may have multiple same tags everyone for different product.
My problem is that when echo the tags from the table it show me all tags,this is good,but the repeated tags are in that count. I need to echo repeated tags only once, but i don't know how to make that.
Here is and my code that showed and repeated tags.
$id = $_GET['catid'];
$sql = "SELECT * FROM tags_group";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
//echo $row['name'];
$id = $row['id'];
$sql1 = "SELECT * FROM tags WHERE tag_group='$id'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_array($result1)) {
$name = $row1['tag_name'];
$sql2 = "SELECT * FROM tags WHERE tag_name='$name'";
$resut2 = mysql_query($sql2);
$rows = mysql_num_rows($resut2);
echo $row1['tag_name'] . '(' . $rows . ')' . '<br>';
// echo $row1['tag_name'].$rows.'<br>';
}
echo '<br>';
}
You have to use the DISTINCT keyword do avoid duplicates:
SELECT DISTINCT * FROM tags_group
As I mentioned in the comments above, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
UPDATE
It also looks like you're using nested queries, rather than joining your tables and retrieving the results. Try this instead:
$id = $_GET['catid'];
$sql = "SELECT tags.tag_name, count(*) AS name_count FROM tags
INNER JOIN tags_group
ON tags.tag_group = tags_group.id
GROUP BY tag_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['tag_name'];
$rows = $row['name_count'];
echo $name . '(' . $rows . ')' . '<br>';
// echo $row['tag_name'].$rows.'<br>';
}
echo '<br>';
Here I don't use DISTINCT but GROUP BY allows you to aggregate the count for each distinct row (based on the GROUP BY column).
Take a look at this diagram to better understand how joins work.
So I have a list of CSVs in one table. (EG: 1,3,19 )
I want to search out all of the usernames from the other table where the ids match any of those.
I feel like I should be able to do something like:
<?
$query = "SELECT player_ids FROM cast_list WHERE game='".$gameid."' ";
$result = mysql_query($query) or die(mysql_error());
$playerquery = "SELECT username,id FROM players WHERE id IN (".$result.") ORDER BY username;
$player_result = mysql_query($playerquery) or die(mysql_error());
echo "<ul>";
while ($row = mysql_fetch_array($player_result) ) {
echo "<li>".$row['username']."</li>";
}
echo "</ul>";
?>
but I can't get it to work. What am I doing wrong?
You can also use a subquery (which will be faster):
$playerquery = "SELECT username,id
FROM players
WHERE id IN (SELECT player_ids FROM cast_list WHERE game='".$gameid."')
ORDER BY username";
Btw if game is an integer field you don't have put quotes (' ') around the value.
The idea is correct, but you need to transfer the $result to an actual string array:
$game_ids = array();
while ($row = mysql_fetch_array($result) ) {
$game_ids[] = .$row[1];
}
Now using implode to convert the array to a comma separated values with a comma:
$playerquery = "SELECT username,id FROM players WHERE id IN (" . implode(",",$result) . ") ORDER BY username;
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 :)