次のコードについて質問があります。これは、DB ハンドラーとして使用する予定の PHP クラスです。INSERT では、小さなヘルパー関数を使用しています。主な理由は、手から文字列をサニタイズするのが面倒だからです。コードは次のとおりです。
<?php
class Db{
/*
* Configure DB settings here, make sure php is in good health. Check phpinfo();
*/
private $MYSQL_HOST = 'localhost';
private $MYSQL_USER = 'root';
private $MYSQL_PASS = '******';
private $db;
function select($selected_db, $sql){
//Create new object out of connection to db
$this->db = @new mysqli($this->MYSQL_HOST, $this->MYSQL_USER, $this->MYSQL_PASS, $selected_db);
//If there aren't any errors
if(mysqli_connect_errno() == 0){
$result = $this->db->query($sql);
if($result){
$result = $result->fetch_array(MYSQLI_ASSOC);
}else{
echo "There is a problem with the query";
}
} else { //If you couldn't connect to DB at all
die("No connection possible: " . mysqli_connect_error());
}
//Close connection
$this->db->close();
return $result;
}
function dirtyLittleHelper($string){
//Change each character into its HTML equivalent
$string = htmlentities($string);
//Create a legal SQL string from input
$string = $this->db->mysqli_real_escape_string($string);
return $string;
}
}
?>
今私が得るエラーのために:
致命的なエラー: 35 行目の /path/to/file/db_class.php の非オブジェクトでメンバ関数 mysqli_real_escape_string() を呼び出します
質問は単になぜですか?サニタイズされていない文字列を使用したくありません。また、非推奨になっている mysql_real_escape_string を使用したくありません。
SQL を扱うのはこれが初めてなので、リスクを冒して質問の重複を投稿します。データベースへの道を開いたままにして、機能するバージョンを使用するだけでなく、適切に学習することが重要です。
前もって感謝します、 Stiller_leser
編集
ありがとう、私はとらえどころのないヒントで行くと思います。私は知りませんでした。とにかく確認するために、適切な挿入関数はそのように見えるでしょうか?
function insert($selected_db, $sql){
//Create new object out of connection to db
$this->db = @new mysqli($this->MYSQL_HOST, $this->MYSQL_USER, $this->MYSQL_PASS, $selected_db);
//If there aren't any errors
if(mysqli_connect_errno() == 0){
//If you could prepare query
if($result = $db->prepare( $sql )){
//Execute query
$result->execute();
} else { //If you couldn't prepare query
echo "There is a problem with the query";
}
} else { //If you couldn't connect to DB at all
die("No connection possible: " . mysqli_connect_error());
}
//Close connection
$this->db->close();