6 Replies - 524 Views - Last Post: 23 March 2011 - 05:46 AM Rate Topic: -----

#1 Slice  Icon User is offline

  • D.I.C Addict


Reputation: 196
  • View blog
  • Posts: 594
  • Joined: 24-November 08

Creating links from returned database result

Posted 20 March 2011 - 01:45 PM

OK, I havn't got any of this up and running at the moment so my code is hypothetical.

Say I wanted to run a query that returns all the usernames from a table users, but then I want to generate a link to the users profile from their name.

At the moment I imagine it will be something like:

<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
	{
		die('Could not connect: ' . mysql_error() );
	}
	
mysql_select_db("database", $con);

$result = mysql_query("SELECT username FROM users ORDER BY username DESC ");

while($row = mysql_fetch_array($result))
	{
        echo "<a href='";
        echo $row['username'];
        echo "'>";
        echo $row['username'];
        echo "<br/>";
	}
?>



But the only problem with that is I don't want to have to create a page for every user. I would rather have a link they click, which then stores a variable like "session->clickedlink" and then use post to retrieve all their information on the next page.

Not sure if that makes any sense, but would love some advice.

Is This A Good Question/Topic? 0
  • +

Replies To: Creating links from returned database result

#2 Slice  Icon User is offline

  • D.I.C Addict


Reputation: 196
  • View blog
  • Posts: 594
  • Joined: 24-November 08

Re: Creating links from returned database result

Posted 20 March 2011 - 05:59 PM

Sorry for the double post but I figured it out once I got the database set up. Since the information I was passing over wasn't delicate I just used a GET method and put all the information into the URL.

Just incase anyone stumbles onto this in the future and wonders how I did it, it looks something like this:

In the page where I have a list of all my users I put:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
	{
		die('Could not connect: ' . mysql_error() );
	}
	
mysql_select_db("database_name", $con);

$result = mysql_query("SELECT * FROM users ORDER BY username ASC ");

while($row = mysql_fetch_array($result))
	{
	echo "<a href='userpage.php?user=";
	echo $row['username'];
	echo "'>";
	echo $row['username'];
	echo "</a>";
	echo "<br/>";
	}

?>



Then on userpage.php I put:
<?php
$username=$_GET['user'];
$con = mysql_connect("localhost","username","password");
if (!$con)
	{
		die('Could not connect: ' . mysql_error() );
	}
	
mysql_select_db("database_name", $con);

$result = mysql_query("SELECT * FROM posts WHERE username='$username' ORDER BY postid DESC ");

while($row = mysql_fetch_array($result))
	{
	echo "<div class='post'>";
	echo "<h3>";
	echo $row['posttitle'];
	echo "<span class='datetime'>";
	echo $row['posttime'];
	echo "</span></h3>";	
	echo $row['postcontent'];
	include("php_files/postoptions.php");
	echo "</div>";
	}

?>



Which displays all the posts of the one user among other things to do with that user.

This probably isn't the only way (or best way) to do it but it's working for me so far :).

If anyone else has an other way of doing it then let me know! :D
Was This Post Helpful? 0
  • +
  • -

#3 calebjonasson  Icon User is offline

  • $bert = new DragonUnicorn(); $bert->rawr();
  • member icon

Reputation: 198
  • View blog
  • Posts: 973
  • Joined: 28-February 09

Re: Creating links from returned database result

Posted 20 March 2011 - 06:31 PM

Great to see that you have figured it out on your own but there are a few things that you should take a note of when handling information with the database.

First things first is you need to make sure that you handle each possibility appropriately. Say someone from an external site links to a profile that isn't there. If this happens they are going to hit a fatal error and it won't look good on your websites behalf. You should user the function mysql_num_rows to make sure that there is information being returned.

$result = mysql_query("SELECT * FROM posts WHERE username='$username' ORDER BY postid DESC ");
if(mysql_num_rows($result) == 1)
{
    while($row = mysql_fetch_array($result))
	{
	echo "<div class='post'>";
	echo "<h3>";
	echo $row['posttitle'];
	echo "<span class='datetime'>";
	echo $row['posttime'];
	echo "</span></h3>";	
	echo $row['postcontent'];
	include("php_files/postoptions.php");
	echo "</div>";
    }
}else{
    //they modified the url or the user doesn't exist in the system anymore.
    echo '<h2>User Doesn't Exist</h2>
    <p>It appears that the user was removed or the the url is broken.</p>';
}




The next thing that you should look out for is this deadly little line of code:
$username=$_GET['user'];


The string for the username needs to be cleaned and when I say needs to be cleaned I mean that it NEEDS to be cleaned.
A quick way to clean a string to make sure that there is no mysql injection would be to use the built in mysql_real_escape_String or a pregreplace.

This is a much safer alternative.
//if the number is not a,b,c,d... or A,B,C,D... strip it from the username.
$username = preg_replace("/[^a-zA-Z]/","",$_GET['user']);



The final thing that I would like to bring to your attention is the importance of prepared statements and the overall use of something called mysqli. It will stop a lot of mysql injection dead in its tracks. Prepared statements is a great place to start.
http://ca3.php.net/m...qli.prepare.php

Good luck with your php adventures!
Was This Post Helpful? 2
  • +
  • -

#4 Slice  Icon User is offline

  • D.I.C Addict


Reputation: 196
  • View blog
  • Posts: 594
  • Joined: 24-November 08

Re: Creating links from returned database result

Posted 20 March 2011 - 09:11 PM

Cheers for the great advice.

I'm still learning a lot of the basics so getting all the security areas up to a good standard is a great way to stop me from falling into bad habits.

Can't believe I didn't think to put in that else statement for the results, it seems so obvious now someone has pointed it out :).

Thanks for all the help, I'm going to read up on the prepared statements now.

This post has been edited by Slice: 20 March 2011 - 09:45 PM

Was This Post Helpful? 0
  • +
  • -

#5 chtombleson  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 22
  • Joined: 28-September 09

Re: Creating links from returned database result

Posted 22 March 2011 - 02:06 PM

You really need to escape and data that can be changed in the url or any data that you have no control over.

One possible way of not using so many echo calls
in your while loop you could create a function
like this one:

function buildLink($page, $query/*array*/)
{
   $str = "<a href='".$page."?";
   foreach($query as $key => $value)
   {
      $str .= $key."=".$value."&";
   }
   
   $str = trim($str, '&');
   $str .= "'>".$query['user']."</a>";
   return $str;
}



You would call this function like so using your existing code:
$con = mysql_connect("localhost","username","password");
if (!$con)
{
	die('Could not connect: ' . mysql_error() );
}
	
mysql_select_db("database_name", $con);

$result = mysql_query("SELECT * FROM users ORDER BY username ASC ");

while($row = mysql_fetch_array($result))
{
	$query = array("user" => $row['username']);
        echo buildLink("userpage.php", $query)."<br />";
}



Hopefully that will help you or give you some ideas.
Was This Post Helpful? 1
  • +
  • -

#6 Slice  Icon User is offline

  • D.I.C Addict


Reputation: 196
  • View blog
  • Posts: 594
  • Joined: 24-November 08

Re: Creating links from returned database result

Posted 22 March 2011 - 04:50 PM

So can I put this function in an external session page and just include it on the page I want to call the functions? Will definitely take your advice. Thanks for the help!
Was This Post Helpful? 0
  • +
  • -

#7 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 934
  • View blog
  • Posts: 2,329
  • Joined: 15-February 11

Re: Creating links from returned database result

Posted 23 March 2011 - 05:46 AM

Commenting on the fact that you said you don't want to have to create a page for each user...you actually don't have to. That's the beauty of PHP.

Check out the functions ob_start() and ob_end_flush().

You'd simply have to set up a template since each profile will have the same design but just different content (About Me, Country, Name,..etc). You would then have to include the HTML file or whichever extension you plan on using and replace space-holders with the proper information pertaining to the user's profile.

Sample Code.
Template.html
<html>
	<head>
		<title>{USER}'s Profile</title>
	<body>
		<p>{ABOUTME}</p>
	</body>
</html>



userprofile.php
<?php
function parseProfile($str) {
	//read database and get user info here
	$str = str_replace("{USER}", $user, $str);
	$str = str_replace("{ABOUTME}", $aboutme, $str);
	return $str;
}

ob_start("parseProfile");
require("template.html");
ob_end_flush();
?>

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1