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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?