Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [quote="Celauran"]First of all, stop using mysql_ functions. They've been worst practice for years, are deprecated, and will be removed from the language. That said, the easiest way to prevent SQL injection is to use prepared statements.[/quote]
- Here's a class I like to use:
- [php]class DB extends PDO
- {
- /**
- * Parameterized Query
- *
- * @param string $statement
- * @param array $params
- * @param const $fetch_style
- * @return mixed -- array if SELECT
- */
- public function dbQuery($statement, $params = [], $fetch_style = PDO::FETCH_ASSOC)
- {
- if (empty($params)) {
- $stmt = $this->query($statement);
- if ($stmt !== false) {
- return $stmt->fetchAll($fetch_style);
- }
- return false;
- }
- $stmt = $this->prepare($statement);
- $exec = $stmt->execute($params);
- if ($exec) {
- return $stmt->fetchAll($fetch_style);
- }
- return false;
- }
- /**
- * Fetch a single result -- useful for SELECT COUNT() queries
- *
- * @param string $statement
- * @param array $params
- * @return mixed
- */
- public function single($statement, $params = [])
- {
- $stmt = $this->prepare($statement);
- $exec = $stmt->execute($params);
- if ($exec) {
- return $stmt->fetchColumn(0);
- }
- return false;
- }
- }[/php]
- Example time! Because everybody loves examples.
- Old code:
- [php]<?php
- mysql_connect("localhost", "root", "hackme");
- mysql_select_db("mission_critical");
- $sql = mysql_query("SELECT * FROM table WHERE id = '" . $_GET['id'] ."'");
- $data = mysql_fetch_assoc($sql);[/php]
- New code:
- [php]<?php
- include "keep_this_out_of_document_root_please/DB.php";
- $mySQL = new DB("mysql:host=localhost;dbname=mission_critical", "root", "hackme");
- $data = $mySQL->dbQuery("SELECT * FROM table WHERE id = ?", array( $_GET['id'] ));[/php]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement