- Php update code script
- Объектно-ориентированный стиль
- Список пользователей
- Обновление пользователя
- Процедурный стиль
- Список пользователей
- Обновление пользователя
- Saved searches
- Use saved searches to filter your results more quickly
- License
- travispessetto/script-updater-for-php
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- readme.md
- About
Php update code script
В MySQL для обновления применяется sql-команда UPDATE :
UPDATE Таблица SET столбец1 = значение1, столбец2 = значение2. WHERE столбец = значение
Для примера возьмем использованную в прошлых темах таблицу Users со следующим определением:
CREATE TABLE Users (id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30), age INTEGER)
Объектно-ориентированный стиль
Сначала определим файл index.php , который будет выводить список пользователей с ссылками на их обновление:
Список пользователей
connect_error)< die("Ошибка: " . $conn->connect_error); > $sql = "SELECT * FROM Users"; if($result = $conn->query($sql))< echo "
Имя | Возраст | |
---|---|---|
" . $row["name"] . " | "; echo "" . $row["age"] . " | "; echo "Изменить | "; echo "
Здесь используется команда SELECT, которая получает всех пользователей из таблицы Users. В таблице третий столбец хранит ссылку на скрипт update.php, который мы далее создадим и которому передается параметр id с идентификатором пользователя, которого надо изменить.
Для обновления данных определим скрипт update.php :
connect_error)< die("Ошибка: " . $conn->connect_error); > ?> real_escape_string($_GET["id"]); $sql = "SELECT * FROM Users WHERE "; if($result = $conn->query($sql))< if($result->num_rows > 0) < foreach($result as $row)< $username = $row["name"]; $userage = $row["age"]; >echo "Обновление пользователя
Имя:
Возраст:
"; > else< echo "Пользователь не найден"; > $result->free(); > else< echo "Ошибка: " . $conn->error; > > elseif (isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["age"])) < $userid = $conn->real_escape_string($_POST["id"]); $username = $conn->real_escape_string($_POST["name"]); $userage = $conn->real_escape_string($_POST["age"]); $sql = "UPDATE Users SET name = '$username', age = '$userage' WHERE "; if($result = $conn->query($sql)) < header("Location: index.php"); >else< echo "Ошибка: " . $conn->error; > > else < echo "Некорректные данные"; >$conn->close(); ?>
Весь код обновления структурно делится на две части. В первой части мы обрабатываем запрос GET. Когда пользователь нажимает на ссылку «Обновить» на странице index.php , то отправляется запрос GET, в котором передается id редактируемого пользователя.
if($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["id"]))
И если это запрос GET, то нам надо вывести данные редактируемого пользователя в поля формы. Для этого получаем из базы данных объект по переданному id
$userid = $conn->real_escape_string($_GET["id"]); $sql = "SELECT * FROM Users WHERE "; if($result = $conn->query($sql))Далее получаем полученные данные и, если они имеются, выводим их в поля формы. Таким образом, пользователь увидит на форме данные обновляемого объекта.
Вторая часть скрипта представляет обработку POST-запроса - когда пользователь нажимает на кнопку на форме, то будет отправляться POST-запрос с отправленными данными. Мы получаем эти данные и отправляем базе данных команду UPDATE с этими данными, используя при этом параметризацию запроса:
$userid = $conn->real_escape_string($_POST["id"]); $username = $conn->real_escape_string($_POST["name"]); $userage = $conn->real_escape_string($_POST["age"]); $sql = "UPDATE Users SET name = '$username', age = '$userage' WHERE "; if($result = $conn->query($sql))После выполнения запроса к БД перенаправляем пользователя на скрипт index.php с помощью функции
Таким образом, пользователь обращается к скрипту index.php , видит таблицу с данными и нажимает на ссылку "Обновить" в одной из строк.
После нажатия его перебрасывает на скрипт update.php , который выводит данные редактируемого объекта. Пользователь изменяет данные и нажимает на кнопку.
Данные в запросе POST отправляются этому же скрипту update.php , который сохраняет данные и перенаправляет пользователя обратно на index.php .
Процедурный стиль
Список пользователей
$sql = "SELECT * FROM Users"; if($result = mysqli_query($conn, $sql))< echo "
Имя | Возраст | |
---|---|---|
" . $row["name"] . " | "; echo "" . $row["age"] . " | "; echo "Изменить | "; echo "
?> 0) < foreach($result as $row)< $username = $row["name"]; $userage = $row["age"]; >echo "Обновление пользователя
Имя:
Возраст:
"; > else< echo "Пользователь не найден"; > mysqli_free_result($result); > else < echo "Ошибка: " . mysqli_error($conn); >> elseif (isset($_POST["id"]) && isset($_POST["name"]) && isset($_POST["age"])) < $userid = mysqli_real_escape_string($conn, $_POST["id"]); $username = mysqli_real_escape_string($conn, $_POST["name"]); $userage = mysqli_real_escape_string($conn, $_POST["age"]); $sql = "UPDATE Users SET name = '$username', age = '$userage' WHERE "; if($result = mysqli_query($conn, $sql))< header("Location: index.php"); >else < echo "Ошибка: " . mysqli_error($conn); >> else < echo "Некорректные данные"; >mysqli_close($conn); ?>
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A MIT Licensed script updater for projects
License
travispessetto/script-updater-for-php
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
readme.md
Script Updater for PHP is an update script that can be used with any PHP project to update the files via a couple clicks. The script only requires that it can get at a update file that contains the current version as well as the local filesystem location and the remote location. So, potentially Amazon S3 could be used.
Did we mention that this update script can adapt to languages? All you need is the appropriate language files in js/langs and langs/php.
The code is currently up to date
Prompt if you want to restore backup
To use this update script you will need to define a YAML file that explains what to do for the update. This file must contain version and files . Under files there is two additional items, add and delete . The version must be a set of integers seperated by a period (.) the leftmost number is of greatest importance.
Both the add and delete items are sequences. With all items in the add sequence being a mapping with local and remote defined. local is where you want the downloaded file to go and remote is where to get it from the update server.
The script section defines two sections do and undo . The do section defines what will execute when all files have been added, updated, or deleted. Each script in the do section must define if it should be deleted after execution by setting delete to either true or false . See the example below if you are confused. In the undo section you have scripts that will need to be executed if someone chooses to revert to a backup. This section requires script , remote , and delete sections. These scripts will be added to the backup file and will be retrieved from remote . The delete section specifies if it will be deleted after the backup is restored.
If you want your users to be able to click a button when finished you can set finishUrl in the YAML file to a relative URL. When the button is clicked they will go to whatever this is set to. If this does not exist they will get a message that a finish button was not found.
Below is an example of a YAML update file:
version: 1.1.17 files: add: - - delete: - "foo/foo.txt" scripts: do: - undo: - finishUrl: "finished.html"
To set up the updater you must edit config.php. version_url is where you put the base url for your update files. version_file is the version file on the remote host with the information to update. update_folder is the folder on the local host that you want to serve as your base.
Changing the URL for Different Versions
If you would like to have each version have its own update script you can make sure you include the updaters config.php in the updates with the new location for that version.
The following languages are supported:
Language | Version |
---|---|
English | All |
Spanish | All |
If you would like a language here either contribute it and I will update this repository or request it and I will see if I can get someone to translate it into that language.
Updater allows plugins to make your life a little bit easier. I mainly did this for tasks like authorization. To create a plugin simply put a php file in the plugins directory with a class named the same. See example.
class Authorize < // Hooks go here >
The contructor hook will execute when the controller constructor is called. Therefore, anything that should apply to all functions, such as authorization should be called there. This is done by adding the public function of ConstructorHook() to your plugin file. The constructor hooks really should either do nothing or return a header, such as forbidden if you do not want to continue.
class Authorize < public function ContructorHook() < // Authorization logic use exit(); if you need to terminate. > >
An example of an Authorize plugin that would not authorize anyone is as follows:
class Authorize < public function ConstructorHook() < // authorization logic here. call exit if not // authorized. header('HTTP/1.0 403 Forbidden'); exit(); > >
When the user goes to the update screen it will check for the existance of backup- files. If they exist then a prompt will ask if they would like to restore a backup or check for updates.
The following failsafes are in place:
All files are checked before downloading to make sure they are writable
All files that are going to be added and currently exist or are going to be deleted are added to a backup file named backup-.zip in the same folder as the updater script.
Note: No backup of any databases are taken at this time and probably will not happen anytime in the near future as I want this to be database agnostic. That said, it may take more work but you can use the first position in the script section to make a backup of the database.
The file backup will contain a YAML script name restore.yml that will provide instructions on how to recover the backup. It will simply contain two sections: delete and scripts . It will look similar to the following:
delete: - "scripts/foo.php" - "scripts/bar.php" scripts: -
All remote files are checked to exist before they are installed.
I would love people to fork this project and contribute. If not that I would be interested in who uses this product. See my website https://pessetto.com to find my email and shoot me a quick message if you use and like this product.
The following tools exist for testing purposes or to simply make your life easier when creating a update file. They can be found in the tools folder of this repository. Some may be accessed via a command line/terminal with PHP installed others will need to use a web browser.
This script will generate two folders in the root of the repository, update-test and update-test-source. If you have a test webserver setup you can then test if the backup system works by visting update-test. This is good for testing updates and restoring for backups.
To run this script you will need to make sure the repository is somewhere the web browser can see it and then point the browser to the repsoitory's URL with appended with tools\update-test.php .
In order to parse YAML we are using the Spyc library by Vladimir Andersen. This is licensed under the MIT License.
Copyright (c) 2020 Travis Pessetto
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
A MIT Licensed script updater for projects