Script 13.6 Prevent SQL Injection Attacks

Use prepare statements that bind values to the query variables.

Output
Post a message

Source
<?php # Script 13.6 - post_message as user_id 3 and forum_id 1 to messages table in forum database
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		
		// Assign the values to variables:
		$forum_id = (int) $_POST['forum_id']; //set statically as a constant for now
		$parent_id = (int) $_POST['parent_id']; //set statically at no parent for now
		$user_id = 3; // The user_id value would normally come from the session.
		$subject = strip_tags($_POST['subject']);
		$body = strip_tags($_POST['body']);

		if($subject!='' && $body!='' ) {

			// Connect to the database:
			require(CONNECT);
			
			// Make the query:
			$q = 'INSERT INTO messages (forum_id, parent_id, user_id, subject, body, date_entered) VALUES (?, ?, ?, ?, ?, NOW())';

			// Prepare the statement:
			$stmt = mysqli_prepare($link, $q);

			// Bind the variables:
			mysqli_stmt_bind_param($stmt, 'iiiss', $forum_id, $parent_id, $user_id, $subject, $body);
			
			// Execute the query:
			mysqli_stmt_execute($stmt);

			// Print a message based upon the result:
			if (mysqli_stmt_affected_rows($stmt) == 1) {
				echo '<div class="message">Your message has been posted.</div>';
			} else {
				echo '<p class="error">Your message could not be posted.<br/>';
				echo mysqli_stmt_error($stmt) . '</p>';
			}
			
			// Close the statement:
			mysqli_stmt_close($stmt);

			// Close the connection:
			require(DISCONNECT);

		} else {
			echo '<div class="message"><p class="error">We could not process your message. Please double check your submission.</p></div>';
		}
}
?>
<form action="" method="post">
	<fieldset>
		<legend>Post a message</legend>
		<p>
			<label for="s">Subject</label>
			<input id="s" name="subject" type="text" size="30" maxlength="100" />
		</p>
		<p>
			<label for="b">Body</label> 
			<textarea id="b" name="body" rows="3" cols="40"></textarea>
		</p>
		<p>
			<input type="submit" name="submit" value="Submit" />
		</p>
	</fieldset>
	<input type="hidden" name="forum_id" value="1" />
	<input type="hidden" name="parent_id" value="0" />
</form>