开发者

Catch an array of data and outputting a single row

开发者 https://www.devze.com 2023-02-26 23:22 出处:网络
I need to have a single row of data \"printed out\" through php. So, take this example from w3schools:

I need to have a single row of data "printed out" through php.

So, take this example from w3schools:

http://www.w3schools.com/PHP/php_mysql_select.asp

There is a cicle that goes through all the rows ( in this case, 2) and prints them out. The end result is:

Peter Griffin

Glenn Quagmire

What I want is to be able to select row 1 or 2 (or more) and just have that row of data selected. Then I could say something like (I know this开发者_StackOverflow doesent work, just an example):

echo $row["Name",2];

And get:

Glenn Quagmire

I believe I have to get a special parameter in mysql_fetch_array, but I cant find it anywhere, and I bet its something really simple. Please help me out, full examples/tutorials/guides links are preferred.


you have 2 options. First is edit your SQL query like exmaple below this will return just 2nd row from database.

$result = mysql_query("SELECT * FROM Persons" WHERE id = 2);

Or during the foreach loop fetch all result into another array.

$result = mysql_query("SELECT * FROM Persons");

$rows = array();
while($row = mysql_fetch_array($result))
{
  $rows[] = $row['FirstName'] . " " . $row['LastName'];  
}


As far as i know mysql doesnt have a function to return the entire query as an array.

So you can switch to using PDO (recommended):

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
echo $result[1]['name'];

or if you must use the mysql_functions just create an array with the loop:

while($row = mysql_fetch_array($result)) {
    $result[] = $row;
}
echo $result[1]['name'];


fetchall the results into an array and print the row you want.

0

精彩评论

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