I'm trying to populate a mysql database with the contents of a .csv file using php. I'd like to do it using php code (no phpadmin). I consulted another thread on stackoverflow (populating database from csv file using php) but am still getting stuck. Here is my code:
$file = fopen("input.csv", "r");
while ($data = fgetcsv($file, $lineLength = 0, $delimiter = ",")) {
$added = "INSERT INTO Items VALUES(".$data.")";
if($connection->query($added) === TRUE) {
echo "Values successfully added!";
} else {
echo "Error inserting values: " . $connection->error;
}
Some context: earlier in the code, I create a database, connect to it, and create a table in the database. That part works fine. I just get an error when I try to populate the database from a .csv file. Here is the error message I get:
Notice: Array to string conversion in C:\xampp\htdocs\assignment8\init.php on line 64
Error inserting values: Unknown column 'Array' in 'field list'
I get this message 12 times, which corresponds with the number of rows in the .csv file I'm trying to import. "Line 64" corresponds with the line in my code that starts with "$added = INSERT INTO..."
Any help or suggestions are greatly appreciated.
You have to access to your column in the array
If your csv is something like this
Inside your while, you can access the values like:
echo $data[0] // prints 'Value 1'
So you might want to do something like...
$added = "INSERT INTO Items VALUES(".$data[0].")";
Related
currently im doing my homework project to parse specific data from excel to MySQL using PHP. The project is about uploading an excel file and then the excel data supposed to be in MySQL after excel file uploaded.
The problem that im facing is, my homework project requirement is only parse specific row and column amongst the data exists in the excel file. I have already try using codes that i found, but it doesn't work. It parse everything in the excel files to MySQL table. Not the specific Row and Columns data that i expected.
I'm still looking for a solution for this. Spent almost 2 weeks for this but still i'm facing a dead end. My deadline project in 1 week. So, i would be really thankful if someone could help me and get me a solution of this.
I have tried on this PHP script. But, all the data in excel were parsed to MySQL table and the data messed the row and column in MySQL table. I want only the specific part (row and column) of excel files to be inserted to MySQL table that i've crated. i provided screenshot and the part that i want to be parsed to MySQL table highlighted with red color.
if(!empty($_FILES['excelfile']['name'])){
// Get File extension eg. 'xlsx' to check file is excel sheet
$pathinfo = pathinfo($_FILES['excelfile']['name']);
// check file has extension xlsx, xls and also check
// file is not empty
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['excelfile']['size'] > 0 ){
$file = $_FILES['excelfile']['tmp_name'];
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($file);
$count = 0;
foreach ($reader->getSheetIterator() as $sheet){
foreach($sheet->getRowIterator () as $row)
{
if ($count > 0){
$name = $row[2];
$job_schedule = $row[3];
$overtime = $row[4];
$notes = $row[5];
$start_working = $row[6];
$finished_working = $row[7];
$qry = "INSERT INTO `timesheet` (`name`,`job_schedule`, `overtime`,`notes`, `start_working`,`finished_working`) VALUES ('$name','$job_schedule','$overtime','$notes','$start_working','$finished_working')";
$res = mysqli_query($con,$qry);
}
$count++;
}
}
if($res){
echo "Success";
}
else{
echo "failed";
}
$reader->close();
}
else{
echo "Excel format is not supported";
}
```[Here is the SCREENSHOT LINK]
[1]: https://i.stack.imgur.com/0kIxo.png
You can follow this link:
Exporting data from php to excel
I recommend use PHPExcel php class, just plug and play, I've done it myself. It's works better than trying to figure everthing by yourself.
I am working on a php code as shown below:
class MyDB extends SQLite3
{
function __construct()
{
$this->open('database/Podcast.db');
}
}
$db = new MyDB();
$f = $mp4_files[$_POST['id']];
$parts = pathinfo($f);
switch ($parts['extension']) {
/* Conversion of mp4 into mp3 is happening */
}
print_r($f); // Line Z
$result = $db->exec("UPDATE Podcast_Export SET Status = 'Completed' WHERE House_number = '" . $f . "'"); // Line A
if ($result == FALSE) {
echo "Error in fetch " . $db->lastErrorMsg(); // Line M
}
At Line Z, on console it prints 36031P.mp4 (When Go button is clicked from the 1st table row (from UI))
At Line Z, on console it prints hello.mp4 (When Go button is clicked from the 2nd table row(from UI))
Problem Statement:
I have a query at Line A in order to update Podcast_Export table but its not working and throwing error at Line M:
Error in fetch database is locked
At this moment, I have the following content inside Podcast_Export table:
The SQLite version which I am using is 3.27.2
From the php SQLITE3 doc
SQLite3::exec — Executes a result-less query against a given database
It returns a boolean. "Resultless" query is typcially an INSERT, UPDATE, DELETE but not a SELECT.
You might want to investigate how you could use querySingle to get the desired result.
Usually, the database is locked happened when you have an open DB process.
Check the following URL I hope to help you.
Database locked while trying to access from PHP script
Hey guys im having a problem with a script im working on.
Im getting two errors and i dont understand why.
I do know that the csv file is csv comma delimited type.
Errors
Notice: Undefined variable: data in /home1/public_html/tickets/inv.php on line 17
Notice: Undefined offset: 7 in /home1/public_html/tickets/inv.php on line 20
Here is a link to my csv file: http://goo.gl/tcNNm1
//connect to the database
$connect = mysql_connect("*****","*********","*******");
mysql_select_db("don=_scanner",$connect); //select the table
//
$file = "rfl2.csv";
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO inv (stk, vin) VALUES
(
'".addslashes($data[7])."',
'".addslashes($data[8])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
I had this script working with a file i upload through a forum but im trying to make it load that one file when i request the page.
You're using the wrong kind of loop. $data will not be defined until after the FIRST iteration of the loop, because the $data = fgetcsv() will not be executed until the do/while's innards have been run once already.
You want
while($data = fgetcsv(...)) {
... database insert ...
}
instead
Plus, you are vulnerable to sql injection attacks. addslashes is utterly useless for protection against this. At least use the proper mysql_real_escape_string().
while(...) {...} - execute loop contents only if the condition is true
do {...} while(...) - execute loop contents at least once, terminate if condition is false
As the property of Do-While , it runs at least once. So at first iteration, $data variable is undefined. hence error!. Possible solution is do something like:
if(isset($data)) instead of if($data). or better go for while loop or for loop.
do this:
while(!feof($handle)){
$values = fgetcsv( $handle);
if(isset($values[0])){
add sql here..
}
}
I found and followed the directions contained within this StackOverflow thread: Update MySql Table from CSV using PHP
I've got an error somewhere that I'm unable to detect, I think there's a problem with my query, which works fine in actual MySQL but seems to not quite translate to PHP.
In short, I'm trying to UPDATE the value of several rows within a single table (catalog_product_entity_varchar) with CSV column $data[1], but only where certain skus are concerned AND attribute_id = 523 AND entity_id matches $data[0] of my CSV. Here's my code (actual PW/username, etc, obviously removed)
$con=mysqli_connect("localhost","username","password","some_db");
if (!$con){
die('Could not connect: ' . mysql_error());
}
if (($file = fopen("upload.csv", "r")) !== FALSE) {
while (($data = fgetcsv($file)) !== FALSE) {
$sql = "UPDATE catalog_product_entity_varchar
JOIN catalog_product_flat_1
ON catalog_product_flat_1.entity_id = catalog_product_entity_varchar.entity_id
SET catalog_product_entity_varchar.value='{$data[1]}'
WHERE catalog_product_entity_varchar.entity_id='{$data[0]}'
AND catalog_product_entity_varchar.attribute_id = 523
AND (catalog_product_flat_1.sku LIKE '%PR%'
OR catalog_product_flat_1.sku LIKE '%PT%'
OR catalog_product_flat_1.sku LIKE '%PF%')";
if (mysql_query($con,$sql)) {
echo "Updated!";
} else {
echo "Error updating " . mysql_error();
}
}
}
fclose($file);
It simply returns "Error updating" for every line of the spreadsheet. This query, when simply done in MySQL (without the PHP) and modified to have actual values instead of $data[1] or $data[0] works just fine. What am I missing?
If you're unclear of what I'm trying to achieve, I did post this question yesterday (trying to do it via pure mySQL) and there's more context here - https://stackoverflow.com/questions/21170245/updating-a-joined-table-in-mysql-from-a-csv
Wow.
So I feel stupid. Apparently mixing mysqli_connect and mysql_query doesn't work very well. Adding the "i" to the "mysql" of mysql_query solved it. Thanks for looking everyone!
Automatically build mySql table upon a CSV file upload.
I have a admin section where admin can upload CSV files with different column count and different column name.
which it should then build a mySql table in the db which will read the first line and create the columns and then import the data accordingly.
I am aware of a similar issue, but this is different because of the following specs.
The name of the Table should be the name of the file (minus the extension [.csv])
each csv file can be diffrent
Should build a table with number of columns and names from the CSV file
add the the data from the second line and on
Here is a design sketch
Maybe there are known frameworks that makes this easy.
Thanks.
$file = 'filename.csv';
$table = 'table_name';
// get structure from csv and insert db
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($file,'r');
// first row, structure
if ( ($data = fgetcsv($handle) ) === FALSE ) {
echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = strtolower(trim($data[$i]));
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 20);
$field_count++;
$fields[] = $f.' VARCHAR(50)';
}
}
$sql = "CREATE TABLE $table (" . implode(', ', $fields) . ')';
echo $sql . "<br /><br />";
// $db->query($sql);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
$fields = array();
for($i=0;$i<$field_count; $i++) {
$fields[] = '\''.addslashes($data[$i]).'\'';
}
$sql = "Insert into $table values(" . implode(', ', $fields) . ')';
echo $sql;
// $db->query($sql);
}
fclose($handle);
ini_set('auto_detect_line_endings',FALSE);
Maybe this function will help you.
fgetcsv
(PHP 4, PHP 5)
fgetcsv — Gets line from file pointer
and parse for CSV fields
http://php.net/manual/en/function.fgetcsv.php
http://bytes.com/topic/mysql/answers/746696-create-mysql-table-field-headings-line-csv-file has a good example of how to do this.
The second example should put you on the right track, there isn't some automatic way to do it so your going to need to do a lil programming but it shouldn't be too hard once you implement that code as a starting point.
Building a table is a query like any other and theoretically you could get the names of your columns from the first row of a csv file.
However, there are some practical problems:
How would you know what data type a certain column is?
How would you know what the indexes are?
How would you get data out of the table / how would you know what column represents what?
As you can´t relate your new table to anything else, you are kind of defeating the purpose of a relational database so you might as well just keep and use the csv file.
What you are describing sounds like an ETL tool. Perhaps Google for MySQL ETL tools...You are going to have to decide what OS and style you want.
Or just write your own...