Echo the 2 last columns of tabel - php

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];

mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.

You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}

For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}

$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.

Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php

My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

Related

Getting exact value from fetched array from MySql

Not a duplicate of Select specific value from a fetched array
I have a MySql database as:
Here's my query:
$sql = "SELECT * FROM data ORDER BY Score DESC";
I want it to be a leaderboard which people can update their scores so I can't use
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
I want to get Username of the second row in my query.So I wrote:
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
}
echo "Result = '".$row[1]['Username']."''";
}
?>
But it returns Result = '' like there's nothing in the array.
But if I write
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Name = '".$row['Username']."''";
}
}
It will return : Parham, Mojtaba, Gomnam, Masoud,
So what am I doing wrong in the first snippet?
You can not access $row outside of while loop.
So store result in one new array, and then you can access that new array outside the while loop:
$newResult = array();
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$newResult[] = $row;
}
}
echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array
Because you write where condition after ORDER by at
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
The sequence of query is
SELECT * FROM data // select first
WHERE ID = 1
ORDER BY Score DESC// Order by at last
Check http://dev.mysql.com/doc/refman/5.7/en/select.html
And for second case you need to fetch Username inside while loop and use $row['Username'] instead $row[1]['Username']
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Result = '".$row['Username']."''";// write inside while loop
}
You can assign row value to any array and use that array.
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $row;
}
echo "Result = '".$rows[1]['Username']."'";
}
?>
Or if you want only second highest score from column you can user limit as
$sql = "SELECT * FROM data ORDER BY Score limit 1,1";

mysql_fetch_array pulling fewer results than it should

I have the following code:
$mostRecent = mysql_query("SELECT couponID FROM users_coupons WHERE userID = '$userID' ORDER BY id LIMIT 3");
while($row = mysql_fetch_array($mostRecent))
{
$mostRecentArr = $row;
}
var_dump($mostRecentArr);
The same SQL query in the command line returns 3 results, but this code only returns one result, even though I put LIMIT 3. Any help?
while($row = mysql_fetch_array($mostRecent))
{
$mostRecentArr[] = $row['couponID'];
}
You reassign the value in the loop each time, then dump the last value. Put var_dump in the loop after the assignment. Like so:
$mostRecent = mysql_query("SELECT couponID FROM users_coupons WHERE userID = '$userID' ORDER BY id LIMIT 3");
while($row = mysql_fetch_array($mostRecent))
{
$mostRecentArr = $row;
var_dump($mostRecentArr);
}
I guess what are you trying to do is:
$mostRecent = mysql_query("SELECT couponID FROM users_coupons WHERE userID = '$userID' ORDER BY id LIMIT 3");
$mostRecentArr = array();
while($row = mysql_fetch_array($mostRecent))
{
$mostRecentArr[] = $row;
}
var_dump($mostRecentArr);

MySQL query within another query's while loop in PHP

I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.

mysqli and php fetch object

I have the following code:
$sql_latest = "SELECT * FROM tbl_latest ORDER BY id DESC LIMIT 0,3 ";
$results_latest = $mysqli->query($sql_latest);
while($row = $results_latest->fetch_object())
{
echo $row->id;
}
How can I get the results into a array so I can do something like
echo $row[1];
echo $row[2];
echo $row[2];
I'm assuming you mean get all the rows in one array
$sql_latest = "SELECT * FROM tbl_latest ORDER BY id DESC LIMIT 0,3 ";
$results_latest = $mysqli->query($sql_latest);
$rows = array();
while($row = $results_latest->fetch_object())
{
$rows[] = $row;
}
echo $rows[0]->id;
echo $rows[1]->id;
Or, if you wanted the fields in the array:
while ($row = $results_latest->fetch_array()) {
echo $row[0]; //Prints the first column
}
you are using $results_latest->fetch_object method
how do you think what method should be used to get an array?
mysql_fetch_assoc or mysql_fetch_array
$sql_latest = "SELECT * FROM tbl_latest ORDER BY id DESC LIMIT 0,3 ";
$results_latest = $mysqli->query($sql_latest);
while($row = $results_latest->fetch_array())
{
echo $row[0];
}

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories