Created
March 3, 2018 16:50
-
-
Save platinize/295b1c736e532389c379231cf53a6af7 to your computer and use it in GitHub Desktop.
Php15Tasks.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include 'Connect.php'; | |
if ($db->countRecords($table) != 0): | |
?> | |
<p><a title="Добавить автомобиль" href="index.php">Добавить автомобиль</a></p> | |
<table border="1" cellpadding="7" cellspacing="0"> | |
<tr> | |
<?php foreach ($db->getColumnName($table) as $key => $colName): ?> | |
<td><?=$colName?></td> | |
<?php endforeach; ?> | |
<td>удаление</td> | |
</tr> | |
<?php foreach ($db->getAll($table) as $key => $car): ?> | |
<tr> | |
<?php foreach ($car as $key => $columnName): ?> | |
<td><?=$columnName?></td> | |
<?php endforeach; ?> | |
<td><a href="delete.php?id=<?=$car['id']?>&table=<?=$table?>" >удалить</a></td> | |
</tr> | |
<?php endforeach; ?> | |
</table> | |
<?php else: ?> | |
<p>У вас нет добавленных машин</p> | |
<?php endif; ?> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ini_set('display_errors', '1'); | |
error_reporting(E_ALL); | |
include 'WorkWithDatabase.php'; | |
$db=new WorkWithDatabase('root','','localhost','utf8','dz15'); | |
$dataBaseConnectionsWithParams=$db->connectWithParams('localhost','dz15','root',''); | |
$table = 'cars'; | |
?> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include 'Connect.php'; | |
$db->delete($_GET['table'],$_GET['id']); | |
echo '<meta http-equiv="refresh" content="0; url=cars.php">'; | |
?> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
<meta charset="utf-8" /> | |
<style type="text/css"> | |
span.error{color: red;} | |
input.error, select.error{background: #f7719e;} | |
</style> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> | |
</head> | |
<body> | |
<?php | |
include 'Connect.php'; | |
ini_set('display_errors', '1'); | |
error_reporting(E_ALL); | |
// Создайте html форму со следующими полями | |
// 1) Модель машины* (текстовое поле) | |
// 2) Максимальная скорость (текстовое поле) | |
// 3) Год выпуска (текстовое) | |
// 4) Страна выпуска* (выпадающий список, его необходимо за- | |
// полнить 10 любыми странами) | |
// 5) Тип кузова*: седан, универсал, хэтчбек, кабриолет (радио- | |
// батон) | |
// 6) Кнопка «добавить» | |
// Поля отмеченные * являются обязательными для заполне- | |
// ния | |
// 2. При нажатии на кнопку «Добавить», аяксом данные уходят на | |
// сервер, где выполняется проверка на заполнение обязательных | |
// полей. Если какое-либо поле пустое – вывести возле данного | |
// поля соответствующее сообщение и подсветить поле розовым | |
// фоном | |
// 3. Если форма заполнена верно – записать данные в базу данных | |
// создать отдельную страницу cars.php, в которой вывести список | |
// добавленных машин из базы данных. Если ещё нет ни одной машины – вы- | |
// водим запись «У вас нет добавленных машин» | |
// Если в базе данных уже есть записи – выводим их в виде таблицы | |
$countryRelease = ['Выберите страну', 'Корея', 'Китай', 'Япония', 'Германия', 'Дания', 'Хорватия', 'Италия', 'Франция', 'Англия', 'Франция']; | |
$bodyType = ['седан', 'универсал', 'хэтчбек', 'кабриолет']; | |
?> | |
<form action="" method="POST" onsubmit="return false"> | |
<p id="model"><label><input type="text" name="model" />Модель машины*</label></p> | |
<p><label><input type="text" name="maxSpeed" />Максимальная скорость</label></p> | |
<p><label><input type="text" name="releaseYear" />Год выпуска</label></p> | |
<p id="country_p"><label><select name='country' id='country'> | |
<?php foreach ($countryRelease as $key => $value): ?> | |
<option <?=($key==0)? 'selected': '' ?> value='<?=$key;?>'><?=$value;?></option> | |
<?php endforeach; ?> | |
</select>Страна выпуска*</label></p> | |
<p id="bodyType">Тип кузова*<?php foreach ($bodyType as $key => $value): ?> | |
<label><input type="radio" name="bodyType" value="<?=$key+1;?>"><?=$value;?></label> | |
<?php endforeach; ?></p> | |
<input type="submit" name="add" id="addButton" value="Добавить"> | |
<p id="message"></p> | |
<a href="cars.php">Перейти к списку автомобилей</a> | |
</form> | |
<script type="text/javascript"> | |
$(function(){ | |
$('#addButton').click(function(){ | |
$( "span.error" ).remove(); | |
$('.error').removeClass('error'); | |
var model = $('input[name="model"]').val(); | |
var maxSpeed = $('input[name="maxSpeed"]').val(); | |
var releaseYear = $('input[name="releaseYear"]').val(); | |
var country = $('#country').val(); | |
var bodyType = $('input[name="bodyType"]:checked').val(); | |
$.ajax({ | |
url: 'server.php', | |
type: 'POST', | |
dataType: 'json', | |
data: ({ | |
model: model, maxSpeed: maxSpeed, releaseYear: releaseYear, country: country, bodyType: bodyType, add: 1 | |
}), | |
success:function(answer) { | |
if (typeof answer['model'] !== "undefined"){ | |
$('#model').append("<span class = 'error'>"+answer.message+"</span>"); | |
$('input[name="model"]').addClass('error'); | |
}; | |
if (typeof answer['country'] !== "undefined"){ | |
$('#country_p').append("<span class = 'error'>"+answer.message+"</span>"); | |
$('#country').addClass('error'); | |
}; | |
if (typeof answer['bodyType'] !== "undefined"){ | |
$('#bodyType').append("<span class = 'error'>"+answer.message+"</span>"); | |
$('input[name="bodyType"]').addClass('error'); | |
}; | |
if (typeof answer['ok'] !== "undefined") { | |
$('#message').html("<span style='color:green'>Записано</span>"); | |
}; | |
} | |
}) | |
}) | |
}) | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ini_set('display_errors', '1'); | |
error_reporting(E_ALL); | |
include 'Connect.php'; | |
// 2. При нажатии на кнопку «Добавить», аяксом данные уходят на | |
// сервер, где выполняется проверка на заполнение обязательных | |
// полей. Если какое-либо поле пустое – вывести возле данного | |
// поля соответствующее сообщение и подсветить поле розовым | |
// фоном | |
// 3. Если форма заполнена верно – записать данные в базу данных | |
// создать отдельную страницу cars.php, в которой вывести список | |
// добавленных машин из базы данных. Если ещё нет ни одной машины – вы- | |
// водим запись «У вас нет добавленных машин» | |
// Если в базе данных уже есть записи – выводим их в виде таблицы | |
if (isset($_POST['add'])) { | |
unset($_POST['add']); | |
$answer = ['message'=>'Обязательно к заплнению/выбору']; | |
if (!isset($_POST['model']) || $_POST['model'] == '') { | |
$answer['model'] = 1; | |
}; | |
if (!isset($_POST['country']) || $_POST['country'] == 0) { | |
$answer['country'] = 1; | |
}; | |
if (!isset($_POST['bodyType'])) { | |
$answer['bodyType'] = 1; | |
}; | |
if (count($answer) == 1) { | |
$answer['ok'] = 1; | |
$data = array_map('trim', $_POST); | |
$data = array_map('strip_tags', $data); | |
$db->addCar($table, $data); | |
}; | |
echo json_encode($answer); | |
} | |
?> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class WorkWithDatabase { | |
protected $user; | |
protected $pass; | |
protected $pdo; | |
protected $host; | |
protected $db; | |
protected $charset; | |
public function __construct($user,$pass,$host,$charset,$db) { | |
$this->user = $user; | |
$this->pass = $pass; | |
$this->host = $host; | |
$this->charset = $charset; | |
$this->db = $db; | |
$this->pdo = $this->connectWithParams($this->host,$this->db,$this->user,$this->pass); | |
} | |
public function connectWithParams($host,$db,$user,$pass){ | |
$params='mysql:host='.$host.';dbname='.$db; | |
$opt = array( | |
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, | |
PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC | |
); | |
return new PDO($params,$user,$pass,$opt); | |
} | |
public function getColumnName($tableName) { | |
$stm=$this->pdo->query('SELECT COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ="'.$tableName.'"'); | |
$cars = $stm->fetchAll(PDO::FETCH_COLUMN); | |
return $cars; | |
} | |
public function getAll($tableName) { | |
$stm=$this->pdo->query('SELECT * From '.$tableName); | |
$cars = $stm->fetchAll(); | |
return $cars; | |
} | |
public function delete($tableName, $id) { | |
$sql = 'DELETE FROM `'.$tableName.'` WHERE `id` = '.$id; | |
$stm =$this->pdo->prepare($sql); | |
$stm->execute(['id'=>$id]); | |
} | |
public function selectOnlyEntry($tableName, $id) { | |
$stm=$this->pdo->query('SELECT * From '.$tableName.' WHERE id = '.$id); | |
$value = $stm->fetch(); | |
return $value; | |
} | |
public function addCar($tableName, $arr) { | |
$values = ''; | |
$column = ''; | |
foreach ($arr as $key => $value) { | |
$arr1[] = $value; | |
$values .= ($values == '')? '?' : ',?'; | |
$column .= ($column == '')? $key : ', '.$key; | |
} | |
$sql = 'INSERT INTO '.$tableName.' ( '.$column.' ) VALUES ( '.$values.' ) '; | |
$stm=$this->pdo->prepare($sql); | |
return $stm->execute($arr1); | |
} | |
public function countRecords($tableName) { | |
$stm=$this->pdo->query('SELECT COUNT(id) FROM `'.$tableName.'`'); | |
$cars = $stm->fetch(); | |
return $cars; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment