开发者

Call to a member function rollback() on a non-object

开发者 https://www.devze.com 2023-01-26 01:50 出处:网络
I run a localhost XAMPP server at my office for testing purposes. I am traveling and decided I\'d get some work done on my laptop so I installed a new version of XAMPP on my laptop, copied my files ov

I run a localhost XAMPP server at my office for testing purposes. I am traveling and decided I'd get some work done on my laptop so I installed a new version of XAMPP on my laptop, copied my files over but for some reason, I get non-stop errors on my laptop version where I don't get a single on my desktop.

One of the big ones is a simple log in page for one of my sites.

every time I try and run the code, I get the following error:

Call to a member function rollback() on a non-object

My code is:

开发者_开发技巧<?php
    session_start();

    if( $_SERVER['SERVER_PORT'] == 80) {
        header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]); 
        die();
    }   

    try
    {
        $db = new PDO('mysql:host=localhost;dbname=DB', 'USER', 'PW');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->beginTransaction();

        $sql = $db->prepare("SELECT user, pw FROM table WHERE user=? AND pw=?");
        $sql->execute(array($_POST['user'], $_POST['pw']));
        $foundrows = $db->query("SELECT FOUND_ROWS()")->fetchColumn();

        $rows = $sql->fetchAll();

        foreach($rows as $row) {
            $username = $row[0];
            $pw = $row[1];
        }

        $db->commit();
        $db->NULL;
    }

    catch (PDOException $e)
    {
        $db->rollback();
        echo $e->getMessage();
        exit;
    }


    if ($foundrows == 1) {

        (store stuff and exit to Page A)

    } else {

        (create error and return to login page)

    }
?>

As I said before, this runs without issue on my desktop (and several live sites i use elsewhere). What the H is going on?

Note: I thought it may be different configurations of my PHP file but i copied over the php.ini file from my desktop and still no luck...


Your code is indicating that $db->rollback() is failing, because $db has not been defined. Let's have a look at a snippet of your code:

try
{
    $db = new PDO('mysql:host=localhost;dbname=DB', 'USER', 'PW');
    [snip]
}

catch (PDOException $e)
{
    $db->rollback();
    echo $e->getMessage();
    exit;
}

I think your code isn't even getting past the first statement in the catch block, i.e. an exception is being thrown in the PDO constructor. To test this, move echo $e->getMessage; above $db->rollback(), or do the rollback conditionally:

catch (PDOException $e)
{
    if ($db) {
        $db->rollback();
    }
    echo $e->getMessage();
    exit;
}

To fix this more generally, please check your database settings closely -- perhaps there has been an error moving from one server to another?

0

精彩评论

暂无评论...
验证码 换一张
取 消