PHP MySQL query with error printing
SQLStructured Query Language or popularly known as SQL is an universal language to handle database. An introduction and different types of sql command like select, insert, update etc you will get in the sql section of this site. There are some advance SQL commands like left join, linking of tables etc to study. If you are not comfortable with SQL any time you can refer the materials in sql section.
There are three steps involved in this process.
Connecting database and executing QueryTo manage data we have to connect to MySQL database and execute query to get our date. Here there are two ways to use PHP drivers to connect to MySQL and execute the functions for getting records.
One is using Portable Data Object ( PDO )
Second one is MySQLI ( MysQL Improved )
PHP Functions & SQLLet us start with the function required to execute one query in PHP. Once you have connection established then we can execute sql command by using PHP function mysql_query(). Here is the syntax of the function.
Let us first write the query and store in a variable. We will write a query to create table.
We have stored the sql create query in a variable $query and we will pass this as a parameter to the function like below.
The above command will execute php_mysqli() the query ( stored in variable $query) and we can check the status of the query ( successful or not ) by checking the value of the variable $rt. $rt will be true if the query is successfully executed or it will return false. We will use php if command to check the status of the query.
So from the above line we can know that the query has worked or failed. But we will not come to know about the error if the database has some error and the query has failed. To get the error message we have to use another function mysqli_error() to print the error message returned by MySQL database after executing the query. Here it is how to print the error message.
The above line will print the error returned by mysql database if the query fails to execute. You can read more on mysql error here.
The complete code is available below.
Before executing the above code we must connect to mysql database by using mysqli connection string.
Subscribe to our YouTube Channel here
This article is written by plus2net.com team. https://www.plus2net.com