Pull data from a txt file and Insert into a database - php

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')";

Related

Cannot insert lines into database

I have a basic database that consists of three tables :
Product(idP,name,price,quantity,stock_Minimal,stock_maximal)
Order(ref,date)
Order_Line(idP,ref,quatity)
the product table contains a catalogue of all the product available, the order table contains a list of all the orders references and their respective dates,and finally the order_line table contains informations about whats been ordered in every command
here is the code that I use to insert an order into the order table and its lines to Order_Line table:
<?php
if (isset($_POST['ref'])) {
$ref = $_POST['ref'];
$date = $_POST['date'];
$choosed_product = $_POST['choosed_product'];
$quantity = $_POST['quantity'];
$cn = mysqli_connect("localhost", "root", "");
mysqli_select_db($cn, "vente_db");
$res = mysqli_query($cn, "select * from commande where ref=" . $ref);
$cn->close();
if ($res != null) {
$cn->query("insert into Order_Line values (" . $choosed_product . ",$ref,$quantity)");
} else {
$co = mysqli_connect("localhost", "root", "");
mysqli_select_db($co, "vente_db");
mysqli_query($co, "insert into Commande
values('$ref',''$date'')");
mysqli_query($co, "insert into Order_Line values
(" . $choosed_product . ",$ref,$quantity)");
}
}
?>
But when I check the databse I don't find the inserted lines,can you please help me figure out the problem in my code
[edit]:I know that my code is vulnerable to sql injections, but this is just for a school project and we're not required to secure the database against hackers.
There are a lot of issues with this code. Your code is very much vulnerable to SQL Injection Attacks! I have commented everything inside the code:
Put connection string in the first line for making it available to use.
Add the DB selector to the connection.
Give an alternate message if connection fails.
Make sure you sanitize the data.
Optional: Make sure you backtick the column names and add single quotes for values.
This is not needed here. $cn->close();
Make sure you use the same implementation. Either OOP or Procedural.
You don't need another connection. $co = mysqli_connect("localhost", "root", ""); mysqli_select_db($co, "vente_db"); Use the previous connection.
You have an error in the SQL Syntax with double single quotes.
Add single quotes for the values.
Corrected Code:
<?php
if (isset($_POST['ref'])) {
// Put connection string in the first line for making it available to use.
// Add the DB selector to the connection.
// Give an alternate message if connection fails.
$cn = mysqli_connect("localhost", "root", "", "vente_db") or die("Cannot Connect. " . mysqli_connect_error());
// Make sure you sanitize the data.
$ref = mysqli_real_escape_string($cn, $_POST['ref']);
$date = mysqli_real_escape_string($cn, $_POST['date']);
$choosed_product = mysqli_real_escape_string($cn, $_POST['choosed_product']);
$quantity = mysqli_real_escape_string($cn, $_POST['quantity']);
// Optional: Make sure you backtick the column names and add single quotes for values.
$res = mysqli_query($cn, "select * from `commande` where `ref`='" . $ref . "'");
// This is not needed here.
// $cn->close();
if ($res != null) {
// Make sure you use the same implementation. Either OOP or Procedural.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
} else {
// You don't need another connection.
// $co = mysqli_connect("localhost", "root", "");
// mysqli_select_db($co, "vente_db");
// Use the previous connection.
// You have an error in the SQL Syntax with double single quotes.
mysqli_query($cn, "insert into `Commande` values('$ref', '$date')");
// Add single quotes for the values.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
}
}
?>
This should probably work. If not, at least it would tell you why it failed.

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

Insert data from txt file to database 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) . "')";

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"

Categories