0

わかりましたので、mysqlよりもはるかに安全だと聞いたので、phpで準備されたステートメントを学習しています

だから今、関数を手に入れただけです。mysql dbに接続する関数を作成し、それを使用したいページとは別のフォルダーに配置しました。だから私はすべての主要な機能を1つのファイルに入れたいので、必要なページのファイルからそれらを呼び出したいと思っています。しかし今、phpはそれを好まない.

これが私の functions.php ページです

function mysqlconnect(){

$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = '';
$username = '';
$password = '';

// Construct the DSN, or "Data Source Name".  Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it.  As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";

// Connect!
$db = new PDO($dsn, $username, $password);
} 

そして、これが私のテストページで、関数の呼び出しをテストしています。

include 'functions/functions.php';

mysqlconnect();

$_POST['fish'] = "shadow" ;

$statement = $db->prepare("SELECT * FROM users WHERE username = ?");
$statement->execute(array($_POST['fish']));

while ($result = $statement->fetchObject()) {
    echo $result->username;
    echo "<br />";
}

ファイルをインクルードして関数を呼び出すことに注意してください。

Notice: 未定義の変数: db 致命的なエラー: オブジェクト以外でメンバ関数 prepare() を呼び出しています

接続を同じphpファイルに入れると、すべて正常に動作します。もちろん、同じファイル内のすべての関数が好きで、必要なときに呼び出すだけです。私は何を間違っていますか??

4

2 に答える 2

0

$db is inside a function and cannot be used outside. Look into Variable Scope. You can either declare $db as a global variable, or return $db from the function and then set $db=mysqlconnect(). There are dozens of other ways to do it, but as you have it, it can't be done.

Side note: I would personally do this:

function mysqlconnect(){
    /* your code here*/
    return $db;
}
$db = mysqlconnect();
于 2012-05-25T23:35:57.177 に答える
0

$db is defined inside a function, so it cannot become global. It's scope ends when the function ends.

You should define $db outisde your function.

A not-so-elegant solution:

function mysqlconnect(){
  global $db; 
  $host = 'localhost';
  // etc.etc.
  $db = new PDO($dsn, $username, $password);
}

Please take note that using global, expecially in this context, is a really bad practice (it undermines code cleanliness, code reusability, and can lead to several other problems).

A more elegant solution (like the other user says):

function mysqlconnect(){

  $host = 'localhost';
  // etc.etc.
  $db = new PDO($dsn, $username, $password);
  return $db;
}

And then in your test page:

$db = mysqlconnect();

This is useful as you can use any variable name: makes your code more reusable in other scenarios.

$donaldduck = mysqlconnect();

would be ok too.

于 2012-05-25T23:36:05.237 に答える