upload text file each line into mysql row - php

I have email.txt stored in my server the path of email.txt is
/home/xxxx/public_htnl/email.txt
email.txt consists of several thousand emails of subscriber which gets updated daily.
I want to import these emails to other database daily using cron.
I have tried this but its giving error
Could not load. Access denied for user 'test'#'localhost' (using password: YES)
I think I don't have permission to run LOAD DATA INFILE
My code is:
<?php
$db = mysql_connect('localhost', 'test', 'test')
or die('Failed to connect');
mysql_select_db('test', $db);
$string = file_get_contents("http://www.xyz.com/email.txt", "r");
$myFile = "/home/xxx/public_html/email.txt";
$fh = fopen($myFile, 'w') or die("Could not open: " . mysql_error());
fwrite($fh, $string);
fclose($fh);
$result = mysql_query("LOAD DATA INFILE '$myFile'" .
" INTO TABLE email");
if (!$result) {
die("Could not load. " . mysql_error());
}
?>
Any other good method can be accepted.please don't advice that store data directly in other database while storing emails etc..

As the root MySQL user, try running the query:
GRANT FILE on *.* to 'test'#'localhost';
If you still get the error, make sure your username and password for the test user are correct and that the host you are accessing MySQL from matches the host for the test user and password.
EDIT:
<?php
$db = mysql_connect('localhost', 'test', 'test') or die(mysql_error());
if (!mysql_select_db('test', $db)) die(mysql_error());
$emails = file("http://www.xyz.com/email.txt");
foreach($emails as $email) {
$email = trim($email);
if ($email == '' || strpos($email, '#') === false) continue;
$email = mysql_real_escape_string($email);
$query = "INSERT INTO `email` VALUES('$email')";
$result = mysql_query($query);
if (!$result) {
echo "Failed to insert $email. " . mysql_error() . "<br />\n";
}
}
If there are many, many emails, you can build an array of email addresses and do an extended insert every so often.
INSERT INTO emails VALUES('email1'), ('email2'), ('email3'), ('email4')

Related

TXT to SQL that automatically removes that line of txt once complete

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...
}

PHP - Access Denied while passing parameters through URL

I made a php script which'll echo an image if the correct password is entered; so that, nobody can access the images stored on my server directly, thus, making my server more secure. Now, for the php script I used GET method to generate a mysql_query to my database in order to check if the email and password entered by the user are associated with a relevant account and then echo the image from a folder on my server. Now, in order to pass the parameters while runtime, I'm adding them in the URL like this:
http://<mywebserver>/get_image.php/?email=<email>&password=<password>&file_name=<image-file-name>
But, something's wrong with this whole setup, and I'm getting the following error:
Warning: mysql_query() [function.mysql-query]: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO) in
/home/uXXXXXXXXX/public_html/get_image.php on line 11
Warning: mysql_query() [function.mysql-query]: A link to the server
could not be established in /home/uXXXXXXXXX/public_html/get_image.php
on line 11 Error getting data: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO)
Here is my php script, get_image.php:
<?php
$file_path = "/ProfilePics/";
if(isset($_GET['email']) && isset($_GET['password']) && isset($_GET['file_name'])) {
$id = "\"" . $_GET['email'] . "\"";
$typed_password = "\"" . $_GET['password'] . "\"";
$file = $_GET['file_name'];
$result = mysql_query("SELECT * FROM students WHERE email = $id AND password = $typed_password") or die ("Error getting data: " . mysql_error()); //line 11
if(!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$user = array();
$user["email"] = $result["email"];
$user["password"] = $result["password"];
$pass = "\"" . $user["password"] . "\"";
if($pass == $typed_password) {
$img_path = $file_path . $file;
echo '<img src="' . $img_path . '" name = "cover" />';
} else {
echo "Incorrect password";
}
} else {
echo "Unable to find user";
}
} else {
echo "Unable to find user";
}
} else {
echo "Required field(s) is missing";
}
?>
I agree, that there are lots of other questions already on stackoverflow stating similar problems. But, I didn't find the solution(s) to those questions applicable for my code. So, any help on this will be highly appreciated. Thank you for your time!
This is because you have not connected your file get_image.php to your MySQL database. Do so as follows:
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
Simply replace the information above with the correct information.
You don't seem to be connecting to the database before you try to send queries to it.
It should like something like this:
$conn = new mysqli($servername, $username, $password, $dbname);
Taken from the example here:
http://www.w3schools.com/php/php_mysql_select.asp
Furthermore, if you care, you should consider using PDO or some other method of preventing SQL injection attacks.
SQL Injection:
https://en.wikipedia.org/wiki/SQL_injection
Information on PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
setup a database connection first:
$con = mysql_connect('server','username','password');
$rst = mysql_query('select...', $con);
remember that kind of library to access mysql is outdated.
imagine someone logging in with this password:
password = '"; DROP TABLE students;'
or something crafted better.
There are different libraries like PDO or MYSQLI that take cares of this for you.
in newer releases of php standard mysql libis deprecated and removed

Modifying Insert data into table so that it is now Update Table

Right now I am inserting blob files into a database. I have read up on the update syntax for mysql I can not figure out how to modify my code to update a row with the BLOB instead of inserting a new row with the BLOB. Could someone help me with this?
Here is my code:
<?php
// Create MySQL login values and
// set them to your login information.
$username = "root";
$password = "";
$host = "localhost";
$database = "test";
$tbl_name="members";
// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO members ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
1° You need to pass a referecence for what Data you are trying to update, like the Primary Key Id From Table.
2° Update SQL should be like it
$image = mysql_real_escape_string($unsafe_image);
$id = mysql_real_escape_string($unsafe_id);
$query = "UPDATE members SET image = '$data' WHERE id_image = $id";
$results = mysql_query($query, $link);

Import csv from Yahoo Finance into MySQL using PHP

Using Johnboy's tutorial on importing .csv files to MySQL, I tried to make a script that would take exchange rate data from Yahoo finance, and write it to the MySQL database.
<?php
//connect to the database
$host = "****"
$user = "****"
$password = "****"
$database = "****"
$connect = mysql_connect($host,$user,$password);
mysql_select_db($database,$connect);
//select the table
if ($_FILES[csv][size] > 0) {
//get the csv file
$symbol = "ZARINR"
$tag = "l1"
$file = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=$tag&s='$symbol'=x";
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO ZAR_to_INR(exchange_rate) VALUES
(
'".addslashes($data[0])."',
)
");
echo "done";
}
} while ($data = fgetcsv($handle,1000,",","'"));
//redirect
header('Location: import.php?success=1'); die;
}
else{
echo "nope";
}
?>
I added the echos in the hope that they'd tell me whether or not the script worked. It doesn't work at all. There are no error messages or anything. When I run the script by opening it in my webhost, it simply does not run.
I'd appreciate any advice on how to make this script work (or even an alternate way of solving the problem).
try using mysql debugs :
mysql_select_db($database) or die('Cant connect to database');
$result = mysql_query($query) or die('query fail : ' . mysql_error());
$connect = mysql_connect($host,$user,$password)
or die('Cant connect to server: ' . mysql_error());
to find this outputs you need to check your php error_log : where-does-php-store-the-error-log

My mysql connection returns on error?

I'm attempting to connect to an api and get a user from a donation system and then open a socket to a game to automatically give a user the amount they donated for. I need to get rid of this error:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$r' at line 1"
I can't seem to see what the problem is? Here's the script:
<?php
$tablename="CENSORED";
$DBUSER="CENSORED";
$DBPASSWORD="CENSORED";
$DBHOST="CENSORED";
?>
<?php
$urlMask = 'CENSORED';
$getUser = function($id) use ($urlMask) {
list($user) = json_decode(file_get_contents(sprintf($urlMask, $id)));
return (object) $user;
};
$user = $getUser(4087396);
$Username = $user->user->username;
$Rank = $user->item_name;
$IGN = $user->custom_field;
echo '<center> Your username is '.$IGN.' correct? </center> ';
?>
<?php
if(isset($_POST['Clickbutton'])){
$con = mysql_connect($DBHOST,$DBUSER,$DBPASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($tablename, $con);
$sql="SELECT IGN FROM fisktable WHERE IGN='$IGN' and Rank='$Rank'" ;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
}
$result = mysql_query('$r') or die(mysql_error());
if(mysql_num_rows($result) == 1) {
echo 'That username has already been given their rank!';
} else {
$HOST = "77.45----"; //the ip of the bukkit server
$password = "chdfxfdxh";
//Can't touch this:
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, 4445)
or die("error: could not connect to host\n");
//Authentification
socket_write($sock, $command = md5($password)."<Password>", strlen($command) + 1)
or die("error: failed to write to socket\n");
//Begin custom code here.
socket_write($sock, $command = "/Command/ExecuteConsoleCommand:pex user ($IGN) group set ($Rank);", strlen($command) + 1) //Writing text/command we want to send to the server
or die("error: failed to write to socket\n");
socket_write($sock, $command = "Thanks, ($IGN) for donating to the ($Rank) rank! ;", strlen($command) + 1)
or die("error: failed to write to socket\n");
mysql_select_db($tablename, $con);
$sql="INSERT INTO $tablename(IGN,Rank) VALUES ('$IGN','$Rank')" ;
exit();
}}
?>
<center>
<form method="POST">
<input name="Clickbutton" type="submit" value="Yes! I would like to receive my rank!"/>
</form>
</center>
I'm trying to check if the user has been already given their rank and items by adding them to a database when their given their items. And then if they try to do it twice they will get an error saying that they have already been given their rank!
If you see any other problems or potental problems feel free to point them out.
Thanks!
Basic PHP syntax error:
$result = mysql_query('$r') or die(mysql_error());
^--^--- remove the quotes
single quoted strings do not interpolate values. You're passing a literal $ and r to mysql as a query.

Categories