Good day. I don’t know much about php, so the question is: I have this code, but it saves the data in a .json file. And I need to remake it so that it sends the data to the Mysql table on the server. (I already created a bd-shku, I created a table in it with 2 columns: id and text directly).

What should be the result: There is one textarea field that constantly contains the entered text. (That is, when you reload the page, or enter from another computer - we should see the last text entered). A kind of note of its kind.

<?php $note_name = 'note.json'; if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ // Запрос AJAX if(isset($_POST['note'])){ file_put_contents($note_name, $_POST['note']); echo '{"saved":1}'; } exit; echo '{"saved":0}'; } $note_content = ''; if( file_exists($note_name) ){ $note_content = htmlspecialchars( file_get_contents($note_name) ); } ?> 

I would be grateful for the help!

    1 answer 1

    First you need to connect to the database, for this you need to know the database address, login, password, database name.

    This is a simplified version, which shows the approximate logic of work, it does not take into account the question of initially adding a record to the database, so for the operation it is necessary to have an entry in the database with id = 1.

    I hope this code will give an initial understanding of where to go.

     <?php $dbHost = "localhost"; // Адрес БД $dbUser = "root"; // Ваш логин $dbPassword = ""; // Пароль $dbName = "note" // Название вашей базы // подключение и выбор базы данных $link = mysql_connect($dbHost, $dbUser, $dbPassword) or die('Не удалось соединиться: ' . mysql_error()); mysql_select_db($dbName) or die('Не удалось выбрать базу данных'); // Ваша логика приложения if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ if(isset($_POST['note'])){ $text = $_POST['note']; // Выполняем SQL-запрос $query = "UPDATE `tablename` SET `text`='$text' WHERE id=1" ; // id=1 это для примера, вам исходя из потребностей нужно указать свое условие $result = mysql_query($query) or die('Запрос не удался: ' . mysql_error()); echo '{"saved":1}'; } exit; echo '{"saved":0}'; } $note_content = ''; // Выполняем SQL-запрос $query = "SELECT `text` FROM `tablename` WHERE id=1" ; // id=1 это для примера, вам исходя из потребностей нужно указать свое условие $result = mysql_query($query) or die('Запрос не удался: ' . mysql_error()); $row = mysql_fetch_array($result, MYSQL_ASSOC); $note_content = $row['text']; ?>