Related
I have two *.sql files that I use when creating a new web site database. The first file creates all the tables. The second file populates some default records. I would like to execute these files from PHP. I also use the Zend_Framework, if that will help accomplish this.
Additional Info
I don't have console access
I'm trying to automate site generation from within our application.
SOLUTION
Using shell_exec()...
$command = 'mysql'
. ' --host=' . $vals['db_host']
. ' --user=' . $vals['db_user']
. ' --password=' . $vals['db_pass']
. ' --database=' . $vals['db_name']
. ' --execute="SOURCE ' . $script_path
;
$output1 = shell_exec($command . '/site_db.sql"');
$output2 = shell_exec($command . '/site_structure.sql"');
...I never did get useful output, but followed some suggestions on another thread and finally got it all working. I switch to the --option=value format for the commands and used --execute="SOURCE ..." instead of < to execute the file.
Also, I never got a good explanation of the difference between shell_exec() and exec().
This question comes up from time to time. There's no good solution for running a .sql script directly from PHP. There are edge cases where statements common in a .sql script can't be executed as SQL statements. For example, the mysql tool has builtin commands that are not recognized by the MySQL Server, e.g. CONNECT, TEE, STATUS, and DELIMITER.
So I give +1 to #Ignacio Vazquez-Abrams's answer. You should run your .sql script in PHP by invoking the mysql tool, for instance with shell_exec().
I got this test working:
$command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
. "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";
$output = shell_exec($command . '/shellexec.sql');
See also my answers to these related questions:
Loading .sql files from within PHP
is it possible to call a sql script from a stored procedure in another sql script?
PHP: multiple SQL queries in one mysql_query statement
$commands = file_get_contents($location);
$this->_connection->multi_query($commands);
You'll need to create a full SQL parser for this. I recommend you use the mysql command line tool for this instead, invoking it externally from PHP.
Here is what I use:
function run_sql_file($location){
//load file
$commands = file_get_contents($location);
//delete comments
$lines = explode("\n",$commands);
$commands = '';
foreach($lines as $line){
$line = trim($line);
if( $line && !startsWith($line,'--') ){
$commands .= $line . "\n";
}
}
//convert to array
$commands = explode(";", $commands);
//run commands
$total = $success = 0;
foreach($commands as $command){
if(trim($command)){
$success += (#mysql_query($command)==false ? 0 : 1);
$total += 1;
}
}
//return number of successful queries and total number of queries found
return array(
"success" => $success,
"total" => $total
);
}
// Here's a startsWith function
function startsWith($haystack, $needle){
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
I have never had to use it but the mysqli class has a multi_query method:
http://php.net/manual/en/mysqli.multi-query.php
I know I'm pretty late to the party but PHP Mini Admin has been a lifesaver on a couple of occasions. It's basically a "lite" PHPMyAdmin all contained in one file so no need for complicated installs, just upload it and log in. Simples!
Don't forget about phpMyAdmin. Pretty solid interface for interacting with MySQL.
I don't know if it solves your problem, since I don't know if you can interact with it directly from code, but just wanted to throw it out there.
You can use this script to run MySQL script files. You'll need to set $hostName, $userName, $password, $dataBaseName, $port and $fileName of course.
<?php
function parseScript($script) {
$result = array();
$delimiter = ';';
while(strlen($script) && preg_match('/((DELIMITER)[ ]+([^\n\r])|[' . $delimiter . ']|$)/is', $script, $matches, PREG_OFFSET_CAPTURE)) {
if (count($matches) > 2) {
$delimiter = $matches[3][0];
$script = substr($script, $matches[3][1] + 1);
} else {
if (strlen($statement = trim(substr($script, 0, $matches[0][1])))) {
$result[] = $statement;
}
$script = substr($script, $matches[0][1] + 1);
}
}
return $result;
}
function executeScriptFile($fileName, $dbConnection) {
$script = file_get_contents($scriptFleName);
$statements = parseScript($script);
foreach($statements as $statement) {
mysqli_query($dbConnection, $statement);
}
}
$hostName = '';
$userName = '';
$password = '';
$dataBaseName = '';
$port = '';
$fileName = '';
if ($connection = #mysqli_connect($hostName, $userName, $password, $dataBaseName, $port)) {
executeScriptFile($fileName, $connection);
} else {
die('Can not connect to MySQL');
}
I created a migration script with multi_query. It can process mysqldump output and phpmyadmin exports without mysql command line tool. I also made some logic to process multiple migration files based on timestamp stored in DB like Rails. I know it needs more error handling but currently does the work for me.
Check it out: https://github.com/kepes/php-migration
I think if you don't process user input with it only scripts made by developers or export tools you can use it safely.
Here is my solution and the below code explains what is does.
The principle is to read the file line by line, build a query and execute each of them. I saw many solutions using the "file_get_contents" which is not a good solution because it could cause a buffer issue as it read the whole file contents to string variable.
My solution takes also into account TRIGGERs' queries.
There's no array allocation, comment and empty lines are stripped.
<?php
/**
* Get a connection from database
* #param type $db_host database hostname
* #param type $db_user database username
* #param type $db_password database password
* #param type $db_name database name
* #return \PDO
*/
function get_db_connection($db_host, $db_user, $db_password, $db_name)
{
$dns = "mysql:host=$db_host;dbname=$db_name";
try
{
return new PDO($dns, $db_user, $db_password);
} catch (PDOException $ex)
{
return null;
}
}
/**
* Runs SQL queries from file
*/
function exec_sql_queries_from_file($script_file, $db_host, $db_user, $db_password, $db_name)
{
// to increase the default PHP execution time
set_time_limit ( 60 ); // Max time = 60 seconds
// Connect to database
$connection = get_db_connection($db_host, $db_user, $db_password, $db_name);
// If the connection is acquired
if($connection != null){
// Open sql file
$f = fopen($script_file, 'r');
// sql query
$query = '';
// Default delimiter for queries
$delimiter = ';';
// read line by line
while (!feof($f))
{
$line = str_replace(PHP_EOL, '', fgets($f)); // read a line and remove the end of line character
/* if the current line contains the key word 'DELIMITER'. Ex: DELIMITER ;; or DELIMITER $$
* mostly used for TRIGGERS' queries
*/
if(strpos($line, 'DELIMITER') !== false)
{
// change the delimiter and read the next line
$delimiter = str_replace('DELIMITER ', '', $line);
continue;
}
// Consider the line as part of a query if it's not empty and it's not a comment line
if (!empty($line) && !starts_with($line, '/*') && !starts_with($line, '--'))
{
// the query hasn't reach its end: concatenate $line to $query if $line is not a delimiter
$query .= $line !== $delimiter ? $line : '';
// if the current line ends with $delimiter: end of current query
if (ends_with($line, $delimiter))
{
// exec the query
$connection->exec($query) or die($connection->errorInfo());
// start new query
$query = '';
}
}
}
fclose($f);
}
}
/**
* Starts with function
*/
function starts_with($haystack, $needle)
{
return $haystack{0} === $needle{0} ? stripos($haystack, $needle) === 0 : false;
}
/**
* Ends with function
*/
function ends_with($haystack, $needle)
{
$pos = stripos($haystack, $needle);
return $pos === FALSE ? FALSE : substr($haystack, $pos) === $needle;
}
To execute table generation from within the application, you may want to create a php file that will do just that when you run it.
$hostname = "localhost";
$database = "databasename";
$username = "rootuser";
$UserPassword = "password";
$myconnection = mysql_pconnect($hostname, $username , $UserPassword) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_connect($hostname , $username , $UserPassword ) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if ( !$myconnection ){ echo "Error connecting to database.\n";}
$userstableDrop = " DROP TABLE IF EXISTS `users`";
$userstableCreate = " CREATE TABLE IF NOT EXISTS `users` (
`UserID` int(11) NOT NULL,
`User_First_Name` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15" ;
$userstableInsert = "INSERT INTO `users` (`UserID`, `User_First_Name`) VALUES
(1, 'Mathew'),
(2, 'Joseph'),
(3, 'James'),
(4, 'Mary')";
$userstableAlter1 = "ALTER TABLE `users` ADD PRIMARY KEY (`UserID`)";
$userstableAlter2 = " ALTER TABLE `users` MODIFY `UserID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15";
$createDb_sql = $userstableDrop;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableCreate;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableInsert;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableAlter1;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableAlter2;
$insertSite = mysql_query($createDb_sql);
echo "Succesful!";
mysql_close($myconnection );
Just wanna to add to #Bill Karwin answer given above.
You can import | reinitialize | execute custom SQL; the database using sql script file, by simply clicking on button. That button would execute the sql script file using ajax.
eg.
Front end code
<input type="button" value="Execute SQL Script" id="btnExecuteScript" />
<input type="button" value="reset" onclick="clearDiv('divExecuteScript')" />
<div id="divExecuteScript" style='display: none'></div>
<br />
Jquery code calling the ajax
$('#btnExecuteScript').click(function (event) {
if ($('#divExecuteScript').html() == '') {
$('#divExecuteScript').html("<b style='font-family: sans-serif;font-size: larger'>Please Wait, It might take a few minutes</b>");
$('#divExecuteScript').show();
$.get("../controller/Controller.php?executeScript=TRUE", function (data) {
// alert("$" + data + "$");
$('body').css('cursor', 'default');
$('#divExecuteScript').html(data);
$('#divExecuteScript').show();
});
} else
$('#divExecuteScript').toggle();
});
connection file
class Conn {
protected $databaseURL; // const
protected $databaseName;
protected $databaseUName;
protected $databasePWord;
public $mysqli;
public function __construct($args = null) {
if (stripos($_SERVER['SERVER_NAME'], "localhost") !== FALSE) {
$this->databaseURL = "host";
$this->databaseName = "database";
$this->databaseUName = "user";
$this->databasePWord = "password";
}
$this->mysqli = new mysqli($this->databaseURL, $this->databaseUName, $this->databasePWord, $this->databaseName) or die('Could not connect to the database server' . mysqli_connect_error());
if (empty($this->mysqli))
die("Error while connecting to host");
}
function get_databaseURL() {
return $this->databaseURL;
}
function get_databaseUName() {
return $this->databaseUName;
}
function get_databasePWord() {
return $this->databasePWord;
}
function get_databaseName() {
return $this->databaseName;
}
}
controller code executing the command
$con = new Conn();
$mysqli = new mysqli($con->get_databaseURL(), $con->get_databaseUName(), $con->get_databasePWord(), $con->get_databaseName()) or die('Could not connect to the database server' . mysqli_connect_error());
if (isset($_GET['executeScript'])) {
$script_path = '/path-to-script-file/filename.sql';
$command = "mysql --user={$con->get_databaseUName()} --password='{$con->get_databasePWord()}' "
. "-h {$con->get_databaseURL()} -D {$con->get_databaseName()} < {$script_path}";
$output = shell_exec($command);
if (!empty($output))
echo "<b style='font-family: sans-serif;font-size: large'>Execute the SQL script<br />";
else
echo "<b style='font-family: sans-serif;font-size: large'>Unable to execute the SQL script</b><br />";
return;
}
PHP Code
The code I found on this page worked for me.
(Scroll down to see the commented version)
<?php
$conn = new mysqli('localhost', 'root', '' , 'sql_auto_test_table');
$query = '';
$sqlScript = file('sqlFileName.sql');
foreach ($sqlScript as $line) {
$startWith = substr(trim($line), 0 ,2);
$endWith = substr(trim($line), -1 ,1);
if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
continue;
}
$query = $query . $line . "/*<br>*/";
if ($endWith == ';') {
mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
$query= '';
}
}
echo '<div>SQL file imported successfully</div>';
?>
Potential Fixes
I tested this file with a WordPress database exported to SQL using phpMyAdmin and it worked fine. I had to add the following lines at the top of the .sql file to avoid a few DEFAULT VALUE errors in some DATE columns. Alternatively, you can try executing the following queries before executing your SQL file if you receive a similar error.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
In addition, substitute the violent die() function with a better error-handling mechanism.
Explanation
In case you want, I added a few comment lines to explain the behavior.
<?php
$conn = new mysqli('localhost', 'root', '' , 'db_name');
$query = ''; //Set an empty query variable to hold the query
$sqlScript = file('mySqlFile.sql'); //Set the sql file location
//Read each line of the file
foreach ($sqlScript as $line) {
//Get the starting character and the ending character of each line
$startWith = substr(trim($line), 0 ,2);
$endWith = substr(trim($line), -1 ,1);
//Check for empty or comment lines. (If the line starts with --,/*,// or the line is empty, skip to the next line)
if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
continue;
}
//Add the line to the query. (Additional optional commented out <br> tag added to query for easy error identification)
$query = $query . $line . "/*<br>*/";
//If the line end with a ";" assume the last query has ended in this line
if ($endWith == ';') {
//Therefore, try to execute the query. Upon failure, display the last formed query with the SQL error message
mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
//Reset the query variable and continue to loop the next lines
$query= '';
}
}
//If nothing went wrong, display a success message after looping through all the lines in the sql file
echo '<div>SQL file imported successfully</div>';
/*
If failed with an invalid DEFAULT value for a DATE column error, try adding the following lines to the top of your SQL file. Otherwise, execute these lines before executing your .sql file.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
*/
?>
I found the easy solution, that's works for me
$new_conn=mysqli_connect("localhost","db_user","pass","db_name");
$quries=file_get_contents("db_backup.sql");
$res=mysqli_multi_query($new_conn,$quries);
One suggestion:
// connect to db.
if (mysql_query("SOURCE myfile.sql")) {
echo "Hello Sonny";
}
I try this solution to import large SQL file in mysql database using PHP script. I use mysqli instead of mysql. But this error appears:
previous error: Error performing query '/*!40101 SET
#OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
I know for sure that SQL file is fine and the problem is in my script:
// SQL import
// your config
$filename = 'auct_lots_full.sql';
$maxRuntime = 8; // less then your max script execution limit
$deadline = time()+$maxRuntime;
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro
$con = mysqli_connect("localhost", "xxxx", "xxxxxxxx", "asystem_db") OR die("Database selection failed: " . mysqli_error($con));
mysqli_select_db($con, "asystem_db") OR die("Database selection failed: " . mysqli_error($con));
($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);
// check for previous error
if( file_exists($errorFilename) ){
die('<pre> previous error: '.file_get_contents($errorFilename));
}
// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';
// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
$filePosition = file_get_contents($progressFilename);
fseek($fp, $filePosition);
}
$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
if(substr($line,0,2)=='--' OR trim($line)=='' ){
continue;
}
$query .= $line;
if( substr(trim($query),-1)==';' ){
if( !mysqli_query($con, $query) ){
$error = 'Error performing query \'<strong>' . $query . '\': ' . mysqli_error($con);
file_put_contents($errorFilename, $error."\n");
exit;
}
$query = '';
file_put_contents($progressFilename, ftell($fp)); // save the current file position for
$queryCount++;
}
}
if( feof($fp) ){
echo 'dump successfully restored!';
}else{
echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}
On my server, I am attempting to find a specific string in a database table, if that string is found, I want to check to see what an integer value is in another field of the same row and UPDATE that integer if it is needed, or exit the PHP script.
The code below is only some of what I have tried. I don't see what is incorrect with the commands, and there are no error messages produced when it is ran/called.
What happens is, if the string is found, the script automatically runs the $there query.
What do I need to do to make this work correctly?
Thank you very much.
// This script checks to see if a member name sent by the page exists in the database.
//-------------------------------------------------------------
// The database section starts here.
$servername = "localhost";
$username = "manager";
$password = "********";
$dbname = "golf_ledger";
//------------------------------
// Make a connection with the server.
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection.
if($conn === false){
die("ERROR: Couldn't connect. " . mysqli_connect_error());
}
else {
echo "The connection worked."."<br>"."<br>";
}
//------------------------------------------------------------------
// This is the test string to be searched for.
$memName = "Richardson";
//----------------------------------------
// Populate $result with the search query.
// Database name Table name
$result = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName'");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, the name was not found";
die();
}
//----------------------------------------
// Something is wrong with this one, possibly.
$there = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 1");
// "if ($there)" is the same as "if ($there == true)" in PHP.
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
//----------------------------------------
$notThere = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 0");
if ($notThere == true) {
mysqli_query($conn,"UPDATE `golf_ledger`.`member_table` SET `pay_Status` = 1 WHERE `member_table`.`name` = '$memName'");
echo "The name has been found, they have NOT paid, but the status has been updated.";
die();
}
Instead of this code:
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
try that:
// Check if found any records
if (mysqli_num_rows($there) > 0) {
echo "The name has been found, and they have paid.";
die();
}
I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)
I have two *.sql files that I use when creating a new web site database. The first file creates all the tables. The second file populates some default records. I would like to execute these files from PHP. I also use the Zend_Framework, if that will help accomplish this.
Additional Info
I don't have console access
I'm trying to automate site generation from within our application.
SOLUTION
Using shell_exec()...
$command = 'mysql'
. ' --host=' . $vals['db_host']
. ' --user=' . $vals['db_user']
. ' --password=' . $vals['db_pass']
. ' --database=' . $vals['db_name']
. ' --execute="SOURCE ' . $script_path
;
$output1 = shell_exec($command . '/site_db.sql"');
$output2 = shell_exec($command . '/site_structure.sql"');
...I never did get useful output, but followed some suggestions on another thread and finally got it all working. I switch to the --option=value format for the commands and used --execute="SOURCE ..." instead of < to execute the file.
Also, I never got a good explanation of the difference between shell_exec() and exec().
This question comes up from time to time. There's no good solution for running a .sql script directly from PHP. There are edge cases where statements common in a .sql script can't be executed as SQL statements. For example, the mysql tool has builtin commands that are not recognized by the MySQL Server, e.g. CONNECT, TEE, STATUS, and DELIMITER.
So I give +1 to #Ignacio Vazquez-Abrams's answer. You should run your .sql script in PHP by invoking the mysql tool, for instance with shell_exec().
I got this test working:
$command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
. "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";
$output = shell_exec($command . '/shellexec.sql');
See also my answers to these related questions:
Loading .sql files from within PHP
is it possible to call a sql script from a stored procedure in another sql script?
PHP: multiple SQL queries in one mysql_query statement
$commands = file_get_contents($location);
$this->_connection->multi_query($commands);
You'll need to create a full SQL parser for this. I recommend you use the mysql command line tool for this instead, invoking it externally from PHP.
Here is what I use:
function run_sql_file($location){
//load file
$commands = file_get_contents($location);
//delete comments
$lines = explode("\n",$commands);
$commands = '';
foreach($lines as $line){
$line = trim($line);
if( $line && !startsWith($line,'--') ){
$commands .= $line . "\n";
}
}
//convert to array
$commands = explode(";", $commands);
//run commands
$total = $success = 0;
foreach($commands as $command){
if(trim($command)){
$success += (#mysql_query($command)==false ? 0 : 1);
$total += 1;
}
}
//return number of successful queries and total number of queries found
return array(
"success" => $success,
"total" => $total
);
}
// Here's a startsWith function
function startsWith($haystack, $needle){
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
I have never had to use it but the mysqli class has a multi_query method:
http://php.net/manual/en/mysqli.multi-query.php
I know I'm pretty late to the party but PHP Mini Admin has been a lifesaver on a couple of occasions. It's basically a "lite" PHPMyAdmin all contained in one file so no need for complicated installs, just upload it and log in. Simples!
Don't forget about phpMyAdmin. Pretty solid interface for interacting with MySQL.
I don't know if it solves your problem, since I don't know if you can interact with it directly from code, but just wanted to throw it out there.
You can use this script to run MySQL script files. You'll need to set $hostName, $userName, $password, $dataBaseName, $port and $fileName of course.
<?php
function parseScript($script) {
$result = array();
$delimiter = ';';
while(strlen($script) && preg_match('/((DELIMITER)[ ]+([^\n\r])|[' . $delimiter . ']|$)/is', $script, $matches, PREG_OFFSET_CAPTURE)) {
if (count($matches) > 2) {
$delimiter = $matches[3][0];
$script = substr($script, $matches[3][1] + 1);
} else {
if (strlen($statement = trim(substr($script, 0, $matches[0][1])))) {
$result[] = $statement;
}
$script = substr($script, $matches[0][1] + 1);
}
}
return $result;
}
function executeScriptFile($fileName, $dbConnection) {
$script = file_get_contents($scriptFleName);
$statements = parseScript($script);
foreach($statements as $statement) {
mysqli_query($dbConnection, $statement);
}
}
$hostName = '';
$userName = '';
$password = '';
$dataBaseName = '';
$port = '';
$fileName = '';
if ($connection = #mysqli_connect($hostName, $userName, $password, $dataBaseName, $port)) {
executeScriptFile($fileName, $connection);
} else {
die('Can not connect to MySQL');
}
I created a migration script with multi_query. It can process mysqldump output and phpmyadmin exports without mysql command line tool. I also made some logic to process multiple migration files based on timestamp stored in DB like Rails. I know it needs more error handling but currently does the work for me.
Check it out: https://github.com/kepes/php-migration
I think if you don't process user input with it only scripts made by developers or export tools you can use it safely.
Here is my solution and the below code explains what is does.
The principle is to read the file line by line, build a query and execute each of them. I saw many solutions using the "file_get_contents" which is not a good solution because it could cause a buffer issue as it read the whole file contents to string variable.
My solution takes also into account TRIGGERs' queries.
There's no array allocation, comment and empty lines are stripped.
<?php
/**
* Get a connection from database
* #param type $db_host database hostname
* #param type $db_user database username
* #param type $db_password database password
* #param type $db_name database name
* #return \PDO
*/
function get_db_connection($db_host, $db_user, $db_password, $db_name)
{
$dns = "mysql:host=$db_host;dbname=$db_name";
try
{
return new PDO($dns, $db_user, $db_password);
} catch (PDOException $ex)
{
return null;
}
}
/**
* Runs SQL queries from file
*/
function exec_sql_queries_from_file($script_file, $db_host, $db_user, $db_password, $db_name)
{
// to increase the default PHP execution time
set_time_limit ( 60 ); // Max time = 60 seconds
// Connect to database
$connection = get_db_connection($db_host, $db_user, $db_password, $db_name);
// If the connection is acquired
if($connection != null){
// Open sql file
$f = fopen($script_file, 'r');
// sql query
$query = '';
// Default delimiter for queries
$delimiter = ';';
// read line by line
while (!feof($f))
{
$line = str_replace(PHP_EOL, '', fgets($f)); // read a line and remove the end of line character
/* if the current line contains the key word 'DELIMITER'. Ex: DELIMITER ;; or DELIMITER $$
* mostly used for TRIGGERS' queries
*/
if(strpos($line, 'DELIMITER') !== false)
{
// change the delimiter and read the next line
$delimiter = str_replace('DELIMITER ', '', $line);
continue;
}
// Consider the line as part of a query if it's not empty and it's not a comment line
if (!empty($line) && !starts_with($line, '/*') && !starts_with($line, '--'))
{
// the query hasn't reach its end: concatenate $line to $query if $line is not a delimiter
$query .= $line !== $delimiter ? $line : '';
// if the current line ends with $delimiter: end of current query
if (ends_with($line, $delimiter))
{
// exec the query
$connection->exec($query) or die($connection->errorInfo());
// start new query
$query = '';
}
}
}
fclose($f);
}
}
/**
* Starts with function
*/
function starts_with($haystack, $needle)
{
return $haystack{0} === $needle{0} ? stripos($haystack, $needle) === 0 : false;
}
/**
* Ends with function
*/
function ends_with($haystack, $needle)
{
$pos = stripos($haystack, $needle);
return $pos === FALSE ? FALSE : substr($haystack, $pos) === $needle;
}
To execute table generation from within the application, you may want to create a php file that will do just that when you run it.
$hostname = "localhost";
$database = "databasename";
$username = "rootuser";
$UserPassword = "password";
$myconnection = mysql_pconnect($hostname, $username , $UserPassword) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_connect($hostname , $username , $UserPassword ) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
if ( !$myconnection ){ echo "Error connecting to database.\n";}
$userstableDrop = " DROP TABLE IF EXISTS `users`";
$userstableCreate = " CREATE TABLE IF NOT EXISTS `users` (
`UserID` int(11) NOT NULL,
`User_First_Name` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15" ;
$userstableInsert = "INSERT INTO `users` (`UserID`, `User_First_Name`) VALUES
(1, 'Mathew'),
(2, 'Joseph'),
(3, 'James'),
(4, 'Mary')";
$userstableAlter1 = "ALTER TABLE `users` ADD PRIMARY KEY (`UserID`)";
$userstableAlter2 = " ALTER TABLE `users` MODIFY `UserID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15";
$createDb_sql = $userstableDrop;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableCreate;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableInsert;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableAlter1;
$insertSite = mysql_query($createDb_sql);
$createDb_sql = $userstableAlter2;
$insertSite = mysql_query($createDb_sql);
echo "Succesful!";
mysql_close($myconnection );
Just wanna to add to #Bill Karwin answer given above.
You can import | reinitialize | execute custom SQL; the database using sql script file, by simply clicking on button. That button would execute the sql script file using ajax.
eg.
Front end code
<input type="button" value="Execute SQL Script" id="btnExecuteScript" />
<input type="button" value="reset" onclick="clearDiv('divExecuteScript')" />
<div id="divExecuteScript" style='display: none'></div>
<br />
Jquery code calling the ajax
$('#btnExecuteScript').click(function (event) {
if ($('#divExecuteScript').html() == '') {
$('#divExecuteScript').html("<b style='font-family: sans-serif;font-size: larger'>Please Wait, It might take a few minutes</b>");
$('#divExecuteScript').show();
$.get("../controller/Controller.php?executeScript=TRUE", function (data) {
// alert("$" + data + "$");
$('body').css('cursor', 'default');
$('#divExecuteScript').html(data);
$('#divExecuteScript').show();
});
} else
$('#divExecuteScript').toggle();
});
connection file
class Conn {
protected $databaseURL; // const
protected $databaseName;
protected $databaseUName;
protected $databasePWord;
public $mysqli;
public function __construct($args = null) {
if (stripos($_SERVER['SERVER_NAME'], "localhost") !== FALSE) {
$this->databaseURL = "host";
$this->databaseName = "database";
$this->databaseUName = "user";
$this->databasePWord = "password";
}
$this->mysqli = new mysqli($this->databaseURL, $this->databaseUName, $this->databasePWord, $this->databaseName) or die('Could not connect to the database server' . mysqli_connect_error());
if (empty($this->mysqli))
die("Error while connecting to host");
}
function get_databaseURL() {
return $this->databaseURL;
}
function get_databaseUName() {
return $this->databaseUName;
}
function get_databasePWord() {
return $this->databasePWord;
}
function get_databaseName() {
return $this->databaseName;
}
}
controller code executing the command
$con = new Conn();
$mysqli = new mysqli($con->get_databaseURL(), $con->get_databaseUName(), $con->get_databasePWord(), $con->get_databaseName()) or die('Could not connect to the database server' . mysqli_connect_error());
if (isset($_GET['executeScript'])) {
$script_path = '/path-to-script-file/filename.sql';
$command = "mysql --user={$con->get_databaseUName()} --password='{$con->get_databasePWord()}' "
. "-h {$con->get_databaseURL()} -D {$con->get_databaseName()} < {$script_path}";
$output = shell_exec($command);
if (!empty($output))
echo "<b style='font-family: sans-serif;font-size: large'>Execute the SQL script<br />";
else
echo "<b style='font-family: sans-serif;font-size: large'>Unable to execute the SQL script</b><br />";
return;
}
PHP Code
The code I found on this page worked for me.
(Scroll down to see the commented version)
<?php
$conn = new mysqli('localhost', 'root', '' , 'sql_auto_test_table');
$query = '';
$sqlScript = file('sqlFileName.sql');
foreach ($sqlScript as $line) {
$startWith = substr(trim($line), 0 ,2);
$endWith = substr(trim($line), -1 ,1);
if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
continue;
}
$query = $query . $line . "/*<br>*/";
if ($endWith == ';') {
mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
$query= '';
}
}
echo '<div>SQL file imported successfully</div>';
?>
Potential Fixes
I tested this file with a WordPress database exported to SQL using phpMyAdmin and it worked fine. I had to add the following lines at the top of the .sql file to avoid a few DEFAULT VALUE errors in some DATE columns. Alternatively, you can try executing the following queries before executing your SQL file if you receive a similar error.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
In addition, substitute the violent die() function with a better error-handling mechanism.
Explanation
In case you want, I added a few comment lines to explain the behavior.
<?php
$conn = new mysqli('localhost', 'root', '' , 'db_name');
$query = ''; //Set an empty query variable to hold the query
$sqlScript = file('mySqlFile.sql'); //Set the sql file location
//Read each line of the file
foreach ($sqlScript as $line) {
//Get the starting character and the ending character of each line
$startWith = substr(trim($line), 0 ,2);
$endWith = substr(trim($line), -1 ,1);
//Check for empty or comment lines. (If the line starts with --,/*,// or the line is empty, skip to the next line)
if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
continue;
}
//Add the line to the query. (Additional optional commented out <br> tag added to query for easy error identification)
$query = $query . $line . "/*<br>*/";
//If the line end with a ";" assume the last query has ended in this line
if ($endWith == ';') {
//Therefore, try to execute the query. Upon failure, display the last formed query with the SQL error message
mysqli_query($conn,$query) or die('<div>Problem in executing the SQL query <b>,<br><br>' . $query. '</b><br><br>'.$conn->error.'</div>');
//Reset the query variable and continue to loop the next lines
$query= '';
}
}
//If nothing went wrong, display a success message after looping through all the lines in the sql file
echo '<div>SQL file imported successfully</div>';
/*
If failed with an invalid DEFAULT value for a DATE column error, try adding the following lines to the top of your SQL file. Otherwise, execute these lines before executing your .sql file.
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';
*/
?>
I found the easy solution, that's works for me
$new_conn=mysqli_connect("localhost","db_user","pass","db_name");
$quries=file_get_contents("db_backup.sql");
$res=mysqli_multi_query($new_conn,$quries);
One suggestion:
// connect to db.
if (mysql_query("SOURCE myfile.sql")) {
echo "Hello Sonny";
}