To-do lists are a great way to keep track of your daily tasks. In this tutorial, we will build our own to-do list using PHP, MySQL, and AJAX. This tutorial assumes that you have a basic understanding of HTML, PHP, MySQL, and JavaScript.

We will be using the following files throughout this tutorial. You can download them using the link below. Feel free to use an alternative structure, but remember to change your file paths from those in the example code.

Main Index File

The first thing we need to do is lay out the structure for our main index page (index.php ). This application will only have one page and we will use AJAX to add and delete to-do items. Open the index.php file and add the following code.

Simple To-Do List

Note: For the sake of time, we will not cover styling in this tutorial. A CSS file has been included in the source files.

Connecting to the MySQL Database

We need to set up a MySQL database for storing our to-do items. The easiest way to do this is trough a server-side tool called phpMyAdmin . The tools comes pre-installed on most web hosts and is bundled with local development services such as WampServer and XAMPP. We will be setting up one table with the name of ‘tasks’ and the following columns in this order: ‘id’, ‘task’, ‘date’, ‘time’. Be sure to set the id column to auto-increment (there should be a checkbox labeled ‘A_I’).

After creating the new table, we need to connect our project to the database. Open connect.php and add the following code to the file. Be sure to substitute your database details for the ‘username’, ‘password’, and ‘database_name’ fields. Save the file when you are done.

Explaining the Code
PHP has a mysql_connect() function that creates a connection to the MySQL server. The server variable should remain set to ‘localhost’ unless your database is hosted on a different server than the project files. In that case, substitute this value for the MySQL server’s IP address. Once the connection has been made, the mysql_select_db() function selects a specific database from the server.

Now that we have created our connect.php file, we need to add it to the main index file. Add the following code to index.php and save the change.

Simple To-Do List

Adding a New To-Do Item

The next thing we want to do is create a way to add items to our to-do list. To do this, we will use a form and submit the results to the database. Add the following code to index.php and save the change.

Simple To-Do List

Note: Notice that the form does not have action and method attributes. These are typically used to submit data to another file via a post or get request. We will be using AJAX to submit our form, so we will not be defining either of these attributes. For more information on AJAX, check out this article from W3Schools .

Open index.php in your web browser and have a look. At this point, you should see a large white rectangle where the to-do items will be displayed and a text field for adding new items to the list.

We need to set up a way for the form to communicate with the database. Using jQuery, let’s send our new to-do item via a post request to the add-task.php file. From there, our item will be formatted and saved to the database. Add the following to the index.php file directly after the closing tag.

Explaining the Code
The script above intercepts the text field value on form submit and sends it to add-task.php using the $.post() jQuery method. The add-task.php file then sends back confirmation of the newly added item, so it can be added to the list. The beautiful thing is that all of this happens without refreshing the page!

Now that our form is sending the new to-do item to add-task.php , we need to tell that file what to do with the information. Open add-task.php and add the following code. Remember to save the file.

Эта статья также доступна на следующих языках: Тайский

  • Next

    Огромное Вам СПАСИБО за очень полезную информацию в статье. Очень понятно все изложено. Чувствуется, что проделана большая работа по анализу работы магазина eBay

    • Спасибо вам и другим постоянным читателям моего блога. Без вас у меня не было бы достаточной мотивации, чтобы посвящать много времени ведению этого сайта. У меня мозги так устроены: люблю копнуть вглубь, систематизировать разрозненные данные, пробовать то, что раньше до меня никто не делал, либо не смотрел под таким углом зрения. Жаль, что только нашим соотечественникам из-за кризиса в России отнюдь не до шоппинга на eBay. Покупают на Алиэкспрессе из Китая, так как там в разы дешевле товары (часто в ущерб качеству). Но онлайн-аукционы eBay, Amazon, ETSY легко дадут китайцам фору по ассортименту брендовых вещей, винтажных вещей, ручной работы и разных этнических товаров.

      • Next

        В ваших статьях ценно именно ваше личное отношение и анализ темы. Вы этот блог не бросайте, я сюда часто заглядываю. Нас таких много должно быть. Мне на эл. почту пришло недавно предложение о том, что научат торговать на Амазоне и eBay. И я вспомнила про ваши подробные статьи об этих торг. площ. Перечитала все заново и сделала вывод, что курсы- это лохотрон. Сама на eBay еще ничего не покупала. Я не из России , а из Казахстана (г. Алматы). Но нам тоже лишних трат пока не надо. Желаю вам удачи и берегите себя в азиатских краях.

  • Еще приятно, что попытки eBay по руссификации интерфейса для пользователей из России и стран СНГ, начали приносить плоды. Ведь подавляющая часть граждан стран бывшего СССР не сильна познаниями иностранных языков. Английский язык знают не более 5% населения. Среди молодежи — побольше. Поэтому хотя бы интерфейс на русском языке — это большая помощь для онлайн-шоппинга на этой торговой площадке. Ебей не пошел по пути китайского собрата Алиэкспресс, где совершается машинный (очень корявый и непонятный, местами вызывающий смех) перевод описания товаров. Надеюсь, что на более продвинутом этапе развития искусственного интеллекта станет реальностью качественный машинный перевод с любого языка на любой за считанные доли секунды. Пока имеем вот что (профиль одного из продавцов на ебей с русским интерфейсом, но англоязычным описанием):
    https://uploads.disquscdn.com/images/7a52c9a89108b922159a4fad35de0ab0bee0c8804b9731f56d8a1dc659655d60.png