Code Examples

Execute SQL query in PHP

programming

The following code example will demonstrate how to execute a set of SQL commands against MySQL database from your PHP code.

<?php
// define local variables
$servername = "localhost";
$username = "root";
$password = "";
$sql = "";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error){
	die("Connection failed: " . $conn->connect_error);
}

try
{
		// open file with SQL commands, in binary read mode, for maximum
		// compatibility
		$filename = __DIR__ . '/schema.sql';
    $fh = fopen($filename, 'rb');
		// read each line until the end of file
    while ($line = fread($fh, filesize($filename)))
    {
			// concatenate all file content into string variable
       $sql = $sql. $line;
    }
		// close file
    fclose($fh);

	// use multi_query here and not query,
	// to execute multiple SQL queries at once.
	if ($conn->multi_query($sql) === TRUE) {
		echo "Database created successfully";
	} else {
		echo "Error creating database: " . $conn->error;
	}
	// close database connection
	$conn->close();
}
catch(Exception $e)
{
    echo $e->getMessage();
}

?>