mysql fetch数组个人回声php

时间:2015-07-31 04:46:28

标签: php variables echo

需要从mysql select语句中获取行内容。目前从高id和desc开始。需要获取最高ID并获得它,并且接下来的15行,并且需要将它们存储为变量。这是一个例子:

 $servername = "localhost";
 $username = "_p";
 $password = "1";
 $dbname = "w";
 mysql_connect("localhost", "p", "s") or die(mysql_error()); 
 mysql_select_db("p") or die(mysql_error()); 

 $highest_id = mysql_result(mysql_query("SELECT MAX(id) FROM NE2"), 0);
 $result = mysql_query("SELECT content, id FROM NE2 order by ID desc LIMIT 15  ");
 while($row[0] = mysql_fetch_array($result)){

      echo $row[0]['content'];

3 个答案:

答案 0 :(得分:0)

像这样使用

 $result = mysql_query("SELECT content, id FROM S_ENGINE2 order by ID desc LIMIT 15");
 if (mysql_num_rows($result) > 0)
 {
     while($row = mysql_fetch_array($result))
     {
         echo $row['content']."<br>"; 
     }
 }

这可能会对你有所帮助

答案 1 :(得分:0)

while循环逐行执行,在一个实例中你只能有一行(就像数组索引一样),所以喜欢

 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
       echo $row["id"];
       echo $row["contetnt"]);
    }
  

NOTE: mysql_*已弃用,不建议使用。使用PDO进行安全的数据库交互

答案 2 :(得分:0)

您可以使用一个查询执行此操作并访问前16个ID(最大ID和15个下一个ID)

$servername = "localhost";
$username = "_p";
$password = "1s";
$dbname = "wc";

mysql_connect($servername, $username, $dbname) or die(mysql_error());
mysql_select_db("we_ppp") or die(mysql_error());

// Let's get the 16 first highest id's and their content
// Why 16 ? We want the highest and the 15 next
$result = mysql_query("SELECT content, id FROM SEARCH2 order by ID desc LIMIT 0, 16");

// Now it's easied to handle if we just stack the result in a big array
$data_array = array();
while($row = mysql_fetch_array($result)) {
        $data_array[] = $row;
}

// Now we have $data_array[0] to $data_array[15] (the 16th row) each one containing
// an associative array resulting from the mysql_fetch_assoc().
// Now if I want the highest id :

$highest_id = $data_array[0]['id'];
$highest_content = $data_array[0]['content'];

// And the next 15 are
for($i = 1; $i < 16; $i++) { // We start at the second line until the 16th (numer 15)
        echo $highest[$i]['id'];
        echo $highest[$i]['content'];
}

// Now you do whatever you want with $highest and the next ones

这里的代码更具可读性:

http://pastebin.com/jGF94WJ2