NaughtySquid
NaughtySquid

Reputation: 2087

php pdo mysql fetch returns a general error?

When trying to do this:

        // make unread notifications
        $db->sqlquery("SELECT `participant_id` FROM `user_conversations_participants` WHERE `conversation_id` = ? AND `participant_id` != ?", array($_POST['conversation_id'], $_SESSION['user_id']));
        while ($participants = $db->fetch())
        {
            $db->sqlquery("UPDATE `user_conversations_participants` SET `unread` = 1 WHERE `participant_id` = ?", array($participants['participant_id']));
        }

I seem to get this error:

Warning: PDOStatement::fetch() [pdostatement.fetch]: SQLSTATE[HY000]: General error in /home/gamingon/public_html/prxa.info/includes/class_mysql.php on line 68

Here is my query and fetch functions:

// the main sql query function
public function sqlquery($sql, $objects = array())
{
    global $core;

    try
    {
        $this->STH = $this->database->prepare($sql);

        foreach($objects as $k=>$p)
        {
            // +1 is needed as arrays start at 0 where as ? placeholders start at 1 in PDO
            if(is_numeric($p))
            {
                $this->STH->bindValue($k+1, (int)$p, PDO::PARAM_INT);
            }
            else
            {
                $this->STH->bindValue($k+1, $p, PDO::PARAM_STR);
            }
        }

        $this->counter++;

        return $this->STH->execute();
    }

    catch (Exception $e)
    {
        $core->message($e->getMessage());
    }
}

public function fetch()
{
    $this->STH->setFetchMode(PDO::FETCH_ASSOC); 
    **return $this->STH->fetch();**
}

Upvotes: 1

Views: 6028

Answers (1)

RickN
RickN

Reputation: 13500

During the first iteration of the loop, you overwrite the STH property of the $db instance. In other words:

  1. You do a SELECT query, $db->STH is a SELECT prepared statement.
  2. You do a fetch() call on the SELECT statement, which works.
  3. First loop iteration: You overwrite $db->STH with an UPDATE prepared statement.
  4. Just before the second loop iteration: You can't do a fetch() call anymore, because the SELECT statement is gone, an INSERT statement is in its place.

Refactor your database class or make a new instance of $db's class (with a different variable name!) for use in the loop.

Upvotes: 4

Related Questions