简体   繁体   English

如何通过存储在该列中的值访问列名

[英]How to access column name by the value stored in that column

I have a table its name is 'specialization' database name is 'hackathon' inside table it have one row and 8 columns "id" "name" "soft_dev" "Data_analytics" "DB_manager" "sys_engineer" "research" .networks_admin" the first row data is "5, gourav, 59.7,72.6,73.87,59.14,43.14,50.74" these are values respectively now.I am on $row['Data_analytics'] means I can access value 72.6 now I want to find out the name of this column in which it is stored Like the name is "Data_analytics". I want this value to be return how we can do it我有一个表,它的名字是'specialization' 数据库名称是'hackathon' 在表里面它有一行和8列“id”“name”“soft_dev”“Data_analytics”“DB_manager”“sys_engineer”“research”.networks_admin“第一行数据是“5,gourav,59.7,72.6,73.87,59.14,43.14,50.74”这些分别是现在的值。我在 $row['Data_analytics'] 意味着我现在可以访问值 72.6 我想找出存储它的列的名称就像名称是“Data_analytics”。我希望这个值返回我们如何做

<?php
$value = 72.6; // the value you have access to
// Connect to the database
$db = new mysqli("localhost", "root", "", "hackathon");
// Prepare the query
$query = "SELECT COLUMN_NAME FROM information_schema.columns 
WHERE table_name = 'specialization' AND table_schema = 'hackathon' 
AND (column_name LIKE 'soft_dev' OR column_name LIKE 'Data_analytics' OR column_name LIKE 'DB_manager' OR column_name LIKE 'sys_engineer' OR column_name LIKE 'research' OR column_name LIKE 'networks_admin') 
AND EXISTS (SELECT * FROM specialization WHERE Data_analytics = ?)";
$stmt = $db->prepare($query);
$stmt->bind_param("d", $value);
$stmt->execute();
// Retrieve the result
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// Get the column name
$column_name = $row['COLUMN_NAME'];
echo "The value " . $value . " is stored in the column " . $column_name;
$stmt->close();
$db->close();
?>

Its giving error saying trying to access null variable or null value when i print column name它给出错误说当我打印列名时尝试访问 null 变量或 null 值

You're not checking if the result set is empty, or even if it has multiple rows.您没有检查结果集是否为空,或者即使它有多行。

Use this pattern in general...一般使用这种模式......

while($row = $result->fetch_assoc())
{
    $column_name = $row['COLUMN_NAME'];
    echo "The value " . $value . " is stored in the column " . $column_name;
}

Or...或者...

if ($result->num_rows === 0) {
    echo 'No results';
} else {
    while ($row = $result->fetch_object()) {
        $column_name = $row['COLUMN_NAME'];
        echo "The value " . $value . " is stored in the column " . $column_name;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM