あなたのコードで提案したいことがいくつかあります。しかし、列名の変更に関しては、なぜ変更する必要があるのでしょうか? はいの場合は、クエリを修正する必要があります。あなたの関数のサニテーションと、PHP 5.0 以降で削除された mySQL の使用について少し心配しています。同等の代替品である mySQLi を見たいと思うかもしれません。私は手続き型のコードが得意ではないので、誤りがあればご容赦ください。
関数では、true を返す必要はありません。または mysql_query を返します。これらは返品なしで遵守されます。また、クエリ内では、次のようなキーワードを大文字にすることをお勧めしますSELECT, FROM, WHERE, INSERT INTO, LIMIT
。すべての列を選択する場合でも、選択する列も常に宣言する必要があります。クエリ文字列の例:
"SELECT * FROM table WHERE id = '{$id}'"//Variables should be entered in this way
//I don\'t know why they just do lol
"SELECT id,name FROM table WHERE table.id = '{$id}'"//This will only return the id and name from the table named table
したがって、スクリプトには mysqli プロシージャル スタイルをお勧めします。手続き型のスタイルは次のとおりです。
$DBH = new mysqli('localhost','user','pass','optional Database selection');
mysqli_select_db($DBH,'selection of the data can be done this way also');
mysqli_prepare($DBH,"SELECT * FROM table WHERE id = ?");//note the question mark instead of your $id variable.
mysqli_bind_param($DBH,'i',$id);//this replaces your question mark with the variable $id. This is a lot more sanitised that your example.
//bind_param() expects 3 parameters. first the database, second the variables datatype
// 'iiss' would be int int string string third comes your vars
mysqli_execute($DBH);
mysqli_bind_results($tableID,$tableName,$otherColumns);//your columns will be returned in order. Selecting * will return all columns. Selecting id,name will return only id and name column.
while(myslqi_fetch_result($DBH)){
//this is basically saying while there are results fro the database.
echo $tableID.' '.$tableName.' '.$otherColumns;
}
ここで、関数を構造化する方法として、OOP (オブジェクト指向プログラム) もお勧めします。それは次のようになります。
Class users{
private $DBH;//makes sure our database handler is secure
public function __construct(){
//public so that this function is ran at the start of the class
$this->DBH;//how to access your variables and functions in OOP in other words
//$addUser->DBH; which would be private and inaccessible.
$this->DBH = new mysqli('local','user','pass','database');
}
public function addUser($name,$surname){
$query = $this->DBH->prepare('INSERT INTO users VALUES(NULL,?,?');
$query->bind_param('ss',$name,$surname);
$query->execute();
//you can also run a check query returned true function :)
}
public function returnUser($id){
$data = array();
$query = $this->DBH->prepare('SELECT * FROM users WHERE id = ?');
$query->bind_param('i',$id);
$query->execute();
$query->bind_result($ID,$name,$surname,$other);
while($query->fetch_result()){
$data[] = array('ID'=>$ID,'name'=>$name,'surname'=>$surname,'other'=>$other);
}
return $data;
}
}
$userHandler = new users(); //adding an instance of the class users();
$usersInfo = $userHander->returnUser($id);//userinfo will now contain an array of arrays of users that have an id of $id. Depends how you use it :p
私が一度にやりすぎた場合、またはあなたがすでに知っていて、私がただのディックである場合は申し訳ありません笑 mysqli クエリとプログラムの構造についてお役に立てば幸いです