简体   繁体   中英

PHP OOP Fetch array from Database with mysql

Hi guys I have the following code :

$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 / >";
}

Although is working as I planned, I am not satisfied with the code, I want to get the information for "Id" and "Grad" from the "db" like this.

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

Well here I get stuck when trying to echo "Id" and "Grad" I get his Notice

Notice: Array to string conversion in C:\\xampp\\htdocs\\poo\\classes\\MVC\\userlogin.php on line 39 Array

Code for 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;

I want to mention that I am a beginner in PHP and OOP. Code to all function used http://tny.cz/4c5596fc

Your getInfo() function returns array, so try to just print it like

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

So it looks like the getInfo() would get the 1st value of the 1st row, then when called the second time get the 2nd value of the first row. What if it's called a third time?

One thing you could do, since you are only fetching 1 row, is to just return mysql_fetch_assoc($this->Resource) in your getInfo() without the while loop. This will just give you the first row as an associative array and you could do:

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

I should also mention here that the mysql_ functions are deprecated and the code is prone to mysql injection attacks if the user supplies $Email or $Parola. Take a look into PDO and prepared statements to prevent this. If you really prefer the format you have, you could do it like this in your getInfo():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM