0

I've been looking, at other questions asking the same, and can't figure out why my query won't act like it should.

My query:

$stmt = db()->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo db()->lastInsertId();

When I do this the lastInsertId(); keeps returning 0.

My db() function:

function db()
{
    $dsn = 'mysql:host=localhost;dbname=message_board';
    $username = 'root';
    $password = 'root';

    try {
        $db = new PDO($dsn, $username, $password);
    } catch(PDOException $e) {
        // exceptions handles here
    }
    return $db;
}
skolind
  • 1,724
  • 6
  • 28
  • 51

2 Answers2

7
function db()
{
    static $db;

    $dsn = 'mysql:host=localhost;dbname=message_board';
    $username = 'root';
    $password = 'root';

    if (!$db) {
       $db = new PDO($dsn, $username, $password);
    }
    return $db;
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

You're creating a new db connection every line.

Try:

$db = db();
$stmt = $db->prepare("INSERT INTO conversations (user1, user2) VALUES (?, ?)");
$stmt->execute(array($_SESSION['user']['userId'], $user));
echo $db->lastInsertId();
scottlimmer
  • 2,230
  • 1
  • 22
  • 29