2015-01-26 35 views
0

嗨,大家好,我有以下代碼:PHP OOP取回陣列從數據庫和MySQL

$this->db->setQuery("SELECT id,grad FROM login WHERE Email='$Email' AND Parola='$Parola' LIMIT 1"); 
//setQuery Is setting the Query 
if($this->db->NumRows() > 0) { 
//Checking if Number of Rows is greater than 0 

    if(session_id() == ''){ 
     session_start(); 
    } 

    $this->Email = $Email; 

    while($row = mysql_fetch_array($this->db->GetResource())){ 
     //Fetching from the database the "Id" And "Grad" 
     $this->Id = $row[0]; 
     $this->Grad = $row[1]; 
    } 
    echo $this->Id . "<br />"; 
    echo $this->Grad . "<br/>"; 
} 

雖然是工作,我的計劃,我很不滿意的代碼,我想爲「ID信息「和」畢業「從這樣的」數據庫「。

$this->Id = $this->db->getInfo(); 
$this->Grad = $this->db->getInfo(); 

那麼這裏我想呼應 「ID」 和 「梯度」 我得到他的注意,當遇到問題

注意:數組字符串轉換在 C:\ XAMPP \ htdocs中\便便\類\ MVC \ userlogin.php第39行上陣列

代碼的getInfo():

//$this->Resource is the mysql_query of the setQuery 
$this->Rows = array(); 

if ($this->Resource) { 

    while ($row = mysql_fetch_array($this->Resource)) { 

     $this->Rows[] = $row; 

    } 

} 
return $this->Rows; 

我想提一提的是我是PHP和OOP的初學者。 代碼對所有功能使用http://tny.cz/4c5596fc

回答

0

所以它看起來像的getInfo()將獲得第1行的第1個值,然後第二次調用時獲取第一行的第二個值。如果它被稱爲第三次呢?

你可以做的一件事,因爲你只取1行,只是在沒有while循環的情況下,在你的getInfo()中返回mysql_fetch_assoc($ this-> Resource)。這將只是給你的第一行作爲關聯數組,你可以這樣做:

$row = $this->db->getInfo(); 
$this->Id = $row['id']; 
$this->Grad = $row['grad']; 

我還要在這裏提到的是mysql_功能已被取消,該代碼是容易的MySQL注入攻擊如果用戶提供$電子郵件或$ Parola。看看PDO並準備好聲明來防止這種情況發生。 如果你真的喜歡你的格式,你可以做這樣在你的getInfo():

if (!$this->Row) { 
    if ($this->Resource) { 
     $this->Row = mysql_fetch_array($this->Resource); 
    } 
} 
return array_shift($this->Row); 
+0

我意識到SQL注入是可能的,我將在稍後檢查PDO,因爲我可以獲得更多關於PHP的知識。 – camin10 2015-01-26 21:45:10

0

你的getInfo()函數返回數組,所以儘量只打印它像

echo '<pre>'; 
print_r($this->id); 
echo '</pre>'; 
+0

這會不會是我的解決辦法,因爲我希望我的「ID」和「梯度」存儲在2回聲後的會話。 – camin10 2015-01-26 20:02:31

+0

然後將其存儲在$ _SESSION全局數組 – 2015-01-26 20:09:33

+0

我需要在其他頁面上回顯Id和Grad,以便它不起作用。 – camin10 2015-01-26 20:37:05