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"
Related
I am trying to design a scoreboard for a project for my local youth club and would like to be able to click a button onto a wordpress page that will run a PHP script to update a value by 1 in a sql db table, then i can grab the value and display it else where.
Not too worried about passwords being used in scripts at this will only be used within the local network that nobody else has access to, have looked around and found a few bits of code but im not able to actually get it working, here's what i've got so far.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "sot";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The database name is 'sot' the table i want to update is called 'wp_sotstats' and the field within the table is 'CaptainChest' i only need this to really work with just the one entry which the id is '1'
Any thoughts?
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
Is not creating record, it updating it. For me, I will take current value from database as Select, then do ++ to it and do Update query.
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
Please wrap it in quotes and finish statement with semicolon
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')";
I have an html form, with multiple checkboxes (subjects)
When a user (student) selects the subjects ,the StudentID is stored in a MySQL table along with the selections made in separate columns but in the same table.
My question is: How can I store the student ID in a new table if the checkbox value "equals" to something, would strpos do it ?
for example:
if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
}
Full Code:
<?php
$host = 'localhost';
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
$tbl_name="courses" ;
$tbl_name="studentinfo";
$tbl_name="newtable";
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
mysqli_set_charset($dbcon, "utf8");
if (!$dbcon) {
die('error connecting to database'); }
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']); //echo $studentid;
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courses){
$cc=$cc. $courses.',';
}
}
if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
echo "$cc, trtue";
}
HTML
<form action="cdb.php" method="get">
<input name="studentid" type="text" id="studentid" maxlength="11"value="Student ID" />
<input type="checkbox" name="ckb[]" value="251000-1"/>
<input type="checkbox" name="ckb[]" value="251000-2"/>
Ok if you absolutely must ignore all good database design practices try this.
Instead of creating a comma delimited list and putting it into the newtable use the serialize() function to place the contents of $_GET['ckb'] into this new row. At least this way you can use unserialize() to get back an array which makes manipulating the data easier even if it does not make searching the database any easier.
You could replace serialise/unserialize with json_encode() and json_decode()
references:
serialize: http://php.net/manual/en/function.serialize.php
unserialize: http://php.net/manual/en/function.unserialize.php
<?php
$host = 'localhost';
// I assume you moved apache to port 8889.
// so its irrelevant to mysql connection,
// good job you are not actually using this variable anywhere
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
// fix so you have 3 variables and are not overwriting the same one
$tbl_name1="courses" ;
$tbl_name2="studentinfo";
$tbl_name3="newtable";
// remove unnecessary double quotes
$dbcon = mysqli_connect($host,$username,$password,$db_name) ;
// add some error checking that reports the actual error
if ( ! $dbcon ) {
echo 'Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error();
exit;
}
mysqli_set_charset($dbcon, "utf8");
if(isset($_GET['ckb'])) {
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$cc = serialize($_GET['ckb']);
$result = mysqli_query($dbcon,"INSERT INTO newtable
(studentid,ckb)
VALUES ('$studentid','$cc')");
if ( ! $result ) {
echo mysqli_error($dbcon);
exit;
}
}
?>
Below, total size of 'ckb' checkbox is calculated. Then. due to for loop, it will run till the total size. 'studentid' coming from the textbox. It will insert into the table till for loop condition is true.
extract($_POST);
$CKBsize=sizeof($ckb);
for($i=0;$i<$CKBsize;$i++)
{
$CourseName=$ckb[$i];
mysql_query("INSERT INTO newtable SET studentid='$studentid', ckb='$CourseName'");
}
It turns out , that using this code does in fact sort the data according to the checkbox in new and different tables
if (strpos($cc,'251000') !== false) {
$sql3="INSERT INTO newtable (studentid, ckb)
VALUES ('$studentid', '$cc')";
echo 'true';
}
However It seems I must check for the sql3 statement
if (!mysqli_query($dbcon,$sql3))
{
die('Error: ' . mysqli_error($dbcon));
}
Another mistake I had was using reserved words such as table in one of the sql statements. that fixed and the code above added solved the problem.
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));
I want to import a csv file content into a database table, I'm using this code that it works perfectly when pasting it in phpmyadmin console:
LOAD DATA LOCAL INFILE '/Applications/MAMP/htdocs/testApp/trips.csv' INTO TABLE trips FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS (type,startDate,endDate,steps,coordinates,distance)
However, when using it in a php file, I have an error:
<?php
$host = "localhost"; //Your database host server
$db = "dbTest"; //Your database name
$user = "root"; //Your database user
$pass = "root"; //Your password
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
die(mysqli_error($db));
} else {
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$sql = "LOAD DATA LOCAL INFILE '/Applications/MAMP/htdocs/testApp/trips.csv'
INTO TABLE trips
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\\n'
IGNORE 1 ROWS (type,startDate,endDate,steps,coordinates,distance)"
;
$result = mysql_query($sql, $connection);
if (mysql_affected_rows() == 1) {
$message = "The trip was successfully inserted!";
} else {
$message = "The trip insert failed";
$message .= mysql_error();
}
echo $message;
}
}
?>
=> The trip insert failed
I'm pretty sure that the problems come from a \ or any other character that I can't target.
Thank you for helping .
You've mixed up MySQL and MySQLi plugins — you're trying to connect with MySQLi then perform a query with MySQL. You can't do that. Pick one API and use it consistently.
So:
mysql_query($sql) ---> $connection->query($sql)
mysql_affected_rows() ---> $result->affected_rows()
mysql_error() ---> $connection->error
Ultimately, this has nothing to do with LOAD DATA INFILE and you should have tried it with a basic SELECT! And I recommend reading the documentation for the functions that you use.
EDIT : You are mixing two plugins MYSQL and MYSQLi in same script, below i dumped remaining part of your code using mysqli plugin, because your upper part uses mysqli...
N.B:You can't do that. Pick just any single API.
$result = mysqli_query($connection, $sql);
if (mysqli_affected_rows($connection) >= 1) {
$message = "The trip was successfully inserted!";
} else {
$message = "The trip insert failed";
$message .= mysqli_error($connection);
}
Try to move you trip.csv file into datadir - You can find it with this command : SELECT # #datadir