Я знаю, что это было отмечено как ответное, но я думаю, что важно показать пример параметра связывания. Это немного сложнее решения, заметьте, но он довольно организован, поэтому его довольно легко рассеять. Также это всего лишь пример, есть много способов сделать этот скрипт с параметрами привязки. Параметры связывания в функциях является наиболее важной частью действительно:
/classes/class.DatabaseConfig.php
<?php
// Database configuration meant for connection
class DatabaseConfig
{
private static $singleton;
public function __construct()
{
if(empty(self::$singleton))
self::$singleton = $this;
return self::$singleton;
}
public function connectMySQLi($host = "localhost", $username = "username", $password = "password", $database = "database")
{
// Create connection
try {
$mysqli = new mysqli($host, $username, $password, $database);
return $mysqli;
} catch (mysqli_sql_exception $e) {
// Print real error if admin, or write to
// secured log file
// throw $e;
die("Connection has failed.");
}
}
}
/classes/class.Db.php
<?php
// Singleton-based class to re-use instantiated resources
class Db
{
private static $singleton;
// Default connection
public static function mysqli()
{
if(empty(self::$singleton)) {
$con = new DatabaseConfig();
self::$singleton = $con->connectMySQLi();
}
return self::$singleton;
}
}
/functions/function.save.php
<?php
// I have chosen a singleton, but you can pass your db connection as a
// second argument like save($array,$mysqli)
function save($settings = false)
{
// Because the the class allows for a static variable, you can
// connect straight in the class without using globals
$mysqli = Db::mysqli();
// Use bind_param/prepare/execute for safe queries
$stmt = $mysqli->prepare("INSERT INTO `tb_blogs` (`title`, `author` , `content`) values (?,?,?)");
// You can do checks on these variables to see that they are filled out, I have not though
$stmt->bind_param("sss",$settings['title'],$settings['author'],$settings['content']);
$stmt->execute();
}
/functions/function.update.php
<?php
function update($settings = false)
{
$mysqli = Db::mysqli();
$stmt = $mysqli->prepare("UPDATE `tb_blogs` SET `title` = ?, `author` = ?, `content` = ? WHERE id = ?");
$stmt->bind_param("sssi",$settings['title'],$settings['author'],$settings['content'],$settings['blog_id']);
$stmt->execute();
}
index.php
<?php
// Look into using spl_autoload_register() here
include_once("classes/class.DatabaseConfig.php");
include_once("classes/class.Db.php");
// You can make a similar autoloader-type function as well instead of
/// manually writing a crap-load of includes
include_once("functions/function.save.php");
include_once("functions/function.update.php");
// Do single wrapper for submit
if(isset($_POST['submit'])) {
// Check for create
if($_POST["action_type"] =='create')
save($_POST);
// Check for update
elseif($_POST["action_type"] =='update')
update($_POST);
}
Вы должны пройти 'соединение $ mysqli' в ваши функции наряду с переменными. – Rasclatt
Собираетесь ли вы использовать эти функции еще где, можете просто поместить две строки в ваши условные выражения. Также вы открыты для SQL-инъекций. Http://stackoverflow.com/questions/60174/how-can-i-prevent -sql-injection-in-php? rq = 1 – chris85