I'm trying to make a function for a website where after you log in to, you can upload a csv file to the database into table csv. But when i try to upload the csv file it gives me the following error;
SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'server2.bhosted.nl' (111)
The code that i use is this ->
<?php
session_start();
// mysql hostname
$hostname = 'server2.bhosted.nl';
// mysql username
$username = 'username';
// mysql password
$password = 'password';
// databasename
$dbname = 'birdss';
// Get Extension of the File.
$extension= end(explode(".", basename($_FILES['file']['name'])));
// isset Determines if a variable is set and is not NULL. Set Size Limit less then 10 MB=10485760 bytes. Extension must be CSV.
if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension== 'csv')
{
// We will get csv file and save it in a $file
$file = $_FILES['file']['tmp_name'];
//$handle is a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). fopen() used to open file.
$handle = fopen($file, "r");
// We will use try{} Catch() statements here.
try {
// Database Connection using PDO
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname;", $username, $password);
// Truncate Table before insertion
$STMR = $dbh->prepare("TRUNCATE TABLE csv");
$STMR->execute();
// Prepare the statement for the insertion in the table
$STM = $dbh->prepare('INSERT INTO csv (tijd, aantal) VALUES ("'.$data['tijd'].'", "'.$data['aantal'].'")');
//Check handel is True or False
if ($handle !== FALSE)
{
// fgets() Gets a line from file pointer and read the first line from $handle and ignore it.
fgets($handle);
// While loop used here and fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
// For Executing prepared statement we will use below function
$STM->execute($data);
}
//The file pointed to by handle will be closed.
fclose($handle);
// Closing MySQL database connection
$dbh = null;
// If data inserted successfully we will redirect this page to index.php and show success message there with code 77083368
header( "location:index.php?ServerStatsAdded=77083368");
}
}
//
catch(PDOException $e)
{
die($e->getMessage());
}
}
else
{
// Error mesage id File type is not CSV or File Size is greater then 10MB.
header( "location:index.php?ServerStatsAdded=37767");
}
?>
Please help me!!
Try this way by removing second ; after $dbname variable but check your credentials again.
$hostname = 'server2.bhosted.nl';
$username = 'username';
$password = 'password';
$dbname = 'birdss';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
EDIT:
As error (111) means only listen on localhost, If you have lines like this :
skip-networking
bind-address = 127.0.0.1
In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.
Related
This question already has answers here:
Transfer in-memory data to FTP server without using intermediate file
(2 answers)
Closed 3 years ago.
I'm trying to updating a CSV file which in a external FTP server, I tried to follow the basic ftp_fput() but it's not working. File is not updating and also a blank CSV file is downloading when I run this script which is not needed. I've been trying to solve this but can't find the solution
<?php
// connect and login to FTP server
//ftp setup
$ftp_server = "ftp.test.test.co.uk";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$ftp_username='ftp_username';
$ftp_userpass='ftp_userpass';
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
//local DB setup
$servername = "localhost";
$username = "root";
$password = "TEST";
$dbname= "TEST";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//END database connection//
$sql = "SELECT sku,SUM(quantity) as quantity FROM tbl_old_books GROUP BY isbn";
$result = $conn->query($sql);
header("Content-Disposition: attachment; filename=AllOpenOrders.csv");
header("Content-Type: application/csv; ");
// file creation
$file = fopen('php://temp', 'W');
$header = array("SKU","QUANTITY");
fputcsv($file, $header);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
fputcsv($file, $row );
}
}
$remote_path = "/export/AllOpenOrders.csv";
ftp_fput($ftp_conn, $remote_path, $file, FTP_BINARY, 0);
fclose($file);
ftp_close($ftp_conn);
?>
You file handler $file points at the end of the file as you write in it. There is nothing left to write via ftp_fput.
You can reset your file pointer at the beginning of the file with rewind($file); before writing in the FTP : rewind documentation
My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.
I have a wordpress plugin that exports form entries to a txt file. So I need to write a php script to add them to a sql database as I want the submissions added to a database on a different domain (otherwise I’d just get the plugin to do it for me). I’m fine about how I get it to connect to the database, it’s just how I code it to interpret the data as the column names are always next to the field as shown.
{"Entry_ID":"235","Name":"matt","Email":"matt#gmail.com","Date":"03/10/2017"}{"Entry_ID":"236","Name":"matt","Email":"matt#btinternet.com","Date":"10/10/2017"}
Is there a way to get it to ignore the column name and only interpret the data within the “” after the : ?
Once these have been added to the sql database I would then need to get the lines removed from the txt
So far I have this but it isn't working...
$file= fopen('http://mpcreations.staging.wpengine.com/wp-content/themes/red-seal-resources/test.txt', 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$object = json_encode($data[0]);
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "INSERT INTO 'wp_forms' LINES TERMINATED BY '\n';
if (mysqli_multi_query($conn, $query)) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
Any help would be greatly appreciated.
Thank you
Each line in the txt file has JSON data? Process the txt file, parse the data and INSERT it into the database table.
$file= fopen('file.txt', 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$object = json_encode($data[0]);
// Prepare INSERT query here...
}
I'm trying to insert values extracted from a csv file to a mysql table. It runs but the table is not populated. I've tried to debug for the last XXXX but just can't see my error. Echo-ing out the values give me the correct SQL but when it comes to the INSERT - no dice.
Thanks very much for your help.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
//////////////////////////////// EDIT ////////////////////////////////////
$redirect_num = 500; // Select how many rows to insert each time before refresh.
// More rows = faster insertion. However cannot be too high otherwise it will timeout.
$filename = "ps4_emails.csv"; // The file we are going to get the data from...
$table = "`ps4_emails`";
////////////////////////////// END EDIT //////////////////////////////////
$file = file($filename);
$lines = count($file);
// Have we just redirected?
$nextline = $_GET['nextline'];
if (!isset($nextline)){
$nextline = 0;
}
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
for ($line=$nextline; $line<=$lines; $line++){
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
mysql_query($query,$db);
}
if ($line % $redirect_num){
// something needs to go here
} else {
$nextline = $line+1;
exit ('<meta http-equiv="refresh" content="0;url=texttomysqlemails.php?nextline='.$nextline.'" />');
}
echo ( $line==$lines ) ? "Done" : "";
}
?>
Put your query inside loop in order use it with variable $final_line.
Try this :
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
mysql_query($query,$db);
}
Don't use mysql_*. It's deprecated and removed from PHP 7. Use mysqli_* or PDO.
This seems like a perfect script to run from the command line PHP CLI and therefore you can forget about all the refresh complexity.
If the file is huge, like your comment suggest, loading all the file into memory may also bring you up against the PHP memory limits, so it might be better to read a line at a time rather than the whole file using fgetcsv() which is intended for reading csv files.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
}
?>
You now just run this script from the command line/terminal like
>php script.php
And it can run for minutes/hours/days with no likleyhood of blowing any limits.
I have to mention this or someone will nag me for not saying it
Please dont use the mysql_ database extension, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
When you need to upload the real file, it would also be a good idea to add a restart mechanism, so you can restart the process from whereever a problem happened or someone shut the database down for a backup or some other unforseen hiccup.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$restart_from = 0;
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
// is it a restart?
if ( file_exists('restart.txt') ) {
// its a restart
$restart_from = file_get_contents('restart.txt');
// read up the file to the last good row inserted
for ( $i=0; $i<=$restart_from; $i++ ) {
$data = fget($handle, 1000);
}
}
$upd_cnt = restart_from;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
$upd_cnt++;
file_put_contents('restart.txt', $upd_cnt);
}
?>
The above restart code is not tested, but I have used something very like this in the past very successfully. So you will have to check I have not made any silly mistakes, but it should give you an idea of how to do a restart from the last row successfully updated before a crash.
You can use LOAD DATA INFILE to insert from file.
refer http://dev.mysql.com/doc/refman/5.7/en/load-data.html
insert csv file data into mysql
I am trying ftp connections for file read.
All I want to do is
read particular ftp dir
list all its text files
and read them one by one
I am successful in listing files in given directory.
For eg: below code returns $emailfiles array with TEST.txt as one value.
But when I try to open/read the same file content using fopen/file_get_contents , it is giving the error: " Failed to open Stream "
I am able to access a file from another ftp : .38, which is public ftp.
The ftp I want to actually use is .94, for which I have full privileges, as I am able to access files from browser with same link. I'm also able to write/paste files from windows explorer.
But I am unable to read the same file from php code.
Below is my code for ftp connection and testing.
$ftp_server = "10.96.5.94";
$ftp_serverpath = "ftp://".$ftp_server;
$ftp_user_name = "myusername";
$ftp_user_pass = "mypassword";
$email_dir = "ebill";
try {
$con = ftp_connect($ftp_server);
if (false === $con) {
throw new Exception('Unable to connect');
}
$loggedIn = ftp_login($con, $ftp_user_name, $ftp_user_pass);
if (true === $loggedIn) {
echo 'Success!';
} else {
throw new Exception('Unable to log in');
}
ftp_pasv($con, true);
$emailfiles = ftp_nlist($con, $email_dir);
print_r($emailfiles);
//$filename = "ftp://10.16.0.38/ebill/TEST.txt";
$filename = "ftp://10.96.5.94/ebill/TEST.txt";
$pr = file_exists($filename);
// OR
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
Any help is greatly appreciated, Thank you.
Ok, This solved my error.
$filename = "ftp://username:password#hostname/path/to/file";
Thanks.