Skip to main content

SQL in a nutshell | Learn SQL

SQL stands for Structured Query Language. SQL is used to access and modify the data in a database.
All dynamic web applications and websites make use of a database and only way to access these database is through SQL.
Now practically what happens is that a programming language passes an SQL command which returns the result which is further processed for viewing.

Demo of what we are making here Post it! Chatroom


Let's cut the theory and move to practical.

Objective: We will be making a small PHP website(chat room) using the SQL commands to feed and fetch the details. I will leave the lessons of PHP for some other day, in fact I'm myself in the learning phase as well.


Part 1. Database and SQL installation.

If you wish to run a database on your local machine follow this link.
I recommend using an online service for practicing. 000webhost is free and provides you everything.
For this tutorial I will be using 000webhost so that the project I end up with will be public for demo.

Setting up a Database and SQL always involves

  1. Creating a database. 
  2. Defining a user and granting him privileges to modify the database we created in step 1.

Part 2: Basic SQL commands.


These are some basic SQL commands that will come in handy, always.

Creating a database: SQL>create database myDB
You don't need this command when using Oracle. We simply create tables in Oracle and use them.

Creating a table: SQL>create table myTable(column1 number(8), column2 varchar2(20));
The above command results in a table of name myTable with two columns. First column will accept values only of type number that too of size upto 8 and column2 will accept value of type varchar which can take any number or character or combination of both.

In case you need to modify the table you just made, following command will be helpful 

alter table tableName add columnName datatype;

alter table tableName drop column columnName;

alter table tableName modify columnName datatype;

alter table tableName rename column oldName to newName;

rename yourtable to mytable;

Inserting data into the table.

insert into tableName values(87, 'hello');

In case you want to change a value you have previously entered.
update mytable set uname='abhay' where uid=123;

Use where clause to narrow your search to specific data.

Like wise there are just too many commands and that would just complicate things for a beginner.

Part 3: PHP website using SQL


Let's get our hands dirty by making an actual application that uses database and SQL.
Objective here is to make a small website that will let anyone post a message to it and it would be visible to everyone.

To explain it like you're 5 year old.

I will make a table which will have a serial number like 1,2,3 and so on and a data associated with each number.

  1. I just made this up.
  2. Some text here.
  3. Well yea again.

Firstly I will make a database and grant privileges to a user to modify this database. Luckily 000webhost provides a very simple way to do this.



To make this type of table I will run the command

SQL>CREATE TABLE `posts` ( `serial` INT NOT NULL , `content` LONGTEXT NOT NULL );

But unfortunately it wasn't as easy as it may look. I used phpMyAdmin to generate my SQL command which was

CREATE TABLE `id1132423_post`.`post` ( `serial` INT NOT NULL , `content` LONGTEXT NOT NULL ) ENGINE = InnoDB;


Now we will test the working of our database by inserting some dummy content.
For this I will use the Insert tab in phpMyAdmin and preview the SQL command and note it.

Now the SQL was generated as

SQL>INSERT INTO `post` (`serial`, `content`) VALUES ('1', 'Hello World!\r\nThis is blog.');




Now I will be executing the likes of above SQL command through my PHP page.

Now let's make a PHP file and make a connection to the database.

For this I will need following details,

  1. database host name, usually localhost. .
  2. database name, whatever you chose earlier, in case of 000webhost it can be found in settings.
  3. database user,
  4. database password for that user.

then make a file by the name index.php
 and put following code in it

<html>
<head>
<title>Post it!</title>
</head>
<body style="background-color:#efefef; font-family:monospace;">
<h1 style="text-align:center;">Post it!</h1>
<?php
 $db = mysqli_connect('localhost','databaseUser','password','databaseName')
 or die('Error connecting to MySQL server.');
$query  = 'SELECT * FROM post ORDER BY timestamp DESC LIMIT 20';

mysqli_query($db, $query) or die('Error querying database.');
?>

<form action="post.php" method="post" align="center">
            <input type="text" name="id" placeholder="enter a number(optional)" />
            <input type="text" name="content" placeholder="enter a text"/>
            <input type="submit" value="submit" onclick="test()" />
</form>
<?php
$result = mysqli_query($db, $query);

while($row = mysqli_fetch_array($result))
{
echo "<table align="."center".">";
    echo "<tr>";
    echo "<td>$row[0]</td>";
    echo "<td>$row[1]</td><br/>";
    echo "</tr>\n";
echo "</table>";
}
mysqli_close($db);
?>
</body>
</html>

This file makes a call to post.php

Make another file and save it with following content as post.php

<?php
$sContent = $_POST['content'];
$db = mysqli_connect('localhost','databaseUser','password','databaseName')
 or die('Error connecting to MySQL server.');
$query = "INSERT INTO `post` (`id`, `content`, `timestamp`) VALUES (NULL, '".$sContent."', CURRENT_TIMESTAMP)";
mysqli_query($db, $query) or die('Error querying database.');
mysqli_close($db);
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>


I made post.s2pd.com with just these code.
It is kind of chat room. I will be covering the break down of PHP code in another post.
Go experiment.

Update: I have made this project available on Github here.

Comments

Popular posts from this blog

Unity Mobile Game Optimization Checklist

- On Image and Text components that aren’t interacted with you can uncheck “Raycast Target” on it, as it will remove them from any Raycast calculus. - Click on your textures in your “Project” window. Click on the “Advanced” arrow, and now check “Generate Mip Maps”, Unity especially recommends it for faster texture loading time and a lower rendering time. - Set the “Shadow Cascades” to “No Cascades” (Quality settings) - If you have dynamic UI elements like a Scroll Rect with a lot of elements to visualize, a good practice is to turn off the pixel perfect check box on the canvas that contains the list and disable the items that aren’t visible on the screen. - Set all non moving objects to "Static" - Above Unity3d 2017.2 you should turn off "autoSyncTransforms" on the Physics tab - Always use Crunch Compression Low on textures - Try to keep the “Collision Detection Mode” on “Discrete” if possible, as “Dynamic” demands more performance. - You can go to the TimeManager w...

How to make RPC in Unreal Engine Steam Online Subsystem and EOS

Remote Procedure Calls, also known as RPCs, are a way to call something on any other instance.  In the Unreal Engine, RPCs are used to ship events from the patron to the server, the server to the customer, or from the server to a specific group. It's important to word that RPCs cannot have a return cost. If you want to return something, you'll ought to use a seconds RPC within the contrary path. There are precise policies that RPCs observe, which are unique in the official Documentation. Some of these regulations encompass wherein the RPC must be run, such as the server instance of an Actor, on the owner of the Actor, or on all instances of the Actor. There are some necessities for RPCs. First, they must be referred to as on Actors or replicated Subobjects. The Actor (and component) have to additionally be replicated. If the server is looking an RPC to be executed on a customer, handiest the patron who owns that Actor will execute the function. Similarly, if a client is calling...

How to drag and drop item in Unity3D

  For dragging and dropping to work we will need to first grab the Game Object and ensure while the Game Object remains grabbed it's position reciprocates the mouse position. This will work fine for not only PC bug mobile devices as well. First define GameObject which we will be dragging. public GameObject selectedPiece; Now inside Update method we will give reference to touched/clicked object and while there is a reference available to an game object(selectedPiece;) we will move that object to mouse position. When the reference is remove, object won't move therefore dropped. void Update(){ RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); if (Input.GetMouseButtonDown(0)){ if(hit.transform != null)             {                 if (hit.transform.CompareTag("PIECE"))                 {     ...