retrieve variables in a txt of multiple values in php - php

content in txt file:
<test#test.com>: connect to test.com[00.00.00.0]:0: Connection timed out
recipient=test#test.com
offset=00000
status=0.0.0
action=delayed
reason=connect to test.com[00.00.00.0]:0: Connection timed out
<test234#test234.com>: connect to e-mail.com[00.00.00.0]:0: Connection timed out
recipient=test234#test234.com
offset=00000
status=0.0.0
action=delayed
reason=connect to test234.com[00.00.00.0]:0: Connection timed out
I need to get in variables in the txt file:
for example:
$email = test234#test234.com
$content = : connect to e-mail.com[00.00.00.0]:0: Connection timed out
recipient=test234#test234.com
offset=00000
status=0.0.0
action=delayed
reason=connect to test234.com[00.00.00.0]:0: Connection timed out
I try but not working
<?php
$connect = mysql_connect('localhost','root','');
if(!$connect)
{
die('Could not connect:' . mysql_error());
}
mysql_select_db('test',$connect);
// txt file
$file = fopen("email_errors.txt", "r") or exit ("Unable to open file");
while ( ($line = fgets($file)) !== false) {
// get the email <email#email.com>
preg_match_all('/\<(.+)\>/', $line, $coincidencias);
foreach ($coincidencias[1] AS $email)
{
// create a query and insert into database
$sql = "INSERT INTO errormailer(id_error, email, description, fecha) VALUES(NULL,'".$email."',' $description (the description)',now());";
echo '<pre>'.$sql. '</pre>';
mysql_query($sql);
}
}
I can not find the right way how to do it
I need to get them in variables for storage in databases.

$connect = mysql_connect('localhost','root','');
if(!$connect)
{
die('Could not connect:' . mysql_error());
}
mysql_select_db('test',$connect);
// txt file
$file = fopen("email_errors.txt", "r") or exit ("Unable to open file");
$i = 0;
while ( ($line = fgets($file)) !== false) {
// get the email <email#email.com>
if (preg_match('/\<(.+)\>/', $line, $email)) {
$coincidencias[] = $email[1];
}
if (strlen(trim($line)) > 0) {
$still_empty = false;
$content[$i] .= preg_replace('/\<.+\>: /', '', $line);
} else {
if (!$still_empty) {
$i++;
}
$still_empty = true;
}
}
$i = 0;
foreach ($coincidencias as $email)
{
// create a query and insert into database
$sql = "INSERT INTO errormailer(id_error, email, description, fecha) VALUES(NULL,'".$email."','".$content[$i]."',now());";
echo '<pre>'.$sql.'</pre>';
$i++;
mysql_query($sql);
}

Related

Sending result of mysql select query from php to python through a tcp socket

I'm trying to send the result of my MYSQL select query to my Rpi server using PHP through the TCP socket.
Here is the PHP code:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "fyp_lora";
$host = "localhost";
$port = 12345;
$f = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($f, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec'
=> 500000));
$s = socket_connect($f, $host, $port);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM led_control";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
echo $row["ID"]. ",". $row["LED"]. "," . $row["Status"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
foreach($data as $value)
{
$msg= $value["ID"]. ",". $value["LED"]. "," . $value["Status"] . "<br>";
$len = strlen($msg);
while (true) {
print($msg);
$sent = socket_write($f, $msg, $len);
if ($sent === false) {
break;
}
// Check if the entire message has been sent
if ($sent < $len) {
// If not send the entire message.
// Get the part of the message that has not yet been sent as message
$msg = substr($msg, $sent);
// Get the length of the not sent part
$len -= $sent;
} else {
socket_close($f);
break;
}
}
}
?>
</body>
</html>
Here is the python code as referenced by:
Sending a message from PHP to Python through a socket
import socket
s = socket.socket()
host = "localhost"
port = 12345
s.bind((host, port))
s.listen(5) #allows for 5 connections to be established
while True:
c, addr = s.accept()
data = c.recv(1024)
if data: print (str(data.decode().split(",")))
c.close() #closes the socket
On the Rpi server, it will only receive the 1st row of the message for example: ['1', 'LED 1', 'OFF'] but it does not receive the rest of the message.
The full message would be as follows:
1,LED 1,OFF
2,LED 2,OFF
3,LED 3,OFF
4,LED 4,ON
I would greatly appreciate any help given :)
The reason only your first line is being received is because you are calling socket_close() after each line is sent in your loop to write data to the socket. This means that the socket is no longer available to socket_write() for subsequent passes of the loop for the remaining lines.
Given that you're just running this on your Raspberry Pi, you could do the following as a quick and dirty fix:
foreach ($data as $value) {
$msg= $value["ID"]. ",". $value["LED"]. "," . $value["Status"] . "\n";
$len = strlen($msg);
$connected = socket_connect($f, $host, $port);
if ($connected) {
while (true) {
$sent = socket_write($f, $msg, $len);
if ($sent === false) {
break;
}
if ($sent < $len) {
$msg = substr($msg, $sent);
$len -= $sent;
} else {
break;
}
}
socket_close($f);
}
}

MySQL replace database

I have a .sql file and want to replace the already existing database by clicking a button. Everything works fine. Except the create query. Is there any query or command to import whole databases?
$filename = 'file.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'user';
// MySQL password
$mysql_password = 'pw';
// Database name
$mysql_database = 'dbName';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
$drop_db = "DROP DATABASE dbName";
mysql_query($drop_db) or die ("error");
$create_db = "";
I got it. The solution is to drop the tables not the whole database.
function resetClient() {
$erg = false;
try {
// get all tablenames
$sql = "SHOW TABLES FROM dbName";
$res = $this->conn->query($sql);
$this->conn->query("SET FOREIGN_KEY_CHECKS=0");
// drop all tables in db
if (is_object($res)) {
if (($res->num_rows > 0)) {
while ($row = $res->fetch_row()) {
$this->conn->query ("DROP TABLE " . $row[0]);
}
}
}
$this->conn->query("SET FOREIGN_KEY_CHECKS=1");
//pause
time_nanosleep(0, 250000000);
// create tables from script
$sql = file_get_contents('./scripts/file.sql');
$this->conn->multi_query($sql);
$erg = true;
error_log(date("Y-m-d H:i:s")." - DB resetted\n", 3,
"./scripts/success.log");
} catch (Exception $e) {
// log
error_log(date("Y-m-d H:i:s")." - DB error\n"
. "resetClientDB() \n"
. "Reset error \n"
. $e->getMessage() . "\n" , 3,
"./scripts/error.log");
}
return $erg;
}
You could try something like:
$cmds=array_filter( file( $filename ) );
foreach( $cmds as $cmd ){
echo $cmd;
}
If that looks ok substitute the echo for mysql_query( $cmd )... totally untested btw.
$sql=array();
$sourcefile='C:\data\db_20101222_0957.sql';
$cmds = file( $sourcefile, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES );
foreach( $cmds as $cmd ){
if ( substr( $cmd, 0, 2) == '--' || $cmd == '' || substr( $cmd,0, 2)=='/*' ) continue;
$sql[]=$cmd;
if ( substr( trim( $cmd ), -1, 1 ) == ';' ){
/* Query */
$query=implode( PHP_EOL, $sql );
/* Execute query */
echo '<pre>',$query,'</pre>';
$sql=array();
}
}

TCP server not responding after the first connection

I have a TCP server, which listens for incoming messages(data/requests) and replies accordingly. However, it does not reply after the first connection. If its a data message, the data is inserted into the database, but the confirmation message does not reach the client. And, there is no response if its a data request message. When I restart the server, it replies correctly only to the first incoming connection. Henceforth, there is no response from server to client.
I have attached my code, please suggest what can be done to correct the issue.
/**
* Settings
*/
$listen_address = "0.0.0.0";
$listen_port = ****;
$mysql_server = "localhost";
$mysql_username = "root";
$mysql_password = "*****";
$mysql_database = "*****";
/**
* End Settings
*/
function socketError($errorFunction, $die=false) {
$errMsg = socket_strerror(socket_last_error());
echo("{$errorFunction}() error: $errMsg");
if ($die) {
exit();
}
}
function doQuery($query) {
global $db, $mysql_server, $mysql_username, $mysql_password, $mysql_database, $thread_id;
if (0) echo "Trying query: $query\n";
if(!($res = mysqli_query($db, $query))) {
#mysqli_kill($db, $thread_id);
#mysqli_close($db);
$db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database);
if(mysqli_connect_errno()) {
echo("\r\nFailed to connect to MySQL: " . mysqli_connect_error());
}
if(!($res = mysqli_query($db, $query))) {
echo("Error: " . mysqli_error($db) . "\n");
}
}
return $res;
}
function logMessage($socket, $msg) {
global $db, $mysql_server, $mysql_username, $mysql_password, $mysql_database, $thread_id;
$get_ip = socket_getpeername($socket, $address);
echo("Received ({$address}): {$msg}\n");
// process update:<pid>:<sid>! request
// the response is sent in format: d_id:value<uptill the first comma>,
// in case of multiple rows, they are separated by LF character (\n)
if (preg_match('/^update:([0-9]+):([0-9]+)!/', $msg, $matches)) {
$pid = $matches[1];
$sid = $matches[2];
$res = doQuery("SELECT d_id FROM devices WHERE project_id = $pid AND subproject_id = $sid");
if ($res) {
if (mysqli_num_rows($res) > 0) {
$output = '';
$i = 0;
while ($r = mysqli_fetch_array($res)) {
$res2 = doQuery("SELECT tt.d_id, tt.field_a, tt.value FROM data tt INNER JOIN (SELECT d_id, MAX(update_time) AS MaxDateTime FROM data WHERE d_id = {$r['d_id']} GROUP BY d_id) groupedtt ON tt.d_id = groupedtt.d_id AND tt.update_time = groupedtt.MaxDateTime");
if ($res2) {
if (mysqli_num_rows($res2) > 0) {
while ($r2 = mysqli_fetch_array($res2)) {
$tmp = explode(',', $r2['value'], 2);
$output .= ($i>0?"\n":'').$r2['d_id'].':'.$r2['field_a'].':'.$tmp[0].',';
++$i;
}
}
}
}
return $output;
}
}
}
else {
// Ensure nothing breaks our query
$msg = str_replace("'", "\'", $msg);
$parts = explode(':', $msg);
if (is_numeric($parts[0])) {
//if(!mysqli_query($db, "INSERT INTO data (data, datetime, receiver) VALUES ('{$msg}', '".time()."', '".$address."')")) {
doQuery("INSERT INTO data (sender, d_id, value, update_time, field_a) VALUES ('".$address."', {$parts[0]}, '{$parts[2]}', '".date("Y-m-d H:i:s")."','{$parts[1]}')");
return "yes\n";
}
else return "no\n";
}
}
function sendData($socket, $message) {
socket_write($socket, $message);
}
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
ignore_user_abort(true);
// Stage 1: MySQL Connection
$db = mysqli_connect($mysql_server, $mysql_username, $mysql_password, $mysql_database);
if(mysqli_connect_errno()) {
echo("\r\nFailed to connect to MySQL: " . mysqli_connect_error());
}
else
$thread_id = mysqli_thread_id($db);
// Stage 2: start listening
if(!($server = #socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
socketError("socket_create", true);
}
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
if(!#socket_bind($server, $listen_address, $listen_port)) {
socketError("socket_bind", true);
}
if(!#socket_listen($server)) {
socketError("socket_listen", true);
}
$allSockets = array($server);
echo("Listening on port {$listen_port}\n");
// Stage 3: accept clients
while (true) {
if(connection_aborted()) {
foreach($allSockets as $socket) {
socket_close($socket);
}
break;
}
$changedSockets = $allSockets;
#socket_select($changedSockets, $write = NULL, $except = NULL, 5);
foreach($changedSockets as $socket) {
if ($socket == $server) {
if(!($client = #socket_accept($server))) {
socketError("socket_accept", false);
} else {
$allSockets[] = $client;
}
} else {
$data = socket_read($socket, 2048);
if ($data === false || $data === '') {
unset($allSockets[array_search($socket, $allSockets)]);
socket_close($socket);
} else {
if(trim($data != "")) {
$response = logMessage($socket, $data);
sendData($socket, $response);
}
}
}
}
}
?>

How do I import a .sql file in mysql database using PHP?

I'm trying to import a .sql file through PHP code. However, my code shows this error:
There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:
MySQL Database Name: test
MySQL User Name: root
MySQL Password: NOTSHOWN
MySQL Host Name: localhost
MySQL Import Filename: dbbackupmember.sql
And this is my code:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
exec($command,$output=array(),$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:<br/><br/><table><tr><td>MySQL Database Name:</td><td><b>' .$mysqlDatabaseName .'</b></td></tr><tr><td>MySQL User Name:</td><td><b>' .$mysqlUserName .'</b></td></tr><tr><td>MySQL Password:</td><td><b>NOTSHOWN</b></td></tr><tr><td>MySQL Host Name:</td><td><b>' .$mysqlHostName .'</b></td></tr><tr><td>MySQL Import Filename:</td><td><b>' .$mysqlImportFilename .'</b></td></tr></table>';
break;
}
?>
What am I doing wrong? The SQL file is in the same directory.
Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
I have got another way to do this, try this
<?php
// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dump';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysql_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>
This is working for me
You can use the mysqli multi_query function as below:
$sql = file_get_contents('mysqldump.sql');
$mysqli = new mysqli("localhost", "root", "pass", "testdb");
/* execute multi query */
$mysqli->multi_query($sql);
Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
the answer from Raj is useful, but (because of file($filename))
it will fail if your mysql-dump not fits in memory
If you are on shared hosting and there are limitations like 30 MB and 12s Script runtime and you have to restore a x00MB mysql dump, you can use this script:
it will walk the dumpfile query for query, if the script execution deadline is near, it saves the current fileposition in a tmp file and a automatic browser reload will continue this process again and again ...
If an error occurs, the reload will stop and an the error is shown ...
if you comeback from lunch your db will be restored ;-)
the noLimitDumpRestore.php:
// your config
$filename = 'yourGigaByteDump.sql';
$dbHost = 'localhost';
$dbUser = 'user';
$dbPass = '__pass__';
$dbName = 'dbname';
$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
mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
($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( !mysql_query($query) ){
$error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
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!';
}
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "demo1"; //Change Your Database Name
$conn = new mysqli($host, $uname, $pass, $database);
$filename = 'users.sql'; //How to Create SQL File Step : url:http://localhost/phpmyadmin->detabase select->table select->Export(In Upper Toolbar)->Go:DOWNLOAD .SQL FILE
$op_data = '';
$lines = file($filename);
foreach ($lines as $line)
{
if (substr($line, 0, 2) == '--' || $line == '')//This IF Remove Comment Inside SQL FILE
{
continue;
}
$op_data .= $line;
if (substr(trim($line), -1, 1) == ';')//Breack Line Upto ';' NEW QUERY
{
$conn->query($op_data);
$op_data = '';
}
}
echo "Table Created Inside " . $database . " Database.......";
?>
<?php
system('mysql --user=USER --password=PASSWORD DATABASE< FOLDER/.sql');
?>
Grain Script is superb and save my day. Meanwhile mysql is depreciated and I rewrote Grain answer using PDO.
$server = 'localhost';
$username = 'root';
$password = 'your password';
$database = 'sample_db';
/* PDO connection start */
$conn = new PDO("mysql:host=$server; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
/* PDO connection end */
// your config
$filename = 'yourFile.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
($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)==';' ){
$igweze_prep= $conn->prepare($query);
if(!($igweze_prep->execute())){
$error = 'Error performing query \'<strong>' . $query . '\': ' . print_r($conn->errorInfo());
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!';
}
I have Test your code, this error shows when you already have the DB imported or with some tables with the same name, also the Array error that shows is because you add in in the exec parenthesis, here is the fixed version:
<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
$output=array();
exec($command,$output,$worked);
switch($worked){
case 0:
echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
break;
case 1:
echo 'There was an error during import.';
break;
}
?>
If you need a User Interface and if you want to use PDO
Here's a simple solution
<form method="post" enctype="multipart/form-data">
<input type="text" name="db" placeholder="Databasename" />
<input type="file" name="file">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])){
$query = file_get_contents($_FILES["file"]["name"]);
$dbname = $_POST['db'];
$con = new PDO("mysql:host=localhost;dbname=$dbname","root","");
$stmt = $con->prepare($query);
if($stmt->execute()){
echo "Successfully imported to the $dbname.";
}
}
?>
Definitely working on my end. Worth a try.
If you are using PHP version 7 or higher, try below script,
// Name of the file
$filename = 'sql.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'username';
// MySQL password
$mysql_password = 'password';
// Database name
$mysql_database = 'database';
// Connect to MySQL server
$con = #new mysqli($mysql_host,$mysql_username,$mysql_password,$mysql_database);
// Check connection
if ($con->connect_errno) {
echo "Failed to connect to MySQL: " . $con->connect_errno;
echo "<br/>Error: " . $con->connect_error;
}
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line) {
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
$con->query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . $con->error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
$con->close($con);
// Import data
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);
function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
$connection = mysqli_connect($host,$uname,$pass)
or die("Database Connection Failed");
$selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected");
$templine = '';
$lines = file($filename); // Read entire file
foreach ($lines as $line){
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
mysqli_query($connection, $templine)
or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
$templine = '';
}
}
echo "Tables imported successfully";
}
// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');
function backup_tables($host,$user,$pass,$name,$tables = '*'){
$link = mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($link,$name);
//get all of the tables
if($tables == '*'){
$tables = array();
$result = mysqli_query($link,'SHOW TABLES');
while($row = mysqli_fetch_row($result))
{
$tables[] = $row[0];
}
}else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = '';
foreach($tables as $table)
{
$result = mysqli_query($link,'SELECT * FROM '.$table);
$num_fields = mysqli_num_fields($result);
$row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
$row2 = mysqli_fetch_row($row_query);
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysqli_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j < $num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", '\n', $row[$j]);
if (isset($row[$j])) {
$return.= '"'.$row[$j].'"' ;
} else {
$return.= '""';
}
if ($j < ($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
I recommend an old but still working tool bigdump
I use this code and RUN SUCCESS FULL:
$filename = 'apptoko-2016-12-23.sql'; //change to ur .sql file
$handle = fopen($filename, "r+");
$contents = fread($handle, filesize($filename));
$sql = explode(";",$contents);//
foreach($sql as $query){
$result=mysql_query($query);
if ($result){
echo '<tr><td><BR></td></tr>';
echo '<tr><td>' . $query . ' <b>SUCCESS</b></td></tr>';
echo '<tr><td><BR></td></tr>';
}
}
fclose($handle);
Solution special chars
$link=mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
//charset important
mysql_set_charset('utf8',$link);
I Thing you can Try this Code, It's Run for my Case:
<?php
$con = mysqli_connect('localhost', 'root', 'NOTSHOWN', 'test');
$filename = 'dbbackupmember.sql';
$handle = fopen($filename, 'r+');
$contents = fread($handle, filesize($filename));
$sql = explode(";", $contents);
foreach ($sql as $query) {
$result = mysqli_query($con, $query);
if ($result) {
echo "<tr><td><br></td></tr>";
echo "<tr><td>".$query."</td></tr>";
echo "<tr><td><br></td></tr>";
}
}
fclose($handle);
echo "success";
?>
function restoreDatabase($db_name,$file_path)
{
//checking valid extension file
$path_parts = pathinfo($file_path);
$ext_file = $path_parts['extension'];
$filename = $path_parts['basename'];
if($ext_file == "sql")
{
$c = new Config();
$confJson = $c->getConfig();
$conf = json_decode($confJson);
$dbhost = "127.0.0.1";
$dbuser = $conf->db_username;
$dbpwd = $conf->db_password;
$dbname = $db_name;
$dumpfile = $file_path;
$is_file = file_exists($file_path);
if($is_file == TRUE)
{
//passthru("/usr/bin/mysqldump --opt --host=$dbhost --user=$dbuser --password=$dbpwd $dbname < $dumpfile");
//passthru("tail -1 $dumpfile");
system('mysql --user='.$dbuser.' --password='.$dbpwd.' '.$db_name.' < '.$file_path);
return "Database was restored from $filename ";
}
else
{
return "Restore database was aborted due ".$filename." does not exist!";
}
}
else
{
return "Invalid file format.Require sql file to restore this ".$db_name." database. ".$filename." is not sql file format\n(eg. mybackupfile.sql).";
}
}
As we all know MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 ref so I have converted accepted answer to mysqli.
<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';
$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
echo "Tables imported successfully";
?>

php reading from a file but i take blank input in mysql

i am trying to read a file and then i am trying to inserted to mysql table
i have tried the follow and i get the te text and i display the text from the file but when i trying to inserted into the db the row is created but i have nothing inside
any help?
This is my code
<?php
$file_handle = fopen("text.htm", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line;
// make the DSN
$dsn = 'mysql:host=localhost;dbname=text;';
$user = 'text';
$password = 'text';
$name=$line;
}
try
{
$dbh = new PDO($dsn, $user, $password);
// set the error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO text (db_text)
VALUES (:name)';
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->execute();
}
catch (PDOException $e)
{
echo 'PDO Exception Caught. ';
echo 'Error with the database: <br />';
echo 'SQL Query: ', $sql;
echo 'Error: ' . $e->getMessage();
}
fclose($file_handle);
?>
I think you should change
$line = fgets($file_handle);
to
$line .= fgets($file_handle);
inside the while loop.
Also, instantiate $line with $line = ""; somewhere before the while-loop;
fgets will probably return false the last time (or an empty line or something).
try declaring $name before the while... it could be a scope problem....
$name = "";
$file_handle = fopen("text.htm", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line;
// make the DSN
$dsn = 'mysql:host=localhost;dbname=text;';
$user = 'text';
$password = 'text';
$name=$line;
}

Categories