I want to import data stored in a .csv file into mysql via php. The LOAD DATA INFILE query does not seem to work and i managed to write a code that will import the records one by one. Here is the code:
<?php
$arr = array(array(),array());
$num = 0;
$row = 0;
$handle = fopen("./import.csv", "r");
while($data = fgetcsv($handle,1000,",")){
$num = count($data);
for ($c=0; $c < $num; $c++) {
$arr[$row][$c] = $data[$c];
}
$row++;
}
$con = mysql_connect('localhost','root','password22');
mysql_select_db("security",$con);
for($i=1; $i<$row; $i++){
$sql = "INSERT INTO sls VALUES ('".$arr[$i][0]."','".$arr[$i][1]."','".$arr[$i][2]."','".$arr[$i][3]."','".$arr[$i][4]."','".$arr[$i][5]."')";
mysql_query($sql,$con);
}
?>
The problem is that I have about 300 000 records to import and when the records get too much, no record gets imported into the database and I get an error message. Is there anyway I can import the data faster or are there any similar statements like LOAD DATA INFILE I can use in PHP?
This may help you out
<?php
require_once 'reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('filename.xls');
$con=mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE tablename(
quote_number VARCHAR(100),
line_no VARCHAR(100),
item_no VARCHAR(100),
name VARCHAR(100),
unit VARCHAR(100),
rm VARCHAR(100),
capex VARCHAR(100))";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table tablename created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
for($x = 2; $x <= count($data->sheets[0]["cells"]); $x++)
{
//$sno = $data->sheets[0]["cells"][$x][1];
$quote_number = $data->sheets[0]["cells"][$x][1];
$line_no = $data->sheets[0]["cells"][$x][2];
$item_no = $data->sheets[0]["cells"][$x][3];
$name = $data->sheets[0]["cells"][$x][4];
$unit = $data->sheets[0]["cells"][$x][5];
$rm = $data->sheets[0]["cells"][$x][6];
$capex = $data->sheets[0]["cells"][$x][7];
$res = mysqli_query($con,"INSERT INTO tablename
(quote_number, line_no, item_no,name,unit,rm,capex) VALUES ('$quote_number','$line_no','$item_no','$name','$unit','$rm','$capex')");
mysqli_close($res);
}
?>
you can download reader.php file from here
Since you have not shared the LOAD DATA INFILE I assume most probably the issue is with FILE Privileges
You have to GRANT FILE privileges to the person loading the file(Mysql user connecting through username/password from php). Sth like this:
GRANT FILE on *.* TO 'mysql_user'#'localhost' ;
Since FILE is global privilege you cannot localize that to a specific database e.g dbname.* , just to note. To run the above command itself you should login to mysql from command line as root or as a user who has GRANT privileges.
Once that is done you should able to load the file using LOAD DATA INFILE. IF you are trying this in shared-hosting environment, your chances are very little. In that case you have to use the above method you tried , read the file, split the each line ,validate the line , insert into db table.
Related
This question already exists:
Copying a database and its tables to a new database doesn't work [duplicate]
Closed 2 years ago.
I need to do this in PHP only, can't use PhpMyAdmin because the process needs to be automated.
I've been using the following code to copy the database and its tables in to a new database with its new tables, with no change to table names, just change to database name.
Seems to work when the tables have 10 or so fields in them but I just added a table with 30-40 fields in it and it seems to fall down -as in, it doesn't copy the database table and it's table rows into the new database. Is there some error checking or buffering problems that I might be running into, or is it some other problem? Doesn't output a PDO exception error either.
here's the code:
$GLOBALS['MySQL_Host'] = "127.0.0.1";
$GLOBALS['MySQL_Username'] = "username";
$GLOBALS['MySQL_Password'] = "password";
$ExistingDatabase = "database_1";
$NewDatabase = "database_2";
// connect server 1
$dblink1 = mysqli_connect("{$GLOBALS['MySQL_Host']}", "{$GLOBALS['MySQL_Username']}", "
{$GLOBALS['MySQL_Password']}", "{$ExistingDatabase}");
// select database_1
mysqli_select_db($dblink1,"$ExistingDatabase");
// get tables from database_1
$tables = mysqli_fetch_all(mysqli_query($dblink1, "SHOW TABLES FROM $ExistingDatabase"));
// connect server 2
$dblink2 = mysqli_connect("{$GLOBALS['MySQL_Host']}", "{$GLOBALS['MySQL_Username']}",
"{$GLOBALS['MySQL_Password']}");
// select database 2
mysqli_select_db($dblink2, "{$NewDatabase}");
$n=0;
foreach($tables as $table){
// get structure from table on server 1
$tableinfo = mysqli_fetch_array(mysqli_query($dblink1,"SHOW CREATE TABLE $table[0]"));
// use found structure to make table on server 2
mysqli_query($dblink2," $tableinfo[1] ");
// select all content
$result = mysqli_query($dblink1,"SELECT * FROM $table[0] ");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
mysqli_query($dblink2,"INSERT INTO $table[0] (".implode(", ",array_keys($row)).") VALUES
('".implode("', '",array_values($row))."')");
}
$n++;
}
mysqli_close($dblink1);
mysqli_close($dblink2);
I tried many (like 10) code snippets from stackoverflow and this was the only one I could get working. Is this a good approach? If not, what is? If so, how can I fix it to make sure it's more robust and actually works?
Remember I can't use PhpMyAdmin. Please don't close this post and link a PhpMyAdmin solution. Thanks.
Edit
I've tried the following commands and executions without success. Here's the top of the file, and the 4 trials I've tried are below it:
$GLOBALS['Dir'] = "C:/wamp64/www/projectsite/";
$dumpDir = $GLOBALS['Dir'].'Databases/';
$exisitingDatabase = "exisitingDatabaseName";
$newDatabase = "newDatabaseName";
if(!file_exists($dumpDir)){
mkdir($dumpDir);
}
$Dbh = new PDO("mysql:host=127.0.0.1:3307", $GLOBALS['MySQL_Username'],
$GLOBALS['MySQL_Password']);
1.
$Dbh->exec("mysqldump --tab={$Dumpdir} {$ExistingDatabase}");
2
$Dbh->exec("-h {$GLOBALS['MySQL_Host']} -u {$GLOBALS['MySQL_Username']} --password={$GLOBALS['MySQL_Password']} > {$Dir_and_Filename}.sql");
3
$cmd = "mysqldump -h {$GLOBALS['MySQL_Host']} -u {$GLOBALS['MySQL_Username']} --password={$GLOBALS['MySQL_Password']} {$existingDatabase} > {$newDatabase}.sql";
exec($cmd);
4
exec("mysqldump -u {$GLOBALS['MySQL_Username']} -p {$ExistingDatabase} > {$NewDatabase}.sql");
Edit
Managed to get this dumping an sql file so far:
$return_var = NULL;
$output = NULL;
$command = "$Dumpdir/mysqldump -u {$GLOBALS['MySQL_Username']} -h {$GLOBALS['MySQL_Host']} -p{$GLOBALS['MySQL_Password']} {$ExistingDatabase} > $Dumpdir/{$NewDatabase}.sql";
if(exec($command, $output, $return_var)){
echo "asd";
}else{
echo "qwe";
}
Got it.
Here's some code that works, and it's simple too..
$Dumpdir = $GLOBALS['SiteDir'].'SQL/Dbs/';
if(!file_exists($Dumpdir)){mkdir($Dumpdir);}
$return_var = NULL;
$output = NULL;
$command = "$Dumpdir/mysqldump -u {$GLOBALS['MySQL_Username']} -h {$GLOBALS['MySQL_Host']} -p{$GLOBALS['MySQL_Password']} {$ExistingDatabase} > $Dumpdir{$NewDatabase}.sql";
if(exec($command, $output, $return_var)){
echo "uio";
}else{
echo "bnm";
}
$Dbh = new PDO("mysql:host=127.0.0.1:3307", $GLOBALS['MySQL_Username'], $GLOBALS['MySQL_Password']);
$Dbh->exec("CREATE DATABASE $NewDatabase");
$sql = file_get_contents($Dumpdir.$ExistingDatabase.".sql");
$mysqli = new mysqli($GLOBALS['MySQL_Host'], $GLOBALS['MySQL_Username'], $GLOBALS['MySQL_Password'], $NewDatabase);
/* execute multi query */
if($mysqli->multi_query($sql)){
echo "cvb";
}else{
echo "zxc";
}
I want insert some data to a table of the wordpress then return it's auto increase id value.
I do this but both of these has error:
INSERT INTO wp_sho_app_form (job_id, first_name, last_name) VALUES(1, 'Caldwell', 'Estrada');
SELECT LAST_INSERT_ID();
This code word well in MySql but by $wpdb I get 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 'SELECT LAST_INSERT_ID()' at line 1
I call this statement by $wpdb->query and also $wpdb->get_results, but both of them has that error.
I don't want use $wpdb->insert for some reasons and I should use this type of code.
The correct way is to use insert_id.
$lastid = $wpdb->insert_id;
if your make another query its not consistent if you have new entries and a lot of traffic. That can cause wired problems.
And that is only working after insert and you should use them. Don't fight the framework.
You can run a custom query then another to select the last item in the table. If you are using a stand alone php file you need to include the wp-load.php file to get the wordpress functions.
$query = "
INSERT
INTO wp_sho_app_form
(job_id, first_name, last_name)
VALUES
(1, 'Caldwell', 'Estrada')
";
$wpdb->query($query);
$query = "
SELECT *
FROM wp_sho_app_form
ORDER BY col_id desc
LIMIT 1
";
$wpdb->query($query);
There is no way to do multiple query by wpdb. The solution which I could find lastly is using direclty MySqli. I wrote this two function for do it. May be it be useful for sombody. As in ajax wordpress not load so I check to find wp-config fle to get details of connection at first:
public static function run_query($query)
{
$wp_config_path = script_generator::get_wp_config_path();
if($wp_config_path == null){
echo 'Could not found wp_config file!';
return;
}
require_once $wp_config_path;
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_count = 0;
$result_set = array();
if ($mysqli->multi_query($query)) {
do {
$current_result_count = 0;
$current_result = array();
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
$current_result[$current_result_count] = $row;
$current_result_count++;
}
$result->close();
}
$result_set[$result_count] = $current_result;
if ($mysqli->more_results()) {
$result_count++;
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
return $result_set;
}
function get_wp_config_path(){
$dir = dirname(__FILE__);
do {
if( file_exists($dir."/wp-config.php") ) {
return $dir."/wp-config.php";
}
} while( $dir = realpath("$dir/..") );
return null;
}
I am trying to figure out will MySQL be enough for my use case. I tried inserting 100 000 rows into my local mysql server, which went fine. I saw that DB started to get populated with the data.
Then I run same insert script agains the Google Cloud SQL. Everything seemed also fine, but for some reason DB stopped inserting entries after the 67667 entry even though the response from the DB was that the insertion was successful.
Does MySQL has some kind of limitation, or what may cause this kind of behavior?
My test script:
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->select_db($database);
$insertData = '';
for ($i = 0; $i < 100000; $i++) {
$insertData .= "INSERT INTO table (isin) VALUES ('".uniqid()."');";
}
if ($conn->multi_query($insertData) === true) {
echo "New records created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
$conn->close();
My test table has only two columns, id and the isin number.
Try using mysql Batch insert for e.g.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Build this part i.e. (1,2,3),(4,5,6),(7,8,9) in your loop and then use only one INSERT query
Try this way :
$val = "";
for ($i = 0; $i < 100000; $i++) {
$val .= "('".uniqid()."'),";
}
$val = rtrim($val,",");
$insertData = "INSERT INTO table (isin) values $val";
$conn->query($insertData);
I wouldn't want to talk too much, here is my code (I know it is not PDO, but it will once it can work). Almost everything working!!!
Now I am doing the logs and I am stuck! - UPDATE thanks to Michael some of it has fixed!
$statresult=mysql_query($statsql, $actconn) or die(mysql_error());
Optimize function too. This is not working with Multiple DB some reason...
The permission doesn't want to be right I have looked hours and I can't figure it out. A part from that everything works beautifully.
The code reads some rows from the real DB and moves them to the backupDB. But I want a cron job and email alert so I did an easy log (into a table) but it doesn't want to work... I can't even see any error log. Well: PHP Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/sites/stcticketing.org/public_html/back/asu1.php on line 34
<?php
// open db
$dbhost = 'localhost';
$actdbuser = 'user1';
$actdbpass = 'pass';
$bckdbuser = 'user2';
$bckdbpass = 'pass';
$actconn = mysql_connect($dbhost, $actdbuser, $actdbpass) or die ('act Error connecting to mysql');
$bckconn = mysql_connect($dbhost, $bckdbuser, $bckdbpass) or die (' back Error connecting to mysql');
$actdbname = '`web151-tevenyal`';
mysql_select_db($actdbname, $actconn);
$bckdbname = '`web151-bckproba`';
mysql_select_db($bckdbname, $bckconn);
//end opendb
//functions
function test($sqls, $states){
if ($sqls=1){
$resflag=1;
}
else {
$resflag=0;
}
$statsql="INSERT INTO `web151-tevenyal`.`tex_bcklog` (`what`,`how`,`when`) VALUES ('$states',$resflag,CURDATE());";
echo "<p>".$sqls."<br/>".$statsql."</p>";
$statresult=mysql_query($statsql, $actconn) or die(mysql_error());
echo "<p>".$states." - ".$resflag."</p>";
$emaltext=$emailtext.$sqls;
}
function db_rows($db,$ord, $connectdb){
$dbquery="SELECT azon FROM $db ORDER BY azon $ord LIMIT 1";
$dbresult=mysql_query($dbquery, $connectdb);
$row = mysql_fetch_array($dbresult);
$dbrow = $row['azon'];
return $dbrow;
}
// end of functions
//config information...
$acttable = 'adat';
$today = date("yW_Hi");
$newdb = $bckdbname.".test_".$today;
test($permsql, "grant");
test(1, "backupstart");
//creating log table for backup results
$backtablesql="CREATE TABLE IF NOT EXISTS `tex_bcklog` ( `azon` int(11) NOT NULL AUTO_INCREMENT,`what` varchar(255) CHARACTER SET utf8 NOT NULL, `how` varchar(255) CHARACTER SET utf8 NOT NULL, `when` date NOT NULL, PRIMARY KEY (`azon`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;" ;
//$backtableresult=mysql_query($backtablesql);
$firstact= db_rows($actdbname.".".$acttable,"asc", $actconn);
$lastact= db_rows($actdbname.".".$acttable,"desc", $actconn);
$upto=$firstact+25000;
if ($lastact-$firstact>50000) {
//create a new table
$permsql="GRANT SELECT ON `$actdbuser`.* TO `$bckdbuser`#'%' ;";
test($permsql, "grant");
$perm = mysql_query($permsql, $bckconn) or die(mysql_error());
$newdbsql="CREATE TABLE $newdb LIKE $actdbname.`$acttable`";
test($newresult, "createdb");
$newresult = mysql_query($newdbsql, $bckconn) or die(mysql_error());
// copy all the data
$query = "INSERT INTO $newdb SELECT * FROM $actdbname.$acttable WHERE $acttable.azon < $upto";
test($query, "copyrows");
$result = mysql_query($query) or die(mysql_error());
// so what has happened...
$delquery = "DELETE FROM $actdbname.$acttable WHERE $actdbname.$acttable.azon < $upto";
test($delquery, "deleterows");
$delresult = mysql_query($delquery, $actconn);
// then tidy up everything:)
$res = mysql_query('SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free > 102400', $actconn);
while($optrow = mysql_fetch_assoc($res)) {
mysql_query('OPTIMIZE TABLE ' . $optrow['Name']);
}
}
else {
test(0, "nothing");
}
// send an email to confirm what's happened - thanks:)
// close db
mysql_close($actconn);
mysql_close($bckconn);
?>
Please fix it first and then comment any PDO unless the solution itself:) Any help would be greatly appreciated!
Inside the function that is failing (it is done correctly in the other function db_rows()), your database resource link variables are out of scope. Pass them to the functions as parameters:
For example, pass one in as $connection here:
function test($sqls, $states, $connection){
if ($sqls=1){
$resflag=1;
}
else {
$resflag=0;
}
$statsql="INSERT INTO `web151-tevenyal`.`tex_bcklog` (`what`,`how`,`when`) VALUES ('$states',$resflag,CURDATE());";
echo "<p>".$sqls."<br/>".$statsql."</p>";
$statresult=mysql_query($statsql, $connection) or die(mysql_error());
echo "<p>".$states." - ".$resflag."</p>";
$emaltext=$emailtext.$sqls;
}
Then call the function with the correct connection as in:
test($permsql, "grant", $actconn);
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.