billiondevil wrote:i have never used printf or sprintf before so i really have no idea what to do.
Take a look at this:
<?php
function foo($a, $b, $c) {
echo $a . $b . $c;
}
foo('Test' 'this' 'out');
What is wrong with the call of foo()? That is the same mistake that I made with printf. As you can see, it has nothing to do with printf itself, other than printf taking more than one argument.
You should learn how to use sprintf and related functions, but even if you choose not to use them, the part to get right is the use of htmlentities() and the appropriate escaping of input/output in general.
billiondevil wrote:could somobody show m,e how to fix and tell me what was wrong with it?
This is a fixed version:
<?php
function friends() {
$sql="SELECT id FROM members WHERE username='".$_SESSION['myusername']."'";
$result=mysql_query($sql);
$userinfo=mysql_fetch_assoc($result);
echo "<table class='box4' width='644'><tr><td>Friends</td></tr></table>";
echo "<table class='box3' width='644'><tr><td>";
echo "<center><table class='bank'><tr><td width=250>Friends</td><td width=100>Online?</td><td width=100>Mail?</td><tr>";
$sql = sprintf("SELECT friends.friendid, friends.friendname, members.`timestamp`
FROM friends, members
WHERE friends.friendid=members.id AND friends.userid='%d'", $userinfo['id']);
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo '<tr><td colspan="3" style="text-align: center;">You have no friends!</td><tr>';
} else {
while ($row = mysql_fetch_assoc($result)) {
$online_text = ($row['timestamp'] > (time() - 300))
? '<span style="color: green;">Online</span>'
: '<span style="color: red;">Offline</span>';
printf('<tr><td><a href="game.php?do=userinfo&id=%1$d">%2$s</a></td><td>%3$s</td>'
. '<td><a href="game.php?do=writemail&to=%2$s">Send Mail</a></td></tr>',
$row['friendid'],
htmlentities($row['friendname']),
htmlentities($online_text));
}
}
echo "</td></tr></table></center>";
echo "</td></tr></table>";
}
php?>
Spot the difference :p
But I only corrected the mistake propagated from my example. I did not correct this:
$sql="SELECT id FROM members WHERE username='".$_SESSION['myusername']."'";
$result=mysql_query($sql);
To understand what is wrong with the above, read about the exploits of a mom. To fix this, you can use:
$sql="SELECT id FROM members WHERE username='".mysql_real_escape_string($_SESSION['myusername'])."'";
$result=mysql_query($sql);
or:
$sql = sprintf("SELECT id FROM members WHERE username='%s'", mysql_real_escape_string($_SESSION['myusername']));
$result=mysql_query($sql);
I prefer the latter because I find it easier to read, and it is arguably more directly convertible to a prepared statement's SQL statement, should you choose to use the PDO extension, or MySQLi extension, etc, later.