I mentioned to Crown on IRC that his code was vulnerable. I told him to use 'mysql_real_escape_string', yet he was not sure what I meant (or truth), so here's Crown's code modified so it's not vulnerable:
CODE
Banjo You might want users to add a joke from your website so here is what you can do.
First create a file called jokeinput_.php
and on that page have this code
CODE
<html>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="jokeinsert.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td colspan="3"><strong>Add a Joke to Our Database</strong></td>
</tr>
<tr>
<tr>
<td>Title</td>
<td>:</td>
<td><input name="Title" type="text" id="Title"></td>
</tr>
<tr>
<td>Joke</td>
<td>:</td>
<td><input name="Joke" type="text" id="Joke"></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</html>
Second create a page called jokeinsert.php this page will add your joke into the database.
CODE
<?php
$host="localhost";
$username="yourusername";
$password="yourpassword";
$db_name="yourdatabase";
$tbl_name="yourtable";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$Title=mysql_real_escape_string($_POST['Title']);
$Joke=mysql_real_escape_string($_POST['Joke']);
// Insert data into mysql
$sql="INSERT INTO $tbl_name(id, title, joke)VALUES('$Title', '$Joke')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='jokeinsert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close();
?>
Might be worth noting that my code does leave you open to XSS vulnerabilities. This code isn't meant to be used in its entirety, it was to serve as an example.
But anywhere, here's the fix:
CODE
<?php
$link = @mysql_connect('localhost', 'myuser', 'mypassword');
if($link === false):?>
<h1 class="error">Could not establish database connection.</h1>
<?php
exit;
endif;
mysql_select_db('mydb', $link);
if(isset($_GET['id']) && ctype_digit($_GET['id'])):
$result = mysql_query('SELECT title, joke FROM jokes WHERE id = ' . $_GET['id']);
if(mysql_num_rows($result) == 1):
$row = mysql_fetch_assoc($result);
?>
<h1 class="title"><?php echo htmlspecialchars($row['title'], ENT_QUOTES); ?></h1>
<p class="joke"><?php echo htmlspecialchars($row['joke'], ENT_QUOTES); ?></p>
<?php
else:
?>
<h1 class="error">Couldn't find joke associated with the supplied ID.</h1>
<?php
endif;
else:?>
<h1 class="error">The ID supplied is invalid.</h1>
<?php
endif;
?>