简体   繁体   English

基于列名称的PHP / MySQL匹配单元格

[英]PHP/MySQL matching cell based on column name

I have a database that looks like this. 我有一个看起来像这样的数据库。

 x  2  3  4  5
 4  8 12 16 20
 5 10 15 20 25
 6 12 18 24 30
 7 14 21 28 35

When an end user plugs in one value I want to match the x variable to the values in the x column and the other variable to the numerical column names. 当最终用户插入一个值时,我想将x变量与x列中的值匹配,将另一个变量与数字列名匹配。

So how would I go about writing an SQL query that does this? 那么我该如何编写一个执行此操作的SQL查询呢?

SELECT * FROM times_tables WHERE x=4 and COLUMN_NAME=4;

Thanks :) 谢谢 :)

SELECT
    `4`
FROM
    (SELECT
        4 as `x`, 8 as `2`, 12 as `3`, 16 as `4`, 20 as `5`
    UNION ALL
        SELECT 5, 10, 15, 20, 25
    UNION ALL
        SELECT 6, 12, 18, 24, 30
    UNION ALL
        SELECT 7, 14, 21, 28, 35) `times_tables`
WHERE
    `x` = 4

Output: 输出:

4
---
16

So in your case query might be something like this: 因此,在您的情况下,查询可能是这样的:

SELECT `{$col}` FROM `times_tables` WHERE `x` = {$row};

UPD: UPD:

Might be done with pure SQL: 可以使用纯SQL完成:

SET @r = 4; -- row
SET @c = 5; -- col

SET @qry = CONCAT('SELECT `', @c ,'` FROM `times_tables` WHERE `x` = ', @r);

PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

PS: You may wrap SQL into a stored procedure for better protection. PS:您可以将SQL包装到存储过程中,以获得更好的保护。

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

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