Combine two word from a MySQL database at random - php

I have a database with nouns and adjectives for example:
id | type | word
-----------------------
1 | noun | apple
2 | noun | ball
3 | adj | clammy
4 | noun | keyboard
5 | adj | bloody
ect...
I want to create one query what will grab 10 random adjectives and 10 random nouns and put them together.
Having trouble doing it, is this possible?
Thank you!

You can get 10 random elements per type with queries like this:
select word from YOUR_TABLE where type = 'noun' order by rand() limit 10;
select word from YOUR_TABLE where type = 'adj' order by rand() limit 10;
and then put them together in your PHP code, like so:
$phrases = array();
$adj_result = mysql_query("SELECT word FROM words WHERE type = 'adj' ORDER BY RAND() LIMIT 10");
$noun_result = mysql_query("SELECT word FROM words WHERE type = 'noun' ORDER BY RAND() LIMIT 10");
while($adj_row = mysql_fetch_assoc($adj_result)) {
$noun_row = mysql_fetch_assoc($noun_result);
$phrases[$adj_row['word']] = $noun_row['word'];
}
print_r($phrases);
Please note that this code is not very safe (it makes the assumption that the second query always yields as least as many results as the first), but you get the idea.
Edit: Here's a single SQL query that should do it:
select t1.word, t2.word
from
((select word from YOURTABLE where type = 'adj' order by rand()) as t1),
((select word from YOURTABLE where type = 'noun' order by rand()) as t2)
order by rand()
limit 10;
EDIT: removed example

Related

How To select last inserted Row in PHP , Mysql

I m trying to create ID like "A1 , A2, A3 .. etc
So i tried like this
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
if($count2>0)
{
$merge_id5 = explode("A",$merge_id5);
$mergeid_no = $merge_id5[1]+1;
$merge_id6 = $mergeid_no;
}
else
{
$merge_id6 ="1";
}
if($count<1)
{
$merge_id = $merge_id5;
}
Everything is working fine... but after creating A9, it create A10 then again it creates A10 not moving to A11 , A12 . etc., i think if i write correct query to fetch last inserted row i'll fix this issue
Please someone help me
db table :
merge_id | name |
A1 | xxxx |
A2 | yyyy |
A3 | zzzz |
....
....
A9 | sds |
A10 | dsfs |
i know it is not the best solution to your problem, but this will help you.
and just get the first record because if i add LIMIT 1 the output is wrong :(
SELECT * FROM merge_info ORDER BY LENGTH(merge_id) DESC
Change your query to:-
SELECT MAX(merge_id) FROM merge_info;
I think it's better you use an auto_increment field, to get the last insert row with LAST_INSERT_ID(), otherwise you can't be sure if the last row, the one you have inserted.
So long. To order with your solution, use this.
ORDER BY SUBSTRING(merge_id,2) DESC
Better approach to your problem could be ,
use AUTO_INCREMENT field and while displaying append 'A' to it.
Now to solve this you can use below SQL statement
SELECT * FROM `merge_info` ORDER BY SUBSTRING(merge_id,2) DESC limit 1
should change you merge_id column into auto increment column,and the change your query into below mentioned,
SELECT MAX(merge_id) FROM merge_info;
if you want id like A1,A2,A3 ... then you can use the below code for get it
$q = mysql_query("SELECT merge_id FROM merge_info ORDER BY merge_id DESC LIMIT 1;");
$s = mysql_fetch_array($q);
$merge_id5 = $s['merge_id'];
$count2=mysql_num_rows($q);
$merge_id="A".$merge_id5;
after above process,noe we have a meger_id like A1,A2.. on application side

How to get the next row in sql

I have a table that is something like this
id | names | value
1 Vicky 43
2 Erica 23
3 Rueben 33
4 Bob 54
5 Chris 60
Then I set them in order according to their value. Now the table looks like this.
id | names | value
5 Chris 60
4 Bob 54
1 Vicky 43
3 Rueben 33
2 Erica 23
Now the starting point is id 5 which has a name of Chris and a value of 60. My goal is, to get the next row which has an id of 4 and name of Bob and a value of 54.
You just need to limit the resultset:
SELECT * from table
ORDER BY value DESC
LIMIT 1, 1
Output:
| ID | NAMES | VALUE |
|----|-------|-------|
| 4 | Bob | 54 |
Fiddle here.
The LIMIT basically works this way: the first number sets the starting point (being 0 the minimal value) and the second number the amount of items to fetch (in this case only one).
Edit:
A different way of understanding the question would be: Given a value for a particular field (EG: id field with value of 5)... what would be the previous record? As we have the id 4 in the data we should return that one.
That could be accomplished this way:
SELECT * from t
WHERE id < 5
ORDER BY id DESC
LIMIT 1
Fiddle here.
This way you can traverse the results in both orders (ASC and DESC) and also get both the next or previous (> or <) rows.
If your current ID is for example 4 then
Next:
select * from foo where id = (select min(id) from foo where id > 4)
previous:
select * from foo where id = (select max(id) from foo where id < 4)
sql server:
with temp as
(
SELECT ROW_NUMBER() OVER (ORDER BY value desc) AS ROWID, * FROM table_name
)
SELECT * from temp where ROWID=2
mysql:
SELECT * from table
ORDER BY value DESC
LIMIT 1, 1
I get the feeling that this is a PHP related question?
If that's so, then you can use PHP's mysql or mysqli_fetch functions to get what you want... along with a loop
This is your basic loop-through-a-mysql-query
$sql = mysql_query( "SELECT * from table ORDER BY value DESC" );
while ( $r = mysql_fetch_array( $sql ) ) {
echo $r['value'] . "<br />\n";
}
If you want to have them all at your disposal and be able to call either one of them at will, you will need to store the data in an accessible array, like so
$sql = mysql_query( "SELECT * from table ORDER BY value DESC" );
$theData = array();
while ( $r = mysql_fetch_array( $sql ) ) {
$theData[] = $r['value'];
}
Then, to access the SECOND value, use this
echo $theData[1];

Query to list which string how many occured in a table?

I have an array of strings and a table with text type column. I want to list which string how many occured in specified column of any row in table. Is there a way to do this with one query?
Example;
$strings = array('test', 'sth');
Table;
id | someTextColumn
-------------------
1 | abc tests
2 | sthab
3 | teststh
4 | abcd
5 | sth
Expected result;
str | occurences
-----------------
test | 2
sth | 3
You can do this with a series of like statements.
Here is an example:
select totest.str, count(t.id)
from (select 'test' as str union all
select 'sth'
) totest left outer join
t
on t.someTextColumn like concat('%', totest.str, '%')
group by totest.str
This is not going to be particularly fast if your tables are large. If you have largish tables, you might want to consider full-text indexing.
If the table size isn't too large and the column is properly indexed:
SELECT 'test', COUNT(id)
FROM tableName
WHERE someTextColumn LIKE '%test%'
UNION ALL
SELECT 'sth', COUNT(id)
FROM tableName
WHERE someTextColumn LIKE '%sth%'
$query = "select someTextColumn, count(id) from tableName where "
for($i=0; $i < count($Strings); $i++)
{
if($i != 0)
$query .= " OR ";
$query .= "someTextColumn =" . $string[$i];
}
$query .= " group by someTextColumn";
$result = mysql_query($query);
Try this I hope this will solve ur problem!!

display records after spicific id

Here the SQL query and I need some adjustment to it
SELECT DISTINCT ic.img_path, ic.id
FROM images_community ic
WHERE ic.delete_flag = 0 AND ic.status = 1
ORDER BY ( SELECT (count(id = ic.id ) + ic.views)
FROM image_comments WHERE img_id = ic.id) DESC
I need to show record after specific ID
not limit and offset for sure I need display rows after this id =5
this images retrieve
> images id | img_path
> 1 | dafad.sjdbh
> 2 | dafad.sjdbh
> 5 | dafad.sjdbh
> 3 | dafad.sjdbh
IS there a way to display records after id = 5 in the same query retrieved
You can use limit and offset to achieve it, please see Limit, Offset
If you want all rows after offset just do
SELECT DISTINCT ic.img_path, ic.id
FROM images_community ic
WHERE ic.delete_flag = 0 AND ic.status = 1
ORDER BY ( SELECT (count(id = ic.id ) + ic.views)
FROM image_comments WHERE img_id = ic.id) DESC LIMIT (SELECT cout(*) FROM table_name) OFFSET my_row_offset
Found the row position for this ID and start the Limit from it.

Complicated MySQL Query?

I'm working on a 'social sharing' kind of thing for music, and I just ran in to a problem. My friends table is structured like this:
| id | f1 | f2 | status |
----------------------------------------------
| 000001 | username1 |username2| 0 |
| 000002 | username4 |username7| 1 |
My rates table is structured like this:
| id | username | songname | songid | plus | minus |
----------------------------------------------------
|0001| username1| Songname | 000001 | 0001 | 00000 |
|0002| username3| Song2222 | 000002 | 0000 | 00001 |
And so what i'm trying to do, is to get a random list of 3 friends where the status is 1, and then query the rates table for each random friend's most recent rate where plus = 1. 'Recency' (if you will) is based on the ID which is auto incremental.
That part isn't the really tough bit, lol. The tough bit, is that the user could be in EITHER f1 OR f2, so the query needs to contain an OR, and if the user is in f1, it'll need to get the corresponding f2, and vice versa.
Then check if they are friends and status=1, then query rates for the most recent rates by the 3 random friends. Then download those data bits, then write 3 strings similar to the example below
username 3 +1'd Song2222
If anyone would know how to write a script/query like this in PHP/MySQL, I'd be really grateful! Haha
Thanks! :)
Edit 3*
While waiting for responses, I worked out this code, which partially works!
<? session_start();
$user = $_SESSION['username'];
mysql_connect("localhost", "xxxxx", "xxxx") or die(mysql_error());
mysql_select_db("xxxxxx") or die(mysql_error());
$q1data = mysql_query("SELECT * FROM friends WHERE (f1='$user') OR (f2='$user') AND status=1 ORDER BY RAND() LIMIT 1") ;
if(mysql_num_rows($q1data)===1)
{
$q1result = mysql_fetch_assoc($q1data);
$q1f1 = $q1result['f1'];
$q1f2 = $q1result['f2'];
if($q1f1==$user) {
$oq2un1 = $q1f2;
}
if($q1f2==$user) {
$oq2un1 = $q1f1;
}
}
$q2data = mysql_query("SELECT * FROM friends WHERE (f1='$user') OR (f2='$user') AND status=1 ORDER BY RAND() LIMIT 1") ;
if(mysql_num_rows($q2data)===1)
{
$q2result = mysql_fetch_assoc($q2data);
$q2f1 = $q2result['f1'];
$q2f2 = $q2result['f2'];
if($q2f1==$user) {
$oq2un2 = $q2f2;
}
if($q2f2==$user) {
$oq2un2 = $q2f1;
}
}
$q3data = mysql_query("SELECT * FROM friends WHERE (f1='$user') OR (f2='$user') AND status=1 ORDER BY RAND() LIMIT 1") ;
if(mysql_num_rows($q3data)===1)
{
$q3result = mysql_fetch_assoc($q3data);
$q3f1 = $q3result['f1'];
$q3f2 = $q3result['f2'];
if($q3f1==$user) {
$oq2un3 = $q3f2;
}
if($q3f2==$user) {
$oq2un3 = $q3f1;
}
}
/************************************* SECOND SET OF QUERIES ******************************************/
$q4data = mysql_query("SELECT * FROM rates WHERE username='$oq2un1' AND plus=1 ORDER BY id LIMIT 1");
if(mysql_num_rows($q4data)===1)
{
$q4result = mysql_fetch_assoc($q4data);
$finalusername1 = $q4result['username'];
$q4songid = $q4result['song_id'];
$q4songname = $q4result['songname'];
}
$q5data = mysql_query("SELECT * FROM rates WHERE username='$oq2un2' AND plus=1 ORDER BY id LIMIT 1");
if(mysql_num_rows($q5data)===1)
{
$q5result = mysql_fetch_assoc($q5data);
$finalusername2 = $q5result['username'];
$q5songid = $q5result['song_id'];
$q5songname = $q5result['songname'];
}
$q6data = mysql_query("SELECT * FROM rates WHERE username='$oq2un3' AND plus=1 ORDER BY id LIMIT 1");
if(mysql_num_rows($q6data)===1)
{
$q3result = mysql_fetch_assoc($q6data);
$finalusername3= $q6result['username'];
$q6songid = $q6result['song_id'];
$q6songname = $q6result['songname'];
}
$socialmuze_string1 = $finalusername1." recently <font color='#00FF00'>+1'd</font> <a href='song?id=".$q4songid."'>".$q4songname."</a><br>";
$socialmuze_string2 = $finalusername2." recently <font color='#00FF00'>+1'd</font> <a href='song?id=".$q5songid."'>".$q5songname."</a><br>";
$socialmuze_string3 = $finalusername3." recently <font color='#00FF00'>+1'd</font> <a href='song?id=".$q6songid."'>".$q6songname."</a><br>";
echo $finalusername1." ".$q4songname."<br>";
echo $finalusername2." ".$q5songname."<br>";
echo $finalusername3." ".$q6songname."<br>";
?>
I think it might help modifying the friends query such that it only returns the friends. Picking up portions from your code example, this is how I'd suggest doing it:
session_start();
$user = $_SESSION['username'];
// retrieve random 3 friends
$rsFriends = mysql_query('SELECT `id`,
(CASE
WHEN `f1` = \'' . mysql_real_escape_string($user) . '\' THEN `f2`
WHEN `f2` = \'' . mysql_real_escape_string($user) . '\' THEN `f1`
END) AS `friend`
FROM `friends`
WHERE `status` = 1
AND (`f1` = \'' . mysql_real_escape_string($user) . '\'
OR `f2` = \'' . mysql_real_escape_string($user) . '\')
ORDER BY RAND()
LIMIT 3');
while ($row = mysql_fetch_assoc($rsFriends)) {
// retrieve the most recent rate entry where plus = 1
$rsRates = mysql_query('SELECT `id`, `username`, `songname`, `songid`, `plus`, `minus`
FROM `rates`
WHERE `username` = \'' . mysql_real_escape_string($row['friend']) . '\'
AND `plus` = 1
ORDER BY `id` DESC
LIMIT 1');
while ($row1 = mysql_fetch_assoc($rsRates)) {
// $row1 is the array that contains the most recent rate where plus = 1
}
}
The benefit with modifying the friends query is that it will always give you the name of the friend in a single column. There are other ways to write the friends query, like using UNION may be, but I think this one is simple and should work as nicely.
I haven't tested the code above, so please feel free to fix it if in case I've used wrong table or column names. Also, though the above code sample is keeping in lines with your example, you might as well do the above in a single query using JOINs.
Hope this helps!
Let's work on the SQL part first.
In your comment, you said you are using
SELECT * FROM friends WHERE (f1='$user') OR (f2='$user') LIMIT 3
You also said you wanted to get a random sample. MySQL has the construct ORDER BY RAND() so that your first 3 will be randomized.
Let's figure this out from the inside out.
If you issued this Select statement:
SELECT * FROM friends where status=1 and (f1='$user' OR f2='$user') order by RAND() limit 3
Then I think you would get 3 random rows from the friends table where the status=1.
(This would be much easier if friends were normalized and f1 and f2 were a single column with an additional column indicating how f1 and f2 were different. As it stands, there is a computationally expensive way to get these two columns into one, assuming they are the same type, say varchar(13).)
SELECT f1 FROM friends where status=1 and f1='$user' order by RAND() limit 3
union all
SELECT f2 FROM friends where status=1 and f2='$user' order by RAND() limit 3
That will get you 6 usernames that are called $user.
Working your way out, you will need a query to surround the first, making a subselect statement. To do the next step, you might consider:
SELECT * from rates where username in (
SELECT f1 FROM friends where status=1 and f1='$user' order by RAND() limit 3
union all
SELECT f2 FROM friends where status=1 and f2='$user' order by RAND() limit 3
)
Again, this would not be quite so complex if you were to normalize the friends table.

Categories