2017-11-11 83 views
2

我試圖從數據庫中檢索用戶數據...值是常量(「t」),我有很多列來搜索因此我決定使用post方法發佈列名並查找常量值(在我的情況下爲「t」)。我已經創建了這個代碼,但它不工作,請檢查代碼,我正在測試它使用郵遞員,所以附上截圖,請看看我得到什麼錯誤。通過發佈列名不工作來搜索恆定值的代碼需要一些更正

我在DbOperations.php

<?php 

    class DbOperations{ 

    private $con; 

    function __construct(){ 

     require_once dirname(__FILE__).'/DbConnect.php'; 

     $db = new DbConnect(); 

     $this->con = $db->connect(); 

    } 

    //CRUD -> c -> CREATE 

    //Test Purpose 

    public function gettestuser($value, $pin){ 
     $valid_columns = array('a' => 1, 'b' => 1, 'ho' => 1, 'll' => 1, 'c' => 1, 'd' => 1); 
     if (!array_key_exists($value, $valid_columns)) { 
      throw new Exception("Error Processing Request", 1); 
     } 

     $stmt = $this->con->prepare("SELECT * FROM test_category WHERE $value = 't' pin = ?"); 
     $stmt->bind_param("ss", $value, $pin); 
     $stmt->execute(); 
     return $stmt->get_result()->fetch_assoc(); 
     } 
    } 
?> 

我gettestuser.php

<?php 
require_once '../include/DbOperations.php'; 

$response = array(); 

if($_SERVER['REQUEST_METHOD']=='POST'){ 
    if(isset($_POST['reg_value']) && isset($_POST['reg_pin'])){ 

    $db = new DbOperations(); 

    $test_category = $db->gettestuser($_POST['reg_value'], $_POST['reg_pin']); 

    var_dump($test_category); 

     $response['error'] = false; 
     $response['pid'] = $test_category['pid']; 
     $response['name'] = $test_category['name']; 
     $response['pin'] = $test_category['pin']; 
     $response['a'] = $test_category['a']; 
     $response['b'] = $test_category['b']; 
     $response['ho'] = $test_category['ho']; 
     $response['ll'] = $test_category['ll']; 
     $response['c'] = $test_category['c']; 
     $response['d'] = $test_category['d']; 



    }else{ 
     $response['error'] = true; 
     $response['message'] = "Required fields are missing"; 
     } 
    } 

echo json_encode($response); 
?> 

enter image description here

我的表結構功能

enter image description here

+0

在該行的錯誤是說我懷疑它的'其中$值=「T」腳='這是錯的?你也不能綁定列。 –

+0

@LawrenceCherone謝謝......但你能告訴我我在那裏做錯了什麼?我一點也不明白。 –

+0

它應該很可能是'WHERE the_reg_column =? AND pin =?',列名的所有字母是什麼? –

回答

1

要添加動態字段,必須爲字段名稱綁定參數。同時您忘記and的組合條件,改變你的代碼:

$stmt = $this->con->prepare("SELECT * FROM test_category WHERE $value = 't' and pin = ?"); 
    $stmt->bind_param("s", $pin); 
    $stmt->execute(); 
    return $stmt->get_result()->fetch_assoc(); 
+0

謝謝...這段代碼很好,但是有兩件事情做錯了... 1.當沒有找到匹配的結果時它仍然顯示:C:\ wamp64 \ www \ Android \ v1 \ gettestuser.php:13:null { 「錯誤」:假​​的, 「PID」:空, 「名」:空, 「針」:空, 「一」:空, 「b」:空, 「豪」:空, 「LL」:空,「C 「:null,」d「:null} 2.它不顯示多個用戶數據......它只返回一個用戶的詳細信息。 –

+0

您需要while循環來獲取多個數據。請參閱https://stackoverflow.com/questions/35103594/get-result-fetch-assoc-always-returning-1-row –

相關問題