Insert data from txt file to database PHP - php

I have data in a .txt file.
4654664
6545645646
54564121452
564754412
5456545
I want to insert this data in db using php
<?php
$host= "localhost";
$user= "infdgfg";
$pass= "98fgfgdghf6";
$db="xxxxx";
$connect= mysql_connect($host,$user,$pass);
if (!$connect)die ("Cannot connect!");
mysql_select_db($db, $connect);
$file = fopen("oxxxkxxn.txt","r");
while(! feof($file))
{
$sql = "INSERT INTO xxxxx( xxxxx ) VALUES ('($file)')"; //Insert every read line from txt to mysql database
mysql_query($sql);
}
fclose($file);
?>
but this is not working.
(Resource id #4)
(Resource id #4)
(Resource id #4)
this error.

fopen returns a file pointer (that's your Resources).
http://php.net/manual/en/function.fopen.php
After opening your file you then need to use fgets to get the data line by line.
http://php.net/manual/en/function.fgets.php
So you would do something like:
$sql = "INSERT INTO xxxxx( xxxxx ) VALUES ('" . fgets($file) . "')";

Related

inserting json variable into database

I want to insert a json object value in mysql database using php. The object is:
{"data":[{"code":"1234",name:"nike"},{"code":"1034",name:"relexo"}]}.
The database table name is product and the fields name are code and name. How to insert this?
quick explination on how you could read a JSON file and append it to a table in the database:
<?php
//connect to DB
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
mysql_select_db("product", $con);
//read the json file contents
$jsondata = file_get_contents('empdetails.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the product details
$code = $data[code];
$name = $data[name];
//insert into mysql table
$sql = "INSERT INTO product(code, name) VALUES('$code', $name)"
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
this should be enough to get you going

Pull data from a txt file and Insert into a database

I want to pull data from a txt file called domains.txt and insert the contents of the file into a database. Below is the code i wrote but is not working.Please help me
<?php
$conn = mysql_connect("localhost","root","");
if (!$conn) {
die("Could not connect: " . mysql_error());
}
mysql_select_db("modify_domains");
$file = fopen("domains.txt", "r");
// Read line by line until end of file
while (!feof($file)) {
// Make an array using comma as delimiter
$array = explode(",",fgets($file));
$domain_name=$array[0];
$reg_email=$array[1];
$tech_email=$array[2];
$billing_email=$array[3];
$admin_email=$array[4];
$password=$array[5];
$sql = "INSERT INTO tbl_domains (domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES('".$adomain_name"','".$reg_email."',".$tech_email.",".$billing_email.",".$admin_email.",".$password.")";
mysql_query($sql,$conn) or die("Could not connect: " . mysql_error());
// use mysql insert query here
}
?>
All text fields must be separated by single quotes (like '".$reg_email."') and don't forget the point to separate text field and vars.
The query should be like that:
$sql = "INSERT INTO tbl_domains
(domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES
('".$adomain_name."','".$reg_email."','".$tech_email."','".$billing_email."','".$admin_email."','".$password."')";
All text fields must be separated with single quotes. Also you could write it like this:
$sql = "INSERT INTO tbl_domains
(domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES
('$adomain_name','$reg_email','$tech_email','$billing_email','$admin_email','$password')";

Posting Base64 encoded values in phpmyadmin from Android

In my app i am trying to post image from android to phpmyadmin i have also created php code which is here:
MyPhp.php:
<?php
$servername = "dontneedthis";
$username = "also";
$password = "dont care";
$dbname = "bla bla";
$conn =mysqli_connect('localhost', $username, $password);
$db_selected = mysqli_select_db($conn, $dbname);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$base=$_REQUEST['image'];
$filename = $_REQUEST['filename'];
$binary=base64_decode($base);
$sql = "INSERT INTO table (image) VALUES('{$binary}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i upload image from android i get an error where it is shown that he doent understand this :
INSERT INTO table (image) VALUES
And he shows a lot of symbols which i do not recognise. I have created table where is a row where you can add 100 000 symbols of TEXT I tried to add the value as blob and tried to change collation to binary nothing worked do you have any ideas?
Why doesn't anyone ever bother to properly quote their stuff?
table is a keyword in all SQL dialects I know, and hence causes a syntax error.
But for that reason, quotes and backticks have been invented.
Do this:
INSERT INTO `table` (`image`) VALUES ...
and you should have one problem less.
Also, you have to escape your $binary variable, otherwise it's gonna break your ' quotes:
$binary = mysqli_real_escape_string($conn, base64_decode($base));

Insert a plain text list to mysql table

I have a very long list in plain text which I need to insert into a table my database. Do I have to manually input each line of my plain text document or is there a way to insert long lists into independent rows in a table using a query?
I have a table with 2 columns, id and club_name, club_name is the list which is plain text in a notepad document.
You can use LOAD DATA, e.g.:
mysql> LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet
-> LINES TERMINATED BY '\r\n';
You can also use the multi-row insert syntax (if you are using InnoDB tables), like this:
INSERT INTO yourtable VALUES (1,2), (5,5), ...
You can load data into mysql using the LOAD DATA INFILE command.
Here is the documentation...
http://dev.mysql.com/doc/refman/5.1/en/load-data.html
$file = file("content.txt"); //read file line by line
foreach ($file as $val) {
if (trim($val) != '') { //ignore empty lines
mysql_query("INSERT INTO xxx SET club='" . $val . "'");
}
}
Here's a quick PDO based example, but MySQL's LOAD DATA INFILE command may be a much better option if you don't need to manipulate the source data (trim, normalise etc).
<?php
$conn = new PDO($dsn, $username, $password);
$stmt = $conn->prepare('INSERT INTO table VALUES (NULL, ?)');
foreach(file('list.txt') as $club) {
$stmt->execute(array($club));
}
Anthony.
Here is how to do it with php, mysqli and a text file that has each entry on a single line:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file("list.txt"); //read file line by line
foreach ($file as $val) {
if (trim($val) != '') { //ignore empty lines
$sql = "INSERT INTO `db`.`table` (`column`) VALUES ('$val');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
?>
This is based off of DanFromGermany's answer but updated to use mysqli.
Insert the whole notepad content to a column of type "text"

Uploading Large CSV File into Mysql Database

I want to upload large CSV document into mysql database can anyone help me out, the table consist of 10 fields but i want to upload into only 5 fields of the table without a heading. I want this done with php in the browser
$filename = $_FILES['sel_file']['tmp_name'];
<?php
if($_FILES["file"]["type"] != "application/vnd.ms-excel"){
die("This is not a CSV file.");
}
elseif(is_uploaded_file($_FILES['file']['name'])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'cbt_software';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql server');
mysql_select_db('cbt_software') or die(mysql_error());
//Process the CSV file
$handle = fopen($_FILES['file']['name'], "r");
$data = fgetcsv($handle, 1000, ";");
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$att0 = mysql_real_escape_string($data[0]);
$att1 = mysql_real_escape_string($data[1]);
$att2 = mysql_real_escape_string($data[2]);
$att3 = mysql_real_escape_string($data[3]);
$att4 = mysql_real_escape_string($data[4]);
$sql = "INSERT INTO `course_reg` (`coursecode`,`coursename`,`coursedescription`,`coursemaster`,`courselevel`)VALUES ('$att0','$att1','$att2','$att3','$att4')";
mysql_query($sql) or die(mysql_error());
}
mysql_close($link);
echo "CSV file successfully imported.";
}
else{
die("You shouldn't be here");
}
?>
At first this imported all the field from the csv into just one field in the database and after i tampered with the code it is not recognicing it a s a CSV file.
If you have the appropriate permissions, you can do so directly in MySQL with the LOAD DATA INFILE command, see http://dev.mysql.com/doc/refman/4.1/en/load-data.html or the mysqlimport utility, see http://dev.mysql.com/doc/refman/4.1/en/mysqlimport.html
Both methods will allow you to specify which columns the data should go in, for instance:
LOAD DATA INFILE 'myfile.txt' INTO TABLE 'mytable' (col1, col2, col3, ...)
or
mysqlimport --columns='col1,col2,...' tablename.csv
If you intend to do it from PHP, you should be able to read each line of the CSV file and execute an appropriate SQL INSERT query naming the appropriate columns (although that will not be as efficient as doing it directly in MySQL).
EDIT: I should add that you haven't mentioned what you've tried so far or what you're finding difficult; if you're stuck on something in particular, rather than just looking for suggestions on how to go about doing it, please update the question to say so.

Categories