Retrieving from a database

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
mayh3m
Forum Newbie
Posts: 3
Joined: Wed Mar 12, 2003 5:44 am
Location: South Africa

Retrieving from a database

Post by mayh3m »

Please help. I am trying to retrieve and display certain fields from a row in a MySQL databse using php.
I do it the following way:

Code: Select all

$query ="select emp_id, surname, name, tel_no from user_data where user_data.emp_id = '$emp_id1'";
	}
//User information
	$result = mysql_query($query) or 
		die (mysql_error());
		
if (mysql_num_rows($result) == 0)
{
	include ("../helpdesk/newuser/form.php");
} else

{
$number_cols = mysql_num_fields($result);

echo "<table border = 1>\n";
echo "<tr align=center>\n";

for ($i=0; $i<$number_cols; $i++)
{
	echo "<th>" . mysql_field_name($result, $i). "</th>\n";
}
echo "</tr>\n";

while ($row = mysql_fetch_row($result))
{
	echo "<tr align=left>\n";
	for ($i=0; $i<$number_cols; $i++)
	{
		echo "<td>";
		if (!isset($row[$i]))
			{include("../newuser/form.php");}
		else
			{echo $row[$i];}
	}
	echo "</tr>\n";
}

echo "</table>";
This works, but what I need to do is be able to put each field retrieved into a table with headings I have created. Is there no way that I can chage each field retrieved into a variable so that I can echo them where I want them?

I'm new to programming. Please help!!

Regards
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post by daven »

Check out mysql_fetch_assoc and mysql_fetch_object. They permit you to get query results associatively (ex: $row['MyColumn1'] and $row->MyColumn1, respectively).

To toss your results into variables, just create a relevant variable and set it to the result.

$myVar0 = $row[0]; // or $row['MyColumn'] or $row->MyColumn0 depending upon the way you access your results
$myVar1 = $row[1];
etc.

If you do not want to have a whole bunch of variable names, use an array
$myArray=array();
$myArray[0]=$row[0];
$myArray[1]=$row[1];
etc.

Then you can just echo the values where ever you want to.

Also look into mysql_data_seek http://www.php.net/manual/en/function.m ... a-seek.php
Post Reply