Jumat, 08 Agustus 2014

Connecting PHP to MySQL

 Php code run on the server and sometime need to access database from the server. There are a lot of database that we can use. For this time we’ll use MySQL as our database.
There are at least three things that we used to do to connect our PHP to our MySQL database.
1. Connect the database
2. Execute the query
3. Close the database
To make these steps run, we’ll use mysqli function that stands for MySQL Improve function. Here they are the complete step of connecting database to our beloved PHP code.

1. Connect the database

For the sake of connecting the database to our PHP code, we’ll use function that called:
mysqli_connect($host, $user, $password, $database);

parameter that we used here will be filled using our credential. $host will be our host for example, jejebawang.com, localhost, or else. $user will be the name of user that we use for the database, $password is the password of the database  and the last one $database is the name of our database.
For mine on the development mode, it will be something like this:
$link= mysqli_connect('localhost', 'root', '', 'testing');

You don’t need to follow the example, just filled the variable depending on your host and database.

2. Excecute the query

The next one you need the query to do something, for instance you want to insert a data to a table, the function that we use will be
mysqli_query($link, $query);

For mine it will be like this:
$query = "INSERT INTO email_list (first_name, last_name, email) 
VALUES(‘Zaenul’, ‘Hilmi’, ‘jejebawang@gmail.com’)";

$result = mysqli_query($link, $query) or die('query error');


3. Close the database

The last thing that we have to do is closing the database link.
mysqli_close($link);
Closing the database is a good habit when we finished a connection with database. We close the database so that if we want to create new database connection, it will be free and able to make connection.

The complete code will be something like this:
$link= mysqli_connect('localhost', 'root', '', 'testing');

$query = "INSERT INTO email_list (first_name, last_name, email) 
VALUES(‘Zaenul’, ‘Hilmi’, ‘jejebawang@gmail.com’);"


$result = mysqli_query($link, $query) or die('query error');

mysqli_close($link);


That’s it. If you have something in your mind, let me know in comment section bellow. 

Kamis, 07 Agustus 2014

Hello World

Its a common sense in a tale to start a story with "Once upon a time...", so does in every programming language. Instead of using "Once upon a time", we use "Hello world".

Lets do it in some language,

Java :
System.out.println("Hello world");
PHP :
$string = "Hello World";
echo $string ;