try {
# MS SQL Server и Sybase через PDO_DBLIB
$DBH = new PDO("mssql:host=$host;dbname=$dbname", $user, $pass);
$DBH = new PDO("sybase:host=$host;dbname=$dbname", $user, $pass);
# MySQL через PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
# SQLite
$DBH = new PDO("sqlite:my/database/path/database.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Создаем константы
define("HOST", "localhost");
define("DBNAME", "сюда вносим имя БД");
define("DBUSER", "сюда вносим имя пользователя от БД");
define("DBPASSWORD", "сюда вносим пароль пользователя от БД");
// Подключаемся к базе данных через PDO
try {
$mysql = new PDO('mysql:host=' . HOST . ';dbname=' . DBNAME, DBUSER, DBPASSWORD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
} catch (PDOException $e) {
print "Возникла ошибка соединения!: " . $e->getMessage() . "<br/>";
die();
}
$stmt = $db->query("SELECT * FROM categories");
while ($row = $stmt->fetch())
{
echo '<pre>';
print_r($row);
}
$sql = "SELECT name FROM categories WHERE id = ?";
$sql = "SELECT name FROM categories WHERE name = :name";
$stmt = $pdo->prepare("SELECT `name` FROM categories WHERE `id` = ?");
$stmt->execute([$id]);
$stmt = $pdo->prepare("SELECT `name` FROM categories WHERE `name` = :name");
$stmt->execute(['name' => $name]);
$id = 1;
$stmt = $db->prepare("SELECT * FROM categories WHERE `id` = ?");
$stmt->execute([$id]);
while ($row = $stmt->fetch(PDO::FETCH_LAZY)) {
echo 'Category name: '.$row->name;
}
$id = 1;
$stmt = $db->prepare("SELECT `name` FROM categories WHERE `id` = ?");
$stmt->execute([$id]);
$name = $stmt->fetchColumn();
echo 'Category name: '.$name;
$data = $db->query("SELECT * FROM categories")->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $k => $v){
echo 'Category name: '.$v['name'].'<br>';
}
// Добавление записей
$name = 'Новая категория';
$query = "INSERT INTO `categories` (`name`) VALUES (:name)";
$params = [
':name' => $name
];
$stmt = $pdo->prepare($query);
$stmt->execute($params);
// Изменение записей
$id = 1;
$name = 'Изменённая запись';
$query = "UPDATE `categories` SET `name` = :name WHERE `id` = :id";
$params = [
':id' => $id,
':name' => $name
];
$stmt = $pdo->prepare($query);
$stmt->execute($params);
// Удаление записей
$id = 1;
$query = "DELETE FROM `categories` WHERE `id` = ?";
$params = [$id];
$stmt = $pdo->prepare($query);
$stmt->execute($params);