I am a new user and I really need some help. I am also trying to upgrade my skills to use pdo. I am not sure if this is a good thread to put this in or not. I have been searching the forums for days now trying to find my exact example and i just can't understand why I cannot get this to work. I can get this exact example to work using my old mysql code, but not when using pdo. I am trying to connect to a separate database in a snippet to retrieve info. I do not want to have to type the connection with the username and password every time I want to connect. I would like to put the connection in a different snippet (or even external file ) and include that instead of the actual connection. My code works fine when it is all in one snippet, but when i take the connection part out and call it from somewhere else, it does not work. It seems that the variables go out of scope whenever they are not in the same snippet. I apologize if that is not correct, but that is what is seems to me.
Test Snippet - Works fine
$dsn = 'mysql:dbname=db_name;host=localhost';
$user = 'user';
$password = 'pass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
die();
}
$stmt = $dbh->query('SELECT * from table');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$name=$row['name'];
echo '<a href="#">'.$name.'</a><br />';
}
Does NOT work when I put the connection info into a different snippet and then try to reference (via runsnippet or include.
dbConnect Snippet
$dsn = 'mysql:dbname=db_name;host=localhost';
$user = 'user';
$password = 'pass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
die();
}
Test Snippet
$modx->runSnippet('dbConnect');
$stmt = $dbh->query('SELECT * from table');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$name=$row['name'];
echo '<a href="#">'.$name.'</a><br />';
}
This returns:
Fatal error: Call to a member function query() on a non-object in ...
I have tried everything. I know this should be super simple, and I honestly have been looking for posts for a long time now. Any help or topic redirection would be helpful and I would be beyond grateful.