我正在尝试从数据库中检索用户数据...值是常量(“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);
?>
我的表结构
最佳答案
要添加动态字段,您必须为字段名称绑定(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/