返回 ROW 以及使用 PDO 循环遍历 ROWS 的最简单方法是什么?

发布于 2024-09-19 18:56:50 字数 1062 浏览 3 评论 0原文

如果我正在做一个旧的查询来返回一行,我会做这样的事情:

$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);

echo $row['id'];

如何使用准备好的语句来做到这一点?我可以走到这一步...

 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to pull out this one row?       

 }

其次,如果我有多行,我会这样做:

$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {

   echo $row['id'];

}

同样,使用 PDO 我会到达类似的地方...

 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to loop through the rows??
    //
    // something like this...?
    //
    while ($row = $stmt->fetch()) {
       echo $row['id'];
    }       

 }

If I am doing an old query to return a row I would do something like this:

$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);

echo $row['id'];

How do I do that with a Prepared Statement? I can get this far...

 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to pull out this one row?       

 }

Secondly, if I have multiple rows I would do it like this:

$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {

   echo $row['id'];

}

Likewise, with PDO I get to a similar place...

 $stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
 if ($stmt->execute(array($_POST['email']))) {

    // what goes in here to loop through the rows??
    //
    // something like this...?
    //
    while ($row = $stmt->fetch()) {
       echo $row['id'];
    }       

 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏九 2024-09-26 18:56:50

假设您已连接到数据库,并且 $dbh 是您的 PDO 对象。

<?php

$email = '[email protected]';

$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");

$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);

$stmt->execute();


/* One row. */
$result = $stmt->fetch();

if ($result !== FALSE) {
    $stmt->closeCursor();

    echo $result['id'];
}


/* Multiple rows. */
$result = $stmt->fetchAll();

if ($result !== FALSE) {
    foreach ($result as $row) {
        echo $row['id'];
    }
}

?>

Assuming you're connected to the DB and $dbh is your PDO object.

<?php

$email = '[email protected]';

$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");

$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);

$stmt->execute();


/* One row. */
$result = $stmt->fetch();

if ($result !== FALSE) {
    $stmt->closeCursor();

    echo $result['id'];
}


/* Multiple rows. */
$result = $stmt->fetchAll();

if ($result !== FALSE) {
    foreach ($result as $row) {
        echo $row['id'];
    }
}

?>
一人独醉 2024-09-26 18:56:50

以下是我使用的内容:

有关 PDO 的更多信息,请参阅: http://php.net /manual/en/book.pdo.php

如何使用:

    //create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;

    //query
   $sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
    $values = array(":Abbr" => "AL");
    $query = new Query($conn);
    $testArr = $query->getArrayFromQuery($sql, $values);

连接:(Connection.php)

class Connection
{

    public $conn = null;

    /**
     * Creates PDO Database Connection
     *
     * @param array $params             Connection Data (host,database,username,password)
     * @param bool $useErrorReporting   True to Show Errors (optional)
     * @sets Database Connection
     * @access public
     */
    public function __construct($params,$useErrorReporting=false) 
    {
        try
        {   
            $host = "";
            $database = "";
            $username = "";
            $password = "";

            if(isset($params) && is_array($params))
            {
                $host = $params['database_connection']['host'];
                $database = $params['database_connection']['database'];
                $username = $params['database_connection']['username'];
                $password = $params['database_connection']['password'];

                $dsn = 'mysql:dbname='.$database.';host='.$host;
                $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));

                //display errors if true
                if($useErrorReporting)
                {
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                }
            }
            else
            {
                $dbh = null;
            }

        }
        catch (PDOException $e)
        {
            throw new Exception('Connection Failed: '.$e->getMessage());
        }

        $this->conn = $dbh;
    }

查询:Query.php

Class Query
{
    private $conn = null;

    /**
     * sets query properties
     *
     * @param object $conn      pdo connection object
     * @return void
     * @access public
     */
    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    /**
     * getArrayFromQuery
     * gets array from given query
     *
     * @param string $sql       sql statement
     * @param array $values     array values to replace (":value" => 2)
     * @return array
     * @access public
     */
    public function getArrayFromQuery($sql, $values)
    {
        $retValue = array();
        $conn = $this->conn;
        $statement = "";

        try
        {
            //prepare sql statement
            $statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

            //add values
            if(isset($values) && is_array($values))
            {
                $statement->execute($values);
            }

            //set return array to result array
            $retValue = $statement->fetchAll();

        }
        catch (PDOException $e)
        {
            throw new Exception("PDO Query Error: ".$e->getMessage());
        }
        catch(Exception $e)
        {
            throw new Exception("Process Query Error: ". $e->getMessage());
        }

        return $retValue;
    }

}

Here is what I use:

For more info on PDO see: http://php.net/manual/en/book.pdo.php

How to use:

    //create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;

    //query
   $sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
    $values = array(":Abbr" => "AL");
    $query = new Query($conn);
    $testArr = $query->getArrayFromQuery($sql, $values);

CONNECTION: (Connection.php)

class Connection
{

    public $conn = null;

    /**
     * Creates PDO Database Connection
     *
     * @param array $params             Connection Data (host,database,username,password)
     * @param bool $useErrorReporting   True to Show Errors (optional)
     * @sets Database Connection
     * @access public
     */
    public function __construct($params,$useErrorReporting=false) 
    {
        try
        {   
            $host = "";
            $database = "";
            $username = "";
            $password = "";

            if(isset($params) && is_array($params))
            {
                $host = $params['database_connection']['host'];
                $database = $params['database_connection']['database'];
                $username = $params['database_connection']['username'];
                $password = $params['database_connection']['password'];

                $dsn = 'mysql:dbname='.$database.';host='.$host;
                $dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));

                //display errors if true
                if($useErrorReporting)
                {
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                }
            }
            else
            {
                $dbh = null;
            }

        }
        catch (PDOException $e)
        {
            throw new Exception('Connection Failed: '.$e->getMessage());
        }

        $this->conn = $dbh;
    }

QUERY: Query.php

Class Query
{
    private $conn = null;

    /**
     * sets query properties
     *
     * @param object $conn      pdo connection object
     * @return void
     * @access public
     */
    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    /**
     * getArrayFromQuery
     * gets array from given query
     *
     * @param string $sql       sql statement
     * @param array $values     array values to replace (":value" => 2)
     * @return array
     * @access public
     */
    public function getArrayFromQuery($sql, $values)
    {
        $retValue = array();
        $conn = $this->conn;
        $statement = "";

        try
        {
            //prepare sql statement
            $statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

            //add values
            if(isset($values) && is_array($values))
            {
                $statement->execute($values);
            }

            //set return array to result array
            $retValue = $statement->fetchAll();

        }
        catch (PDOException $e)
        {
            throw new Exception("PDO Query Error: ".$e->getMessage());
        }
        catch(Exception $e)
        {
            throw new Exception("Process Query Error: ". $e->getMessage());
        }

        return $retValue;
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文