【问题标题】:PHP OOP Fetch array from Database with mysqlPHP OOP 使用 mysql 从数据库中获取数组
【发布时间】:2015-03-25 07:25:36
【问题描述】:

大家好,我有以下代码:

$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”时,我被卡住了,我收到了他的通知

注意:数组到字符串的转换 C:\xampp\htdocs\poo\classes\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

【问题讨论】:

    标签: php mysql arrays oop


    【解决方案1】:

    所以看起来 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);
    

    【讨论】:

    • 我知道 SQL 注入是可能的,稍后我会检查 PDO,因为我对 PHP 有更多的了解。
    【解决方案2】:

    你的 getInfo() 函数返回数组,所以试着像打印它一样

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

    【讨论】:

    • 这不是我的解决方案,因为我希望我的“Id”和“Grad”在 echo 后存储在 2 个会话中。
    • 然后将其存储在 $_SESSION 全局数组中
    • 我需要在其他页面上回显 Id 和 Grad,这样它就不起作用了。
    • Php 在每个请求的基础上运行。要跨多个页面请求持久化数据,您需要将数据存储在 $_SESSION 全局数组中,或者在任何请求时从数据库中获取它。
    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 2020-10-06
    相关资源
    最近更新 更多