Is there an easy way to display records in a database?
I have the query set up but I don't know how to output the result to the user..
Here is my php:

<?php
session_start();  
 
if (!isset($_SESSION['memberusername'])){  
	header("location:contractorlogin.php");  
	exit();  
}
 
$user = $_SESSION['memberusername'];
$sql = "SELECT Username FROM contractors WHERE Username LIKE'" . $user . "'";
#result = mysql_query($sql);
?>

All I want to do is output the Username field to the person who is logged in as a test.
Is everything set up correctly and how would I output the result to the user on the screen?

Recommended Answers

All 3 Replies

Try this:

session_start();  
 
if (!isset($_SESSION['memberusername'])){  
	header("location:contractorlogin.php");  
	exit();  
}
 
$user = $_SESSION['memberusername'];
$sql = "SELECT Username FROM contractors WHERE Username LIKE'" . $user . "'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);

echo $row['username'];

if there are multiple rows being returned try this:

session_start();  
 
if (!isset($_SESSION['memberusername'])){  
	header("location:contractorlogin.php");  
	exit();  
}
 
$user = $_SESSION['memberusername'];
$sql = "SELECT Username FROM contractors WHERE Username LIKE'" . $user . "'";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)){
     echo $row['username'];
}

Also if Username is unique don't use like use =

are you being redirected to contractorlogin.php at least? Assuming you are, then in contractorlogin.php you MUST be storing the username in a session.

As for the code you posted, you may want to use an EQUAL instead of a LIKE in your query:

<?php
session_start();  
 
if (!isset($_SESSION['memberusername'])){  
	header("Location: contractorlogin.php");  
	exit();  
}

mysql_connect('localhost','username','password') or die( mysql_error() );
mysql_select_db('dbname') or die( mysql_error() );
$user = mysql_real_escape_string($_SESSION['memberusername']);
$sql = "SELECT * FROM contractors WHERE Username='" . $user . "'";
$result = mysql_query($sql) or die( 'Unable to execute<br>'.$sql.'<br>'.mysql_error());
if( !mysql_num_rows($result) )
{
	echo '<p>No Records found!</p>';
}
else
{
	$row=mysql_fetch_assoc($result);
	echo '<table><tr><th>' .implode('</th><th>', array_keys($row) ).'</th></tr>';
	do
	{
		echo '<tr><td>'.implode('</td><td>',$row).'</td></tr>';
	}while($row=mysql_fetch_assoc($result));
	echo '</table>';
}

?>

Thanks KPheasey, thanks hielo! It worked :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.