Search code examples
phpmysqlmysqlibindparam

code to search for a constant value by posting the column name is not working need some correction


I am trying to retrieve user data from a database ... value is constant ("t") and i have so many columns to search in so i have decided to post the column name using post method and look for the constant value("t" in my case). I have created this code but it's not working, please check the code and i am testing it using postman so attaching a screenshot please take a look for what error i am getting.

My function in 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();
        }
    }
?>

My 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

My Table Structure

enter image description here


Solution

  • For adding dynamic field you have to bind params for field names. Also you forgot and for combine conditions so change your code to :

        $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();