dongzhunnai0140 2013-03-27 09:33
浏览 227
已采纳

从MySQL表中获取列名

I have a Table in my MySQL Database which looks like this:

Table: VAAW
Columns:
ID  int(11) PK AI
Voornaam    varchar(45) 
Achternaam  varchar(45) 
Adres   varchar(45) 
Woonplaats  varchar(45) 

I am using this table in the following php code:

$strSQL     = "SELECT * FROM NAW.VAAW";
$objQuery   = mysql_query($strSQL);
while($objResult = mysql_fetch_array($objQuery))
{
$Voornaam   = $objResult["Voornaam"];
$Achternaam = $objResult["Achternaam"];
$Adres      = $objResult["Adres"];
$Woonplaats = $objResult["Woonplaats"];

$string     = $_POST['naam'];

$vaaw       = array("(voornaam)", "(achternaam)", "(woonplaats)", "(adres)");
$vervang    = array("$Voornaam", "$Achternaam", "$Woonplaats","$Adres");

echo str_replace($vaaw, $vervang, $string);
echo '<br>';
}

What I use this for:
I have a form where I can add some tekst in a textbox and when I submit it will echo the result. For example if the Column 'Voornaam' contains the row 'Jack' and when I type in the textbox in my form: Hey (voornaam), it should output: Hey Jack.

I don't really know how to ask this question so I will give an example. If I for some reason want to change a column name in my database I will have to change this source code according to the column name changes.

The example:

If I change the column name 'voornaam' to 'Vnaam' I will also have to change

$Voornaam  = $objResult["Voornaam"];

to

$Voornaam  = $objResult["Vnaam"];

So my question is if there is any way to have some sort of standard for like the 1st column, 2nd colum etc. so I can add that in the code and will not have to change the source code every time I change a column name. Maybe there is a query function to do this? I know this question is kinda vague but I hope you understand, if not feel free to ask in the comments. Any help would be great since I have no clue how to do this!

NOTE: I know I should't be using mysql_* and I will switch to PDO later. So please don't mention that again.

  • 写回答

2条回答 默认 最新

  • duandaishi9268 2013-03-27 09:36
    关注

    if you use print_r($objResult) you will see that you have results with both numerical and strings keys.

    So, instead of $Voornaam = $objResult["Vnaam"] you can use $Voornaam = $objResult[0]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64