I have a table , Here is my table image
my Query Select * from categories
My question is how i can fetch or echo primary index of my table after executing above query.
<?php echo "Primary field is =".$rec['primary_field_name']; ?>
And the output from same query is as
Primary field is = cat_id
Thanks in advance
I think this should do what you want:
<?php
$conn = mysql_connect( $dbhost, $dbuser, $dbpass );
mysql_select_db( $dbname );
$sql='select * from `categories`;';
$res=mysql_query( $sql, $conn );
if( $res ){
while( $rs = mysql_fetch_object( $res ) ){
echo $rs->cat_id . ' ' . $rs->cat_desc .' '. $rs->cat_status.' '.$rs->cat_image.'<br />';
}
}
mysql_free_result( $res );
mysql_close( $conn );
?>
As I misunderstood your question the following query MIGHT be of interest to you.
select `column_name`
from `information_schema`.`columns`
where (`table_schema` = database() )
and (`table_name` = 'categories')
and (`column_key` = 'pri');
Though I don't know of a way to get the name of the primary key within a standard sql query.
You could try the following as an "All in One" solution:
select *,
( select group_concat(`column_name`)
from `information_schema`.`columns`
where (`table_schema` = database() )
and (`table_name` = 'categories')
and (`column_key` = 'pri') ) as 'PrimaryKey'
from `categories`;
I used group_concat
in the sub-query because it is highly possible to have a composite Primary Key
- without group_concat
you are likely to get an error.
use mysql_fetch_assoc
for get column or value
$sql='select * from `categories`';
$query=mysql_query( $sql, $conn );
while($row = mysql_fetch_assoc($query))
{
foreach($row as $key => $value)
{
echo $key;//For print column name
echo $value;//For print value
}
}