كيف يمكنني تنفيذ استعلام MySQL عبر PDO في PHP؟

StackOverflow https://stackoverflow.com/questions/159924

  •  03-07-2019
  •  | 
  •  

سؤال

أنا أتحرك ببطء كل ​​ما عندي LAMP websites من mysql_ وظائف ل PDO وظائف ولقد ضربت أول جدار من الطوب.لا أعرف كيفية تكرار النتائج باستخدام المعلمة.أنا بخير مع ما يلي:

foreach ($database->query("SELECT * FROM widgets") as $results)
{
   echo $results["widget_name"];
}

ولكن إذا أردت أن أفعل شيئًا مثل هذا:

foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results)
{
   echo $results["widget_name"];
}

من الواضح أن "الشيء الآخر" سيكون ديناميكيًا.

هل كانت مفيدة؟

المحلول

فيما يلي مثال لاستخدام PDO للاتصال بقاعدة بيانات، لإخبارها بطرح الاستثناءات بدلاً من أخطاء php (سيساعد ذلك في تصحيح الأخطاء)، واستخدام العبارات ذات المعلمات بدلاً من استبدال القيم الديناميكية في الاستعلام بنفسك (موصى به بشدة):

// $attrs is optional, this demonstrates using persistent connections,
// the equivalent of mysql_pconnect
$attrs = array(PDO::ATTR_PERSISTENT => true);

// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password", $attrs);

// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare the statement. the place holders allow PDO to handle substituting
// the values, which also prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand");

// bind the parameters
$stmt->bindValue(":productTypeId", 6);
$stmt->bindValue(":brand", "Slurm");

// initialise an array for the results 
$products = array();
if ($stmt->execute()) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $products[] = $row;
    }
}

// set PDO to null in order to close the connection
$pdo = null;

نصائح أخرى

بحسب ال وثائق PHP يقول أنه يجب أن تكون قادرًا على القيام بما يلي:

$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $results)
{
   echo $results["widget_name"];
}

أنا لست خبيرا، ولكن هذا يجب أن ينجح.

إذا كنت تحب بناء جملة foreach، يمكنك استخدام الفئة التالية:

// Wrap a PDOStatement to iterate through all result rows. Uses a 
// local cache to allow rewinding.
class PDOStatementIterator implements Iterator
{
    public
        $stmt,
        $cache,
        $next;

    public function __construct($stmt)
    {
        $this->cache = array();
        $this->stmt = $stmt;
    }

    public function rewind()
    {
        reset($this->cache);
        $this->next();
    }

    public function valid()
    {
        return (FALSE !== $this->next);
    }

    public function current()
    {
        return $this->next[1];
    }

    public function key()
    {
        return $this->next[0];
    }

    public function next()
    {
        // Try to get the next element in our data cache.
        $this->next = each($this->cache);

        // Past the end of the data cache
        if (FALSE === $this->next)
        {
            // Fetch the next row of data
            $row = $this->stmt->fetch(PDO::FETCH_ASSOC);

            // Fetch successful
            if ($row)
            {
                // Add row to data cache
                $this->cache[] = $row;
            }

            $this->next = each($this->cache);
        }
    }

}

ثم لاستخدامه:

foreach(new PDOStatementIterator($stmt) as $col => $val)
{
    ...
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top