开发者

i was wondering how to handle a MySQL request in php as an Object?

I was wondering how I can handle a mysql request in php precisely as an object.

Ex:

//supposing...
$beginning=$_GET['start'];//value equal to 3
$ending=$_GET['end'];//value equal to 17
$conn=new mysqli("localhost","user","password","databasename");
$query=$conn->query("select name, favoriteFood, weight, from tablename");

1- Supposing that tablename has 23 rows, how to printing only 14 rows, beginning for example by 3rd row and ending in 17th row, as following?

Ex:

//supposing... It, I guess, should result in error but is a sketch of my ideia    
for($i=$beginning,$colsCol=$query->fetch_array(MYSQLI_ASSOC); $i<$ending; $i++)
printf("%s %s %s<\br>",$colsCol['name'][$i],$colsCol['favoriteFood'][$i],$colsCol['weight'][$i]);

2 - And later, how to order the resulted rows with $query variable?

P.S.: I know that t开发者_StackOverflow社区o get results ordered, I could user order by columname, but in this case I would like to order the resulted rows after query been done.


If you want to sort later, after the query's done, then you'd need to store the results in a PHP data structure and do the sorting there. Or re-run the query with new sorting options.

As for fetching only certain rows, it'd be far more efficient to retrieve only the rows you want. Otherwise (for large result sets) you're forcing a lot of data to be pulled off disk, sent over the wire, etc... only to get thrown away. Rather wasteful.

However, if you insist on doing things this way:

$row = 0; $data = array();

while($row = $query->fetch_array(MYSQLI_ASSOC)) {
   $row++;
   if (($row < 3) || ($row > 17)) {
      continue;
   }
   $data[] = $row;
}


for 2D array you can use it.


function asort2d($records, $field, $reverse=false) {
// Sort an array of arrays with text keys, like a 2d array from a table query:
  $hash = array();
  foreach($records as $key => $record) {
    $hash[$record[$field].$key] = $record;
  }
  ($reverse)? krsort($hash) : ksort($hash);
  $records = array();
  foreach($hash as $record) {
    $records []= $record;
  }
  return $records;
} // end function asort2d


Use SQL for SQL-tasks:

"how to printing only 14 rows, begging for example by 3rd row and ending in 17th row"

$stmt = $database->prepare('SELECT `name`, `favoriteFood`, `weight` FROM `tablename` LIMIT :from, :count');
$stmt->bindValue(':from', (int)$_GET['start'] - 1);
$stmt->bindValue(':count', (int)$_GET['end'] - (int)$_GET['start']);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜