开发者

Use PHP to link to user profile

I want my php query to display the user name with a link to the user profile开发者_运维技巧.

<?php

$get_items = "SELECT * FROM items WHERE category='test'";
$result = mysql_query($get_items);

while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
    $creator = $item['created_by'];
     echo "<b>Seller: </b>"."<a href='userprof.php?id=$creator'>$creator</a>";  
    }
?>

Clicking on this link takes it to a user profile page that I created. But I want "userprof.php?id=$creator" to know which user to display the account information. Is this the best way to do this? How can I read the url and display the correct information?


<?php
$userId = $_GET['id'];
$sql = "SELECT * FROM user WHERE id = " . intval($userId);
$result = mysql_query($sql);
...


You are sending a GET variable.

$id = $_GET['id']; // Contains whatever was in $creator;


use $_GET for getting the variable from the URL. like in your code you want to access the user profile then get the user id from url like

http://localhost/test/user_profile.php?uid=2

here in the url uid is 2 thet is your userid. you can get this id by using the code

$user_id = $_GET['uid'];

use this variable in your query.


OMG!! HORRIBLE PHP ABOUNDS! IT HURTS MY EYES!!

These people, none of them did both of the correct things:

  1. ALWAYS FILTER USER INPUT!!
  2. NEVER TRUST PHP ESCAPE FUNCTIONS, ESP NOT intval() and addslashes()!!
  3. EVEN mysql_real_escape_string() HAS VULNERABILITIES AND SHOULD NEVER BE USED.
  4. You should used prepared statements for everything in 2010.

Here it is the proper way:

<?php
if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
    trigger_error('Invalid User ID. It must be an integer (number).', PHP_USER_ERROR);
    exit;
}

$userId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT * FROM user WHERE id = ?";

$pdo = new PDO('mysql:host=localhost;db=mydb', $dbUsername, $dbPassWord);
$statement = $pdo->prepare($sql);
$statement->execute(array($userId));

$result = $statement->fetch(PDO::FETCH_ASSOC);

That is 100% secure. I hope people neither vote me down nor tone down my answer. Bad code is so systemic, we just have to shout from the rooftops until the new guys start learning it correctly, otherwise PHP as a professional language is seriously harmed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜