Как я могу сохранить значение из базы данных MySQL в файл .txt при нажатии кнопки загрузки? - PullRequest
0 голосов
/ 01 июня 2019

Я только начинаю с MySQL и PHP, я создал таблицу «Шутка» в своей базе данных и показал данные на стороне моего PHP-сервера с помощью этого кода:

$result = mysqli_query($link, 'SELECT joketext FROM joke');  


while ($row = mysqli_fetch_array($result))  
{  
  $jokes[] = $row['joketext'];  
}  

include 'jokes.html.php'; 

И HTML-код:

<p>Here are all the jokes in the database:</p>  
    <?php foreach ($jokes as $joke): ?>  
      <blockquote><p>  
        <?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?>  
      </p></blockquote>  
    <?php endforeach; ?>   

Это работает для меня, но теперь я хочу добавить кнопку «скачать» рядом с каждой шуткой, чтобы загрузить ее в файл .txt.

Ответы [ 2 ]

0 голосов
/ 01 июня 2019

Если вы измените часть HTML / PHP на своей странице, добавив в нее простую гиперссылку, например:

<p>Here are all the jokes in the database:</p>  
<?php foreach ($jokes as $id => $joke): ?>  
  <blockquote>
      <p>  
        <?php 
            echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
        ?>
      </p>
      <a class='download' href='#' title='Download the joke'>Download</a>
  </blockquote>  
<?php endforeach; ?> 

Затем скопируйте нижеприведенный javascript на свою страницу и обнаружите, что вы можете загрузитьшутки по желанию.Если вы скопируете весь приведенный ниже код, вы обнаружите, что он будет работать в вашем браузере нормально.

<html>
    <head>
        <title>Download a joke</title>
        <script>
            /*
                wait for the DOM to load and then set event listeners
                on the new hyperlinks
            */
            document.addEventListener('DOMContentLoaded', ()=>{
                /*
                    Query the DOM for ALL hyperlinks of class `download`
                    and assign an event handler for click events
                */
                document.querySelectorAll('a.download').forEach( function(a){
                    a.addEventListener( 'click', function( event ){
                        /*
                            prevent the default action for this hyperlink
                        */
                        event.preventDefault();

                        /*
                            The Joke is located in the previous
                            DOM node - P
                        */
                        let p=this.previousElementSibling;

                        /*
                            create a BLOB object to store the joke text
                        */
                        let blob=new Blob([ p.innerText ],{type: 'text/plain'});


                        /*
                            function to send the file - jiggery pokery
                        */
                        const sendfile=function( blob, name ){
                            let url=URL.createObjectURL( blob );
                            let lnk=document.createElement('a');
                            let evt=new MouseEvent('click',{
                                bubbles:true,
                                cancelable:true,
                                view:window
                            });
                            p.appendChild( lnk );
                            lnk.href=url;
                            lnk.download=name;
                            lnk.dispatchEvent( evt );
                            p.removeChild( lnk );
                        }


                        sendfile.call( this, blob, 'joke.txt' );
                    });
                });
            });
        </script>
    </head>
    <body>

        <!-- EXAMPLE DATA -->
        <blockquote>
            <p>  
                This is the joke - not very funny though is it?
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>  
                This is another joke - or what passes for a joke!
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>  
                This is probably not the best joke in the World.
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>  
                A woman gets on a bus with her baby. The bus driver says: 'Ugh, that's the ugliest 
                baby I've ever seen!' The woman walks to the rear of the bus and sits down, fuming. 
                She says to a man next to her: 'The driver just insulted me!' The man says: 'You go 
                up there and tell him off. Go on, I'll hold your monkey for you.
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>


    </body>
</html>
0 голосов
/ 01 июня 2019

Вы можете implode() массив $jokes:

$all_jokes = implode("\n", $jokes);
file_put_contents("all_jokes.txt", $all_jokes);

и на вашей html-странице:

<a href="all_jokes.txt">Download all</a>

ссылки здесь:

https://www.w3schools.com/php/func_filesystem_file_put_contents.asp https://php.net/manual/en/function.implode.php

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...