2017-06-30 4 views
0

mysqliを使用して行を取得していますが、行が与えられていないため、クエリにエラーはありません。Mysqliから行を取得しない

$query="select * from members where useremail='$user_email' and password='$password'"; 
$result=$db->query($query); 
$row = $db->fetch_array($result); 
echo $row['id']; 

マイquery機能

function query($query){ 
     $result=mysqli_query($this->conn, $query); 
     if(!$result){ 
      echo $this->err_msg = mysqli_error($this->conn); 
      return false; 
     }else{ 
      return $result; 
     } 
} 

マイfetch_array機能

function fetch_array($result){ 
    return mysqli_fetch_array($result); 
} 

は、どのように私はmysqliを使用して行を取得することができますか?

+4

あなたのコードがする可能性が脆弱である[** SQLインジェクション**](httpsを行いたい://en.wikipediaを。 org/wiki/SQL_injection)の攻撃を防ぎます。あなたは[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)または[** PDO **](https ://secure.php.net/manual/en/pdo.prepared-statements.php)ドライバ。 [**この記事**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)には、いくつかの良い例があります。 –

+0

@AlexHowansky私はmysqliを使用しています。 –

+0

はい、バインドされたパラメータを持つ準備済みの文は使用していません。 –

答えて

1

、これはより安全であるとmysqliのは、ステートメントに

$query="select id from members where useremail=? and password=?"; // Don't use select *, select each column, ? are placeholders for your bind variables 
$stmt = $connection->prepare($query); 
if($stmt){ 
    $stmt->bind_param("ss",$user_email,$password); // Bind in your variables, s is for string, i is for integers 
    $stmt->execute(); 
    $stmt->bind_result($id); // bind the result to these variables, in the order you select 
    $stmt->store_result(); // Store if large result set, can throw error if server is setup to not handle more than x data 
    $stmt->fetch(); 
    $stmt->close(); 
    } 
echo $id; // this would be same as $row['id'], $id now holds for example 5. 

あなたが複数のものを選択した場合

を作成し使用してバインドされたパラメータに

$query="select * from members where useremail='$user_email' and password='$password'"; 
    $result=$db->query($query); 
    $row = $db->fetch_array($result); 
    echo $row['id']; 

を動作するはずですmysqliのを使用してバインドされたパラメータを反映するために、あなたの元のコードを変更して、そのような"SELECT id,name FROM..."とすると、bind_result(..)のときにnをバインドするだけです。 $stmt->bind_result($id,$name);

今、$ idと$ nameは、クエリに一致する行の列データを保持します。一致する複数の行が存在することになる場合は、代わりに$ stmt-の>(フェッチ)あなたは

while($stmt->fetch()){ // just like while($row = $result->fetch_assoc()){} 
    echo $id; 
    echo $name 
} 
+0

'$ row ['id']'をどのように取得できますか?セッションに保存したいのですが、mysqliを用意していません。私は完全な行が必要なことを意味し、行から何かを得るのですか? –

+0

'' SELECT id ... "'、次にbind_result($ id)を実行します。 $ row ['id']は$ idになります。そして、あなたはmysqliを使用しています。準備されたステートメントは、SQLインジェクション攻撃を防ぐためのアイデアです。 while($ stmt-> fetch())の各反復では、while($ row = $ result-> fetch_assoc())の場合と同じ結果が得られます。 $ row ['id']は$ idを使ってアクセスされるようになりました。 – clearshot66

関連する問題