PDO查询过滤器基于其他行

时间:2014-01-26 00:46:01

标签: php mysql pdo

这是我的代码:

//Connects to Database
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    try
    {
        $dbh = new PDO('dbconnection');
        foreach ($dbh->query('SELECT * from table' ) as $row)
        {
            $instructor = ($_POST["name"]);
            //Loads Certificate Template
            $jpg_image = imagecreatefromjpeg('cert.jpg');
            $color = imagecolorallocate($jpg_image, 82, 122, 124);
            //Sets Font
            $font_path = 'name.ttf';
            //Calls first name from database
            $firstname = $row['fname'];
            //Makes entire first name lower case
            $firstnamelower = strtolower($firstname);
            $firstnameucfirst = ucfirst($firstnamelower);
            //Calls Last Name From Database
            $lastname = $row['lname'];
            $lastnamelower = strtolower($lastname);
            $lastnameucfirst = ucfirst($lastnamelower);
            $name = $firstnameucfirst . ' ' . $lastnameucfirst;
            $font_size = 75;
            imagettftext($jpg_image, $font_size, 0, 810, 530, $color, $font_path, $name);
            imagettftext($jpg_image, 40, 0, 375, 945, $color, $font_path, $instructor);
            imagejpeg($jpg_image, 'images/' . $name . '.jpg', 50);
            imagedestroy($jpg_image);
        }
        $dbh = null;
    }
    catch (PDOException $e)
    {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
    echo "All certificates have been created."

    ?>

因此,我尝试更改它,以便只处理符合其他要求的图像。基本上我需要使用WHERE column_name运算符值;但是,当我这样做时,我会收到错误,我已经用Google搜索了,而且我并不真正理解他们在说什么。是否还需要使用pdo来完成此操作所需的代码?

这是我收到的错误警告:为foreach()提供的参数无效

1 个答案:

答案 0 :(得分:0)

错误来自于你的$ pdo-&gt;查询在失败时返回false而不是空数组。

http://www.php.net/manual/en/pdo.query.php

foreach期待一个数组。

调整代码:

$dbh = new PDO('dbconnection');

// Throw exceptions on errors
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

// To make it easier to debug
$sql = 'SELECT * from table';

// To allow check for failuer
$rows = $dbh->execute($sql);

if ($rows === false) ... oopsie

foreach($rows as $row) ...

然后让您的查询工作。考虑直接使用mysql来检查你的SQL。