Punjabi revolution tutorials PHP MySQL Connection Part 1 insertion

In this tutorial, we would observe how to connect with mysql database using PHP.

Database is an integral part of eCommerce websites. If take a sample space of software applications from any freelancing website, more than eighty percent would comprise database in some way. When we install, the xampp the mysql server is automatically installed. Please note that mysql work bench or heidisql are not the mysql server, rather these are just front end interfaces. The mysql server is installed in the background and runs as a service. You can use command line to execute query. Just like, heidisql and workbench etc, Tomcat with PHP also provides  an interface. On localhost it can be accessed in following way.

http://localhost/phpmyadmin/

But if the mysql sever is not installed on your local machine, you would replace the localhost with the IP of the mysql server machine.

The method to create the mysql server has been demonstrated in above video. Here after creating the video, we create a simple form, submit the form to a PHP page and on php page, we put the form data into database. Below is the code for the the page where a form was developed.

after the form is submitted we are landed at form_post_mysql_action.php with following code

Line 5: $n is assigned value got from form name field.

Line 5: $e is assigned value got from form email field.

Line 8: $con object is created using PHP built in class mysqli. The class constructor takes following arguments.

  1.  The address of machine where mysql is installed.
  2. The user name of mysql, by default it is “root”
  3. The password  and by default it is empty.
  4. The name of the database. in this case, it is
    WAD.

Line 10: the variable $q is assigned a string that is actually a SQL query. The single quotes around variables in the insert query conform to the fact that the string values are enclosed by single quotes.

Line 12 : $con->query($q)  method returns Boolean for non-select queries. So in this case, it would return true if query successfully executed and false otherwise.

Line 15: $con->error would contain the error message if $con->query($q)  reurns false i.e. the SQL query fails.

Line 17: the $con->close();  would close the the sql connection. It is very economical to close the connection as it slows the the data base operations and if too many connections are kept open. Also, the hostin companies have in general an upper limit of allowed number of SQL connections.

 

Leave a Reply

Your email address will not be published. Required fields are marked *