php - 通过发布列名来搜索常量值的代码不起作用需要一些更正

标签 php mysql mysqli bindparam

我正在尝试从数据库中检索用户数据...值是常量(“t”)并且我有很多列要搜索所以我决定使用 post 方法发布列名并查找常量值(value)(在我的例子中是“t”)。我已经创建了这段代码,但它不起作用,请检查代码,我正在使用 postman 对其进行测试,因此请附上屏幕截图,请查看我收到的错误。

我在 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

最佳答案

要添加动态字段,您必须为字段名称绑定(bind)参数。此外,您还忘记了 的组合条件,因此请将您的代码更改为:

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

关于php - 通过发布列名来搜索常量值的代码不起作用需要一些更正,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236362/

相关文章:

php - 什么是框架?什么是学说 2?

php - 将 mysql 查找/替换为 mysqli 使代码无法运行

php - 简单的ORM(无需外部库)

MySQL (MyISAM) - 将字段更新为来自不同表的两个字段中的最大值

php 登录脚本如果返回 else 即使登录信息在 db 中是正确的

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - 表单提交在 mysql 中显示空白条目

php - ZF3/2 - 如何捕获在 EVENT_DISPATCH 监听器中抛出的异常?

php - 如何在Moodle上启用Web服务?

php - 在 Kohana 3.1.3 中使用接口(interface)