Сообщение было отмечено xakmika как решение
Решение
HTML
Кликните здесь для просмотра всего текста
| HTML5 | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Сохранения \ Авто загрузка</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="send.js"></script>
</head>
<body>
<p>
<font size="5" color="green" face="Arial">Сохранения</font>
</p>
<form id="FormSave" action="api.php" method="POST" Success="ResultLoad" Error="ResultLoadError">
<input type="hidden" name="method_call" value="FormSave" />
<input type="hidden" name="IdInitialized" value="0" />
<p><input type="checkbox" name="cenatopik" id="cenatopik" checked/> Включи\Выключи меня</p>
<button type="submit" class="button default">Применить </button><br>
<font id="message" size="5" color="red" face="Arial"></font>
</form>
<script>
function ResultLoad(data, this_jquery) {
// Сбросим данные формы. если ошибок нет
// if (!data['error']) this_jquery.trigger("reset");
this_jquery.children('#message').html(data['message']);
$('#cenatopik').prop('checked', data['cenatopik'] != 0);
}
function ResultLoadError(error, this_jquery) {
alert(error.responseText);
}
$(window).bind("load", function() {
$("#FormSave").submit();
$("#FormSave").children('[name=IdInitialized]').val('1');
});
</script>
</body>
</html> |
|
PHP
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| <?php
// Стандартный функционал
// > Покажем все ошибки
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// > Задаём ответ в виде json
header('Content-Type: application/json; charset=utf-8');
include_once "api_functions.php";
include_once "mysqli.php";
$connection = new MSQLi('hostname', 'username', 'password', 'database');
if(!$connection->connected()) {
echo 'Не могу соединиться с БД. Код ошибки: ' . mysqli_connect_errno() . ', ошибка: ' . mysqli_connect_error();
exit;
}
// Код
$table = 'Settings';
switch(ParsArgsResult('method_call', false, true, -1)) {
case 'FormSave':
extract(ParsArgsArray(
['cenatopik', false, true, 0],
['IdInitialized', false, true, 0],
));
$cenatopik = (bool)$cenatopik;
$IdInitialized = (bool)$IdInitialized;
if($IdInitialized) {
$IS = $connection->query("REPLACE INTO `{$table}` (`id`, `cenatopik`) VALUES ('1', '{$cenatopik}');");
$info = $IS === true ? 'Сохранено' : 'Ошибка при сохранение';
} else {
$info = 'Настройки загружены.';
}
$result = $connection->query("SELECT * FROM `{$table}`");
if(is_object($result) && !empty($result->row)) {
returnOut([
'error' => true,
'message' => $info,
'cenatopik' => $result->row['cenatopik']
]);
} else {
returnOut([
'error' => true,
'message' => 'Настройки не найдены',
]);
}
break;
default:
returnOut([
'error' => true,
'message' => 'Метод не найден.'
]);
}; |
|
Дополнительные файлы
Кликните здесь для просмотра всего текста
send.js
Кликните здесь для просмотра всего текста
| JavaScript | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| function function__Send(e, th) {
e.preventDefault();
var url = '';
var callback = th.attr('Success') ? function(data) {
(new Function('return ' + th.attr('Success'))())(data, th);
} : function(data) {
alert(data['message']);
if (!data['error'])
th.trigger("reset");
};
var callbackError = th.attr('Error') ? function(data) {
(new Function('return ' + th.attr('Error'))())(data, th);
} : function(error) {
alert(error.responseText);
};
if (th.data('href'))
url = th.data('href');
else if (th.attr('action'))
url = th.attr('action');
var type_method = 'POST';
if (th.attr('method'))
type_method = th.attr('method');
$.ajax({
data: new FormData(th[0]),
crossDomain: true,
dataType: "json",
url: url,
type: type_method,
processData: false,
contentType: false,
success: callback,
error: callbackError
})
return false;
}
$(window).bind("load", function() {
$("form").unbind("submit");
$("form").submit(function(e) { function__Send(e, $(this)); });
}); |
|
api_functions.php
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
| <?
// > Стандартная функция вывода ответа API
function returnOut(array $result) {
echo json_encode($result);
exit; // Выходим из работы скрипта.
};
function PrintHtml(...$Args) {
echo '<pre>' . print_r($Args, true) . '</pre>';
}
function SendMessageTelegram($Message, $token, $chat_id) {
$ch = curl_init('https://api.telegram.org/bot' . $token . '/sendMessage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'chat_id=' . $chat_id . '&text=' . urlencode($Message));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
if(is_array($result) && (isset($result['error_code']) && ($result['error_code'] == 400))) {
return SendMessageTelegram($Message, $token, $result['parameters']['migrate_to_chat_id']);
}
return $result;
}
// Функция загрузки файлов на сервер
function LoadFilesFromDir($dirLoad, &$SuccessfulLoading, &$IsErrorLoad, $ext = '') {
if(!empty($ext))
$ext = explode('|', $ext);
// Если папки не существует, создадим её
if(!is_dir($dirLoad)) {
if (!mkdir($dirLoad, 0777, true)) {
return true;
}
}
// Обработаем переданные файлы на сервер
$SuccessfulLoading = [];
$IsErrorLoad = [];
$callbackLoad = function($key, $name, $tmp_name, $type)
use ($dirLoad, &$SuccessfulLoading, &$IsErrorLoad, $ext) {
$Load = false;
if(is_array($ext)) {
foreach($ext as $v) {
if(stripos($type, $v) !== false) {
$Load = true;
break;
}
}
} else {
$Load = true;
}
if($Load) {
// Зададим указанный путь, с именем файла
$LoadToDir = $dirLoad . '/' . $name;
// Перенесём файл в нашу указанную папку
$ret = ['tmp_name' => $tmp_name, 'path' => $LoadToDir, 'type' => $type];
if(!move_uploaded_file($tmp_name, $LoadToDir))
$IsErrorLoad[$key] = $ret;
else
$SuccessfulLoading[$key] = $ret;
}
};
foreach($_FILES as $key => $file) {
if(is_array($file['name'])) {
// Похоже, нужно обработать сколько файлов (multiple)
foreach($file['name'] as $index => $name) {
$callbackLoad($key, $name, $file['tmp_name'][$index], $file['type'][$index]);
}
} else {
// Обаработаем без multiple
$callbackLoad($key, $file['name'], $file['tmp_name'], $file['type']);
}
}
return count($SuccessfulLoading) <= 0 && count($IsErrorLoad) <= 0;
}
// Функция быстрой проверки аргументов
// $name > Имя ключа в $_REQUEST
// $ErrorText > Еси нужен кастомтный текст ошибки
// $default > Нужен ли аргумент по умолчанию? Если нет ключа
// $value > Если нужен, то задаём значение
// $callBack($name, $ErrorText) > Кастомный обработчик
function ParsArgsResult($name, $ErrorText = false, $default = false, $value = false, $callBack = false) {
$Result = NULL;
if(empty($_REQUEST[$name])) { // Если пустой ключ, или его нет
if($default) {
$Result = $value; // Задаём значение по умолчанию
} else {
$ErrorText = ($ErrorText ? $ErrorText : "Ключ \"{$name}\" не задан.");
if($callBack && is_callable($callBack)) {
$callBackResult = $callBack($name, $ErrorText);
if($callBackResult) {
return $callBackResult;
}
} else {
returnOut([
'error' => true,
'message' => $ErrorText
]);
}
}
} else { // Получим значение ключа
$Result = $_REQUEST[$name];
}
return $Result;
}
// Обрабатываем поочерёдно [], [], ...
function ParsArgsArray() {
$Result = [];
$callBack = null;
$Error = [];
foreach(func_get_args() as $params) {
if(is_callable($params)) {
$callBack = $params;
} elseif(is_array($params)) {
$name = $params[0];
$ErrorText = isset($params[1]) ? $params[1] : false;
$default = isset($params[2]) ? $params[2] : false;
$value = isset($params[3]) ? $params[3] : false;
if(empty($_REQUEST[$name])) { // Если пустой ключ, или его нет
if($default) {
$Result[$name] = $value; // Задаём значение по умолчанию
} else {
$Error[$name] = $ErrorText ? $ErrorText : "Ключ \"{$name}\" не задан.";
}
} else { // Получим значение ключа
$Result[$name] = $_REQUEST[$name];
}
}
}
if(!empty($Error)) {
if(is_callable($callBack)) {
$callBackResult = $callBack($Error);
if($callBackResult) {
return $callBackResult;
}
} else {
$errorText = '';
foreach($Error as $key => $value) {
$errorText .= $value . PHP_EOL;
}
returnOut([
'error' => true,
'message' => $errorText
]);
}
}
return $Result;
} |
|
mysqli.php
Кликните здесь для просмотра всего текста
| PHP | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
| <?php
class MSQLi {
public $connection;
public function __construct($hostname, $username, $password, $database, $port = '3306') {
$this->connection = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->connection->connect_error) {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno);
}
$this->connection->set_charset("utf8mb4");
$this->connection->query("SET SQL_MODE = ''");
}
public function query($sql) {
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value) {
return $this->connection->real_escape_string($value);
}
public function countAffected() {
return $this->connection->affected_rows;
}
public function getLastId() {
return $this->connection->insert_id;
}
public function connected() {
return $this->connection->ping();
}
public function __destruct() {
$this->connection->close();
}
} |
|
У секций должен быть id
| T-SQL | 1
| ALTER TABLE Settings ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; |
|
Добавлено через 32 секунды
К ознакомлению подробному
https://www.cyberforum.ru/post15626974.html
0
|