php
  • mysql
  • 2013-07-24 25 views -4 likes 
    -4

    我試圖運行此程序卻不料mysql_fetch_assoc()函數返回只即使有很多條目,並進一步在foreach循環錯誤說的第一項單列提供非法「參數」用戶名mysql_fetch_assoc()返回即使有許多行

    <?php 
    $dbc=mysql_connect("localhost","root","nanu"); 
    mysql_select_db('users'); 
    $getQuery='SELECT * FROM userst ORDER BY username'; 
    $result=mysql_query($getQuery,$dbc); 
    $rel=mysql_fetch_assoc($result); 
    echo'<pre>'.print_r($rel).'<pre/>'; 
    echo"<br/>".$rel['username']."<br/>"; 
    foreach($rel as $Query[]){ 
    echo $Query['username']; 
    } 
    ?> 
    
    +1

    [**請不要使用'mysql_ *'功能在新代碼中**](http://bit.ly/phpmsql)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 –

    +1

    -1因爲您沒有閱讀手冊。或者萬億個教程之一。 –

    +0

    我還在想對你怎麼努力追查問題,可能是第一個谷歌搜索結果提供了mysql_fetch_assoc的使用的一個例子。 – JonathanRomer

    回答

    1

    您重新調整數組或行,你必須環通每行

    while ($rel = mysql_fetch_assoc($result)) 
    { 
        echo'<pre>'.print_r($rel).'<pre/>'; 
        echo"<br/>".$rel['username']."<br/>"; 
        foreach($rel as $Query[]){ //don't think you need this foreach loop 
        echo $Query['username']; 
        } 
    } 
    

    Please, don't use mysql_* functions in new code

    5

    mysql_fetch_assoc()總是返回下一行或爲false。您應該將它稱爲循環:

    while ($rel = mysql_fetch_assoc($result)) {...} 
    
    +0

    不應該是mysql_雖然(我知道這是什麼OP使用) –

    0

    mysql_fetch_assoc返回當前指針處的行。你需要把它作爲一個循環的一部分,作爲PHP文檔顯示:

    while ($row = $result->fetch_assoc()) { 
    
    1

    $rel=mysql_fetch_assoc($result);只會在一個時間取決於資源指針讀取一行。

    該指針將增加,一旦你使用的語句,所以使用它與一個循環語句會給你的所有行。

    while ($rel = mysql_fetch_assoc($result)) { 
        echo $rel['username']; 
    } 
    

    請嘗試更安全的API像mysqliPDO代替mysql_* API。 它們已被棄用。

    http://php.net/manual/en/mysqlinfo.api.choosing.php

    不推薦使用舊的MySQL擴展新的發展,因爲它已被棄用PHP 5.5.0的,並會在將來被移除。

    0
    while ($row = mysql_fetch_assoc($result)) { 
    echo $row['username']; 
    } 
    
    相關問題