2

I'm trying to output data into an xml file, everything is working fine except it's only saving the last record fetched.

The following query is used:

$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($query)){
$result = $row['mileage'];
}

My question is how do I make it so each record is saved in 3 seperate variables so I can output those 3 variables into an xml file. I am also trying to fetch only the last 3 rows sorted by the last date and last time so not sure if the query is correct for doing that.

Thank you.

5 Answers 5

1

Firstly: Don't use the mysql_* functions! They are obsolete and you should use PDO instead.

Secondly: The easiest thing to do is to construct an array containing the results.

$result = array();
$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($query)){
    $result[] = $row['mileage'];
}

The results of your query are now contained in $result[0], $result[1] and $result[2]. (If you use PDO the code does not look very different.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, yeah it is working now using $result[0], $result[1] and $result[2].
1
$result=array();
$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$result[]  = $row['mileage'];

}

Comments

0

You can use folowing;

$query = mysql_query("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");
while ($row = mysql_fetch_array($query)){
$result[] = $row['mileage'];
}

You can foreach $result and construct your xml.

Comments

0

try saving the output as an array instead.

$array[]=$value;

will push the $value inside the $array array.

Comments

-1

get yourself a function

function dbGetCol($sql){
  $ret = array();
  $res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if ($res) {
    while($row = mysql_fetch_row($res)){
      $ret[] = $row[0];
    }
  }
  return $ret;
}

and then just call it

$data = dbGetCol("SELECT mileage FROM cars WHERE make ='bmw' ORDER BY date DESC, time DESC LIMIT 3");

2 Comments

Thanks I guess I'll use this next time.
LOL. What next time you are talking about? If you have no idea what is a function and how to use it - just say that, no need to hesitate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.