簡體   English   中英

PHP OOP使用mysql從數據庫獲取數組

[英]PHP OOP Fetch array from Database with 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 / >";
}

盡管按照我的計划工作,但我對代碼不滿意,我想像這樣從“ db”獲取“ Id”和“ Grad”的信息。

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

好吧,在嘗試回顯“ Id”和“ Grad”時我卡住了,我得到了他的通知

注意:第39行Array中C:\\ xampp \\ htdocs \\ poo \\ classes \\ MVC \\ userlogin.php中的數組到字符串的轉換

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

您的getInfo()函數返回數組,因此請嘗試僅將其打印為

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

因此,看起來getInfo()將獲得第一行的第一個值,然后在第二次調用時獲得第一行的第二個值。 如果是第三次呢?

因為只獲取1行,所以您可以做的一件事就是只在getInfo()中返回mysql_fetch_assoc($ this-> Resource),而無需while循環。 這只會為您提供第一行作為關聯數組,您可以執行以下操作:

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

我還要在這里提到,如果用戶提供$ Email或$ Parola,則不建議使用mysql_函數,並且該代碼易於受到mysql注入攻擊。 查看PDO和准備好的語句以防止這種情況。 如果您真的更喜歡自己的格式,則可以在getInfo()中這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM