How to import mysqli in PHP?

The MySQLi extension was developed to take advantage of new features found in MySQL systems versions 4.1 and Above. MySQLi is also sometimes known as the MySQL improved extension.The MySQLi extension is included with PHP versions 5 and later.

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension.

The MySQLi extension has a number of benefits, the key enhancements over the MySQL extension listed below

  • Object-oriented interface as well as this extension also provides a procedural interface
  • Support for Prepared Statements
  • Support for Multiple Statements
  • Support for Transactions
  • Enhanced debugging capabilities
  • Embedded server support

So Today I am going to Write About Connecting to MySQL Server using PHP’s MySQLi Extension.

mysqli_connect() function is used to connect to database,this function returns a link identifier On success, that you can use in other MySQLi functions. On failure, it will throw an error.

MySQLi connection with the object method

$link = new mysqli('localhost', 'root', 'password', 'database_name'); 

MySQLi connection with the procedural method

$link = mysqli_connect('localhost', 'root', 'password', 'database_name'); 

If your MySQL port is different from default one (3306), you need to give the port number as the fifth parameter.

MySQLi connection with the Port Number

//MySQLi connection with the procedural method and port
$link = mysqli_connect('localhost', 'root', 'password', 'database_name',3307);
//MySQLi connection with the object method and port
$link = new mysqli('localhost', 'root', 'password', 'database_name',3307);  

mysqli_connect() throws an error at failure and mysqli_connect_error() stores the error in last call to mysqli_connect(). If there is no error, it returns NULL.

Connection error checking

// OPPs method
$sql = new mysqli('hostName', 'userName', 'password', 'DBName');
 
if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}

//procedural method
$con = mysqli_connect("hostName","userName","password","DBName") or die("Some error occurred during connection " . mysqli_error($con));

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

PHP is widely used for building a wide range of products ranging from web apps to enterprise level applications. The key to efficient PHP code is to follow proper workflows and automate processes. The result is high quality and bug-free code.

In almost all PHP applications, data is stored, accessed and exchanged between various components of the app. To make sure that this exchange and access to data goes smoothly and without any issues, the development team must make sure that the databases and data dumps are in proper format.

How to import mysqli in PHP?

Import and export of data to and from databases is a common enough procedure in PHP development. Another important activity is the backup and transfer of databases.

In this article, I will explain how to save tables from CSV files to MySQL and vice versa. You need to signup at Cloudways to launch a server and PHPstack application. Before signing up, looking at all the pricing options from the world-class hosting providers like AWS, DigitalOcean, Linode, Vultr and GCP is a good idea so you can find the one that perfectly fits your needs.

PHP Hosting: Best PHP 7 & PHP 5.6 Web Hosting

Create a Database in MySQL

The first step in this tutorial is the creation of a MySQL database. Since Cloudways provides the custom mysql manager in the platform which contains a database for app. you can create tables by running SQL queries. Create a table `employeeinfo` in database using the following SQL query.

CREATE TABLE employeeinfo(
emp_id VARCHAR(50) UNSIGNED PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date VARCHAR(50)
)

How to import mysqli in PHP?

This will create a new table `employeeinfo` in the database. I will use this table to insert data from the CSV file.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Create MySql Connection in PHP

For importing and exporting database in MySql will make a separate file `config.php`. Add the following code and replace the database credentials with yours. You can find your db credentials in Application Access details:

How to import mysqli in PHP?

getMessage();
    }
    return $conn;
}
?>

Related: How To Connect MySQL Database With PHP Websites

Import CSV to MySQL in PHP

After the database has been created, I next need an HTML file  that could upload CSV file. For this HTML file, I will use HTML File uploader in a simple bootstrap form.

Create a file and name it `index.php` . This is a simple form for uploading CSV file. This file will also show the results in a simple table on the same page. When the user submits the form,  all records will be saved in the database.

First, I will add Bootstrap CDN to index.php.



Next, in the `body` tag,  add the following HTML code for the Bootstrap form.




    
    
    




    

Form Name

Import

How to import mysqli in PHP?

You might notice that I have set an action to `functions.php` file. In the next step, I will create this file and add code to it. I have also include a method `get_all_records()` near the end of the file. This method fetches all the records from the database and display the records in the table on the index page.

Next up, I will create `functions.php` file and add the following code in it.

 0)
		 {
		  	$file = fopen($filename, "r");
	        while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
	         {


	           $sql = "INSERT into employeeinfo (emp_id,firstname,lastname,email,reg_date) 
                   values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$getData[4]."')";
                   $result = mysqli_query($con, $sql);
				if(!isset($result))
				{
					echo "";		
				}
				else {
					  echo "";
				}
	         }
			
	         fclose($file);	
		 }
	}	 


 ?>

When the upload button is clicked, the temporary file name will be stored in memory and using the `while` loop the data is saved in $getData variable. Once the process has been completed, the data is sorted column wise and then finally inserted in the `employeeinfo` table.

Note that `fgetcsv()` parses lines from the open file, checking for CSV fields and `fopen()` opens a file or a URL. This code could be tested by importing a CSV file with test data.

Display the Saved Records

Once the CSV file has been imported, I will display the data through a simple function, `get_all_records()`, initialized in `index.php`. Copy this function to `function.php`.

function get_all_records(){
    $con = getdb();
    $Sql = "SELECT * FROM employeeinfo";
    $result = mysqli_query($con, $Sql);  


    if (mysqli_num_rows($result) > 0) {
     echo "

"; while($row = mysqli_fetch_assoc($result)) { echo ""; } echo "

EMP ID First Name Last Name Email Registration Date
" . $row['emp_id']." " . $row['firstname']." " . $row['lastname']." " . $row['email']." " . $row['reg_date']."

"; } else { echo "you have no records"; } }

In this really simple method, I simply selected all the records and displayed these records on the index page through the method. Whenever the user uploads a CSV file, the records will get saved in the table and then displayed on the index page.

Export MySQL to CSV With PHP

Exporting data from  MySQL database to a CSV file is similarly very easy. To demonstrate this, I will use the index.php that I created earlier.

Add the following code to the file.

 

After adding this HTML markup, the Export button will appear below the table. Now add the following condition in functions.php.

 if(isset($_POST["Export"])){
		 
      header('Content-Type: text/csv; charset=utf-8');  
      header('Content-Disposition: attachment; filename=data.csv');  
      $output = fopen("php://output", "w");  
      fputcsv($output, array('ID', 'First Name', 'Last Name', 'Email', 'Joining Date'));  
      $query = "SELECT * from employeeinfo ORDER BY emp_id DESC";  
      $result = mysqli_query($con, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {  
           fputcsv($output, $row);  
      }  
      fclose($output);  
 }  

When the `Export` button is clicked, the headers `Content-Type: text/csv` with an attachement `data.csv` is sent.

Since `php://output` is a write-only stream that allows write access to the output buffer mechanism, I selected all data from table in the next line, and passed it to `fputcsv()` method. This method formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file. Finally, the file with all the desired data is downloaded.

Finally, after integrating all the code, you will see the following final shape of application.

How to import mysqli in PHP?

You might also like: Simple CRUD in PHP and MySQL

Conclusion

In this article, I discussed how you could export data from and to CSV files using PHP and MySQL. This is a simple example you can Add more complex logic and validations as per your requirements. You can also create test cases to verify the code and Integerate with GitHub using PHP Continuous Integeration Tools. If you wish to add to the discussion or would like to ask a question, leave a comment below.

How do I import and export CSV using php and MySQL?

  • Approve the submitted record, whether a substantial CSV file.
  • Inspect the CSV file transfer status utilizing PHP is_uploaded_file() function.
  • Access the CSV file utilizing PHP fopen() function.
  • Parse data from the CSV record utilizing PHP fgetcsv() function.
  • Insert or updade data into the database based on the member’s e-mail.

Customer Review at

How to import mysqli in PHP?

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

How to add MySQLi to PHP?

Open your php. ini file ( php configuration file ) inside your PHP directory ( or windows directory ) . Search for mysqli and enable the dll by removing ; before it. You may have to re-boot your system.

How to install MySQLi extension in PHP?

MySQLi - Installation.
Downloading MySQL. ... .
Installing MySQL on Linux/UNIX. ... .
Installing MySQL on Windows. ... .
Verifying MySQL Installation. ... .
Use the mysqladmin Utility to Obtain Server Status. ... .
Execute simple SQL commands using MySQL Client. ... .
Post-installation Steps. ... .
Running MySQL at boot time..

Is MySQLi included in PHP?

The MySQLi extension was introduced with PHP version 5.0. 0. The MySQL Native Driver was included in PHP version 5.3.

How to enable MySQLi extension in PHP 7?

For all docker users, just run docker-php-ext-install mysqli from inside your php container.