Daanvn
Daanvn

Reputation: 1266

Get column names from MySQL Table

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.

Upvotes: 0

Views: 1263

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

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]

Upvotes: 4

JoDev
JoDev

Reputation: 6873

You can call columns by there index like :

$Voornaam  = $objResult[0]; //if the first column of the table is "voornaam"

But you have to know the column order...

The mysql_fetch_array function can have a second param like : MYSQL_ASSOC, MYSQL_NUM, et MYSQL_BOTH default is MYSQL_BOTH, and it return an array with for each column, a key with the column name , and another one with column index.

Upvotes: 1

Related Questions