How to reverse an array in PHP that is fetched from MYSQL - php

I am trying to pull out a row of data from MySQL and put it in an array and then reverse it before displaying the results and then if confirmed by the user it will post the reversed results back into mysql
I am using this code :
for($i=0;$i<6;$i++) {
// Make a MySQL Connection
$query = "SELECT * FROM databasedemo WHERE id='$i'";
$result = mysql_query($query)or die(mysql_error());
$row = mysql_fetch_array($result);
array_reverse($row,true);
echo $i."--"."A".$row['A']. " - ". "B".$row['B']. " - ". "C".$row['C']. " - ". "D".$row['D']. " - ". "E".$row['E'];
echo "<br>";
}
I am getting this error
Warning: array_reverse() [function.array-reverse]: The argument should be an array in /home/nlp4mark/public_html/Databasedemo/main.php on line 37
Any help would be really appreciated. Thanks.

You should only be executing this query once and then iterating through the results and displaying them:
$query = "SELECT * FROM databasedemo ORDER BY id DESC";

$query = "SELECT * FROM databasedemo WHERE id='$i'";
That query will return a one record at the time. You are sending it 6 times with the for loop, that's why you get all the records, but you send 6 times a slighty different query.
try sending one query that return all the 6 records and then reverse it. It would be something like this
$sql = "SELECT * FROM databasedemo WHERE 1=1";
for($i=0;i<6;$i++){
$sql .= " AND id=$i";
}

do like this
select * from (SELECT * from messages INNER JOIN logindata ON messages.author = logindata.id ORDER BY messages.mid DESC LIMIT 0,10) as t ORDER BY t.mid asc

Related

i want to pass limit value in my select query through user

i want to pass limit value in my select query through user,can anybody help me to do this???? thanks in advance![][1]
$result = mysql_query("select distinct * from tweet_info ".
"where MATCH(tweet) ".
"AGAINST('".$search."')ORDER BY created ", $con);
lets just say that the user input is "LimitInput" then :
$limit = $_POST['LimitInput'];
$result = mysql_query("select distinct * from tweet_info ".
"where MATCH(tweet) ".
"AGAINST('".$search."')ORDER BY created limit 0,".$limit, $con);
$result = mysql_query("SELECT DISTINCT *
FROM tweet_info
WHERE MATCH(tweet)
AGAINST('" . $search . "')
ORDER BY created LIMIT 0,1 DESC", $con);
Just add a limit to the end, this will grab the first result found.
You shouldn't really be using the mysql_query function anyway, it's depreciated, maybe look into a different method, e.g. mysqli or PDO.

how can i use two mysql query with user defined variable in php

select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
This query works in mysql console
but
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
this code raise error in php
so, I tried this
$query="
select * from ct_product, (select #min_price:=min(prd_sale_price),#max_price:=max (prd_sale_price) from ct_product) as b
where prd_sale_price=#min_price or prd_sale_price=#max_price
";
$result = mysql_query($query);
that works
...
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
What's the way that this code would work well without modification as my second way?
Use two calls to mysql_query:
$query1 = "select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product";
$query2 = "select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price";
mysql_query($query1);
mysql_query($query2);
Variables are associated with a database connection, so they'll persist between the calls.
in PHP mysql_query() can handle only one query at a time
You can't make this method handle 2 query at the same time
what I can suggest is using mysql_query() for every query

php random mysql data

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 am having problem in "fetching" only one entry from mysql

I want only one single data from that DB but I am not able to "take it out of" $res.
$sql = "SELECT * FROM `study_stuffs_extra`.`tid` ORDER BY `id` DESC LIMIT 1 ";
$res = query($sql);
$tid = $res['tid'];
I have also tried a while loop to do so, but "couldn't do it". Is there any other method to "do it"?
try
$sql = "SELECT * FROM `study_stuffs_extra`.`tid` ORDER BY `id` DESC LIMIT 1 ";
$res = mysql_query($sql);
$res=mysql_fetch_array($res);
$tid = $res['tid'];
SELECT tid FROM study_stuffs_extra ORDER BY `id` DESC LIMIT 1
Also, check what query returns. Is that a mysql result? the whole result set? a row? Do some print_r to see what you get. Check for db errors after executing queries.
You may need to subscript the first member of $res, assuming it is an array.
$firstRow = $res[0];

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");

Categories