php
  • mysql
  • 2012-07-09 28 views 0 likes 
    0

    我想從MySQL數據庫中獲取一個值並將其放入一個PHP變量中。MySQL查詢數據到一個PHP變量

    我嘗試這樣做:

    $data = mysql_query("SELECT userid FROM ao_user " . 
        "WHERE username = '{$this->_username}' " . 
        "AND password = '{$this->_password}' AND display = '{$this->_display}'"); 
    

    代碼無效說用戶名/密碼。

    下面是用戶登錄代碼:

    <?php 
        $username = "Nynex71"; 
        mysql_connect("localhost", "root", "test") or die(mysql_error()); 
        mysql_select_db("test") or die(mysql_error()); 
        $result = mysql_query("SELECT display FROM ao_user " . 
        "WHERE username = '{$username}'") or die(msyql_error()); 
        $row = mysql_fetch_assoc($result); 
        echo $row['display']; 
    ?> 
    

    public function getDisplay() 
        { 
        mysql_connect("localhost", "root", "test") or die(mysql_error()); 
        mysql_select_db("test") or die(mysql_error()); 
    
        $result = mysql_query("SELECT display FROM ao_user " . 
         "WHERE username = '{$this->_username}'"); 
        $row = mysql_fetch_assoc($result); 
        $this->_display = $row['display']; 
        $_SESSION['display'] = $this->_display; 
        } 
    

    程序不把任何話到PHP變量。我做錯了什麼,你如何做到這一點?

    +0

    以下答案正確。然而,我的建議是,如果你剛開始學習PHP和MySQL。使用[MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO_MySQL](http://php.net/manual/en/ref.pdo-mysql.php)作爲mysql_ *貶值,因此你可能忘記它們存在! – 2012-07-09 21:42:19

    回答

    3

    mysql_query返回結果句柄,而不是您選擇的值。您必須先取一行,然後從該行中檢索該值:

    $result = mysql_query("SELECT ...") or die(msyql_error()); 
    $row = mysql_fetch_assoc($result); 
    echo $row['userid']; 
    
    +0

    非常感謝 – user1509916 2012-07-09 21:44:08

    +0

    以獲得所有答案行(而不僅僅是第一個答案行)將「$ row = mysql_fetch_assoc($ result)」部分放入類似「while($ row = mysql_fetch_assoc($ result)){echo $ row ['userid'];}「 – 2012-07-09 21:44:49

    相關問題