-5

I have copied the PDO connection script directly from the php.net documentation, however, it fails to work, because it gets this error.

<?php
  global $pdo = new PDO('mysql:host=localhost;dbname=pionear', "root", "");
?>

http://php.net/manual/en/pdo.connections.php

11
  • 3
    Please cite the link so the docs can be reviewed. Commented May 21, 2017 at 6:08
  • PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass); Commented May 21, 2017 at 6:09
  • Doubtful this is actually a copy/paste from the PHP documentation, since a Google search can't find your code. google.com/…" Commented May 21, 2017 at 6:11
  • Just cited the docs, despite changing some of the variables to string literals, it is more or less the same. Commented May 21, 2017 at 6:12
  • 2
    Oh, great, now you edit your question to remove the syntax error? Fantastic... Commented May 21, 2017 at 6:12

1 Answer 1

1

You cannot declare a variable in the global scope like that. You have to declare it as a normal variable and than access it through global (e.g. in a function):

$pdo = new PDO('mysql:host=localhost;dbname=pionear', "root", "");

function something() {
    global $pdo;
    $pdo->doSometing();
}

something();

You can check the documentation on the global keyword for more information. If you do not want to use the global keyword you can instead use $GLOBALS (which is a 'superglobal', thus no need to do global $pdo;).

Sign up to request clarification or add additional context in comments.

6 Comments

Good catch. I'm surprised this threw a syntax error, but it makes sense.
@Brad but a different one than the title, which only goes to show it was an edit to correct the obviousness of not a doc problem. It would have caused Parse error: parse error, expecting `','' or `';'' in Command line code on line 1
@Spechal It's definitely not a documentation problem as Jack's code was not copied/pasted from the docs as he asserted.
@Spechal He also added global.
Generally speaking, it's not a good idea to use global variables in the first place - they should be passed as arguments to the function, that way you have more control over which variables are in what scope.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.