わかりましたので、バインディングは初めてです。これが機能するコードです。この形式はチュートリアルから学びましたが、もっと効率的な方法があると思います。私の例では 4 つの名前がありますが、実際には 20 ほどのフィールドを持つプロジェクトで多くの挿入と更新を行うことになります。私はこのアプローチが明快であることを気に入っていますが、明らかに 20 以上のフィールドを扱う場合、かなりのスペースが必要です。最初に私のコードを見てみましょう。
使用する関数は次のとおりです。
// prepare the statement
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
// run the binding process
$this->stmt->bindValue($param, $value, $type);
}
// execute the prepared statement
public function execute(){
return $this->stmt->execute();
}
そして今、実際のコード
$database->query("
INSERT INTO users(
user_name,
user_password_hash,
user_email,
user_activation_hash
)
VALUES(
:user_name,
:user_password_hash,
:user_email,
:user_activation_hash
)
");
// bind the values
$database->bind(":user_name", "$this->user_name");
$database->bind(":user_password_hash", "$this->user_password_hash");
$database->bind(":user_email", "$this->user_email");
$database->bind(":user_activation_hash", "$this->user_activation_hash");
// execute the statement and insert the values into the database
$database->execute();
特に私は投稿フィールド、入力フィールド、変数、プレースホルダーを同じ名前で呼ぶ習慣があるので、それが良いことなのか悪いことなのかはわかりませんが、対処するときに役立つと思います私がなる大きな形。
いずれにせよ、私は次のようなことができます:
$placeholder_array = array(
"user_name" => "\$this->user_name",
"user_password_hash" => "\$this->user_password_hash",
"user_email" => "\$this->user_email",
"user_activation_hash" => "\$this->user_activation_hash"
);
// well use this copy to edit the array keys and keep original for the binding
$placeholder_copy = $placeholder_array;
// turn the array into a string i.e user_name, user_password_hash....
$fields = implode (", ", array_keys($placeholder_array));
// foreach to add : placeholder prefix for binding
foreach ($placeholder_copy as $key => $value){
$placeholder_copy [':'.$key] = $value;
unset($placeholder_copy[$key]);
}
// turn the copy array which has prefix :user_name into a string
$placeholders = implode (", ", array_keys($placeholder_copy));
$database->query("
INSERT INTO users($fields)
VALUES($placeholders)
");
// bind the values
foreach ($placeholder_copy as $bind_values => $value){
echo '$database->bind("'.$bind_values.'", "'.$value.'");' . "<br />";
}
// execute the statement and insert the values into the database
$database->execute();
次に、これを連想配列とテーブル名を渡すためのパラメーターを持つ関数に変換して、メイン コードをよりクリーンに保つことができます。
私が取り組んでいるプロジェクトには、ユーザーにデータを送信する大量の大きなフォームが含まれているため、これらをいくらでも実行すると想像してください。私はPDOを初めて使用し、それを把握しようとしているので、これらのタイプのクエリを構造化するより簡単な方法があるかもしれません.Googleとstackflowを見ましたが、彼らが何をしているのか本当にわからなかったので、自分でやると思いました.人々は私に何が起こっているのかをよりよく説明してくれます。後で戻ってすべてを変更するよりも、プロジェクトを開始して正しく理解することをお勧めします。それで、より良いアプローチがありますか、それともこれは大丈夫ですか?
フィードバックに本当に感謝しています。ここで人々のアドバイスを受けて、PDO に移行したことをうれしく思います。