I have more than 300,000 users on an old online store. Client switched to Magento solution and now have to migrate all the users, addresses to Magento. So I have to write a custom script to import users and their address to the Magento system.
Are there any tutorials or similar sort of work already done. Please help me.
Thanks
Here's an example of how I migrated users from OSC into Magento with the SOAP library. This script was run on the old server and needs to be run from the ssh command line (php execution time through the browser will not support this
$proxy = new SoapClient('http://[your magento url]/api/soap/?wsdl=1');
$sessionId = $proxy->login('admin', '[your password]');
// connect to local db
$link = mysql_connect('localhost', '[old ecommerce db]', '[old db pw]');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('sbc_osc', $link);
$sql = "SELECT * FROM customers";
$customers = mysql_query($sql);
// loop thyrough customers
while ($customer = mysql_fetch_assoc($customers)) {
set_time_limit(600);
$newCustomer = array(
'firstname' => $customer['customers_firstname'],
'lastname' => $customer['customers_lastname'],
'email' => $customer['customers_email_address'],
'password_hash' => $customer['customers_password'],
'store_id' => 2, // set the store you want to send to
'website_id' => 2
);
$telephone = $customer['customers_telephone'];
$fax = $customer['customers_fax'];
try{
$newCustomerId = $proxy->call($sessionId, 'customer.create', array($newCustomer));
}
catch (Exception $e) {
echo "failed to create customer for: " . $customer['customers_firstname'] . " " . $customer['customers_lastname'] . "\n";
}
// grab the default address
$sql = "SELECT ab.*, c.countries_iso_code_2, z.zone_name, z.zone_id
FROM address_book ab
LEFT JOIN countries c ON ab.entry_country_id = c.countries_id
LEFT JOIN zones z ON ab.entry_zone_id = z.zone_id
WHERE customers_id = {$customer['customers_id']} AND address_book_id = {$customer['customers_default_address_id']}";
$addresses = mysql_query($sql);
while ($address = mysql_fetch_assoc($addresses)) {
$newCustomerAddress = array(
'firstname' => $address['entry_firstname'],
'lastname' => $address['entry_lastname'],
'company' => $address['entry_company'],
'country_id' => $address['countries_iso_code_2'],
'region_id' => $address['zone_id'],
'region' => ($address['zone_name'] != "" ? $address['zone_name'] : $address['entry_state']),
'city' => $address['entry_city'],
'street' => array($address['entry_street_address']),
'telephone' => $telephone,
'fax' => $fax,
'postcode' => $address['entry_postcode'],
'is_default_billing' => true,
'is_default_shipping' => true,
);
try{
$newAddressId = $proxy->call($sessionId, 'customer_address.create', array($newCustomerId, $newCustomerAddress));
}
catch (Exception $e) {
echo "failed to add address for: " . $address['entry_firstname'] . " " . $address['entry_lastname'] . "\n";
}
}
echo "migrated: " . $customer['customers_firstname'] . " " . $customer['customers_lastname'] . "\n";
}
mysql_close($link);
One thing you need to watch out for is the passwords.. for this to work I had to set up Magento to use the same password hashing schema.
My suggestion would be to look into the customer import api and build out a script using the methods from the code base, using the API will be slower so since you will be running the script on your server you can build it using the actual methods. So you can look at this folder for the customer api classes and methods
/app/code/core/Mage/Customer/Model/Customer
and then here for the address api classes and methods
/app/code/core/Mage/Customer/Model/Address/
You would probably need to export your data to CSV and get it in the right format to import into Magento. 30k isn't that much so you can even try out the normal import process that is default Magento. We haven't had good luck with that but we have been importing hundreds of thousands of customers. Even then we break the file down into small chunks of customers at a time.
Related
i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>
In following code, I'm trying to create a new category (name = 'To be deleted') and then I want to delete it.
first part of the code working fine and I can see new record in the database every time I run the unit test
but I'm having a problem with recode deletion. what's wrong with my code
public function testCategoryDeletion()
{
$user = \App\User::find(1);
//dd($user->name);
$category = \App\Category::create(['name' => 'To be deleted']);
//dd($category->id);
$response = $this->actingAs($user, 'api')
->json('DELETE', "/api/category/{$category->id}")
->assertStatus(200)->assertJson([
'status' => true,
'message' => 'Category Deleted',
]);
}
Test case output
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API> ./vendor/bin/phpunit
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.
. . . . . . . 7 / 7 (100%)
Time: 1.53 minutes, Memory: 18.00 MB
OK (7 tests, 65 assertions)
PS C:\xampp\htdocs\Chathura\Vue_Laravel_API>
In database, recode is created but not deleted,
I fixed the controller as follows and now its working,
public function destroy(Category $category)
{
$status = $category->delete();
return response()->json([
'status' => $status,
'message' => $status ? 'Category Deleted' : 'Error Deleting Category'
]);
}
API routes
Route::group(['middleware' => 'auth:api'], function(){
Route::resource('/task', 'TaskController');
Route::resource('/category', 'CategoryController');
Route::get('/category/{category}/tasks', 'CategoryController#tasks');
});
I am trying to export my MySQL tables from my database to a JSON file, so I can list them in an array.
I can create files with this code no problem:
$sql=mysql_query("select * from food_breakfast");
while($row=mysql_fetch_assoc($sql))
{
$ID=$row['ID'];
$Consumption=$row['Consumption'];
$Subline=$row['Subline'];
$Price=$row['Price'];
$visible=$row['visible'];
$posts[] = array('ID'=> $ID, 'Consumption'=> $Consumption, 'Subline'=> $Subline, 'Price'=> $Price, 'visible'=> $visible);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Now this reads a table and draws it's info from the fields inside it.
I would like to know if it is possible to make a JSON file with the names of the tables, so one level higher in the hierarchy.
I have part of the code:
$showtablequery = "
SHOW TABLES
FROM
[database]
LIKE
'%food_%'
";
$sql=mysql_query($showtablequery);
while($row=mysql_fetch_array($sql))
{
$tablename = $row[0];
$posts[] = array('tablename'=> $tablename);
}
$response['posts'] = $posts;
But now i am stuck in the last line where is says: $ID=$row['ID']; This relates to the info inside the Table and I do not know what to put here.
Also as you can see, I need to filter the Tables to only list the tables starting with food_ and drinks_
Any help is greatly appreciated:-)
There is no 'table id' in MySQL and therefore the result set from SHOW TABLES has no index id. The only index in the resultset is named 'Tables_in_DATABASENAME'.
Also you should use the mysqli library as the good old mysql library is depreacted. Having prepared an example:
<?php
$mysqli = new mysqli(
'yourserver',
'yourusername',
'yourpassword',
'yourdatabasename'
);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
. $mysqli->connect_error;
}
$result = $mysqli->query('SHOW TABLES FROM `yourdatabasename` LIKE \'%food_%\'');
if(!$result) {
die('Database error: ' . $mysqli->error);
}
$posts = array();
// use fetch_array instead of fetch_assoc as the column
while($row = $result->fetch_array()) {
$tablename = $row[0];
$posts []= array (
'tablename' => $tablename
);
}
var_dump($posts);
I've been stuck with this for a full day now and this is the longest I've been stuck coding ever. Please Help me.
I have the following code, it is a paypal ipn URL used to verify an account on a database. I first connect to sql etc. then get the users information from paypal then get the users information from the database. Before paying, the user should have the value of 'unverified' in the user_level column and if 'unverified' it should be updated.
Here is the strange thing that I'm stuck at. The value of user_level is never 'unverified' even though I've checked in the actual database, before running the code, that it is in fact 'unverified'. But when I comment out the mysql_query($u), it gives the value 'unverified'.
What is happening is that it seems to be updating the record before the actual code is being called to check whether to update it or not.
Please help anybody, I would appreciate it greatly.
I
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','root', '******') or die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postFields = 'cmd=_notify-validate';
foreach($_POST as $key => $value)
{
$postFields .= "&$key=".urlencode($value);
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields
));
$result = curl_exec($ch);
curl_close($ch);
if($result=='VERIFIED'){
$log = 'Verfied --- ';
//get buyers information from PAYPAL checkout
$email = $_POST['payer_email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$amount = $_POST['amount3'];
$plan = $_POST['option_selection1'];
$q = "SELECT * FROM users WHERE email='$email'";
$data = mysql_query($q);
$con = mysql_fetch_array($data);
//get buyers information from DATABASE
$email2 = $con['email'];
$first_name = $con['first_name'];
$last_name = $con['last_name'];
$active = $con['active'];
$user_level = $con['user_level'];
$log .= $first_name.' , '.$last_name.' , '.$email2.' , '.$active.' , '.$user_level.' **************** '.$email ;
if($email2==$email){ //User already has a record
if($user_level=='unverified'){ // User unverified, ready for verification
$log .= 'Emails match, and user is VERIFIED';
$u = "UPDATE users SET active='verified', user_level='$plan' WHERE email='$email' LIMIT 1";
$log .= $u;
mysql_query($u);
}
else{ // User is already verified,
$log .= 'Emails match, BUT user is NOT VERIFIED';
}
}
else{ //User doesn't have a record
$log .= 'Emails DONT match, execute update here';
}
$fh = fopen('result_ipn_test.txt', 'w');
//fwrite($fh, $subject.' --- '.$message);
fwrite($fh, $message.' ********** '.$log);
fclose($fh);
}
else
echo 'INVALID';
mysql_close();
shouldn't you be cheking for status instead of user-level?
if($user_level=='unverified')
should be
if($active=='unverified')
You are checking that the user is not verified in the database then immediately logging that the user IS verified. Also, should this not be checking $active rather than $user_level, as you are placing the value of $plan into $user_level
if($user_level=='unverified'){ // User unverified, ready for verification
$log .= 'Emails match, and user is VERIFIED';
Similarly, if the user is listed as 'verified' in the database, you are logging that he is NOT verified:
else{ // User is already verified,
$log .= 'Emails match, BUT user is NOT VERIFIED';
Commenting out the sql query will cause $data to be empty, thus making $user_level empty. $user_level will not match unverified and will result in a log of 'Emails match, BUT user is NOT VERIFIED'
I host at hostgator and have about 30 mysql databases (all different websites that sit on the same server). For the last year.. no problems and suddenly, the last 2 days, I've seen 5 - 10 of these databases marked as 'crashed' and they return no results... so my websites display no info. I have to run a "repair table mytable" to fix these and then they work great again.
Instead of logging in to go through the databases 1 by 1 every morning, is there a way I could setup a php page to connect to all 30 databases and run a simple select statement.. and if it works, return
"database db1 is working"
"database db2 is working"
and then when not working, return
"no reply from db3"
....or something similar?
Thanks!
There's no reason you couldn't have a script that lists all of your databasenames and login credentials, and try to connect in turn to each:
$logins = array(
array('dbname' => 'blah', 'user' => 'username1', 'password' => 'password1'),
array('dbname' => 'yuck', ....)
...
);
$failures = array();
foreach ($logins as $login) {
$con = mysql_connect('servername', $login['user'], $login['password']);
if (!$con) {
$failures[] = $login['dbname'] . " failed with " . mysql_error();
continue;
}
$result = mysql_select_db($login['dbname']);
if (!$result) {
$failures[] = "Failed to select " . $login['dbname'] . ": " . mysql_error();
continue;
}
$result = mysql_query("SELECT something FROM sometable");
if (!$result) {
$failures[] = "Faile to select from " . $login['dbname'] . ": " . mysql_error();
continue;
}
if (mysql_num_rows($result) != $some_expected_value) {
$failures[] = "Got incorrect rowcount " . mysql_num_rows($result) . " on " . $login['dbname'];
}
etc....
mysql_close();
}
if (count($failures) > 0) {
echo "Failures found: "
print_r($failures);
}
You should be able to do something like the following:
<?php
//connect to database
mysql_connect('database','user','password');
//get all database names
$result = mysql_query("show databases;");
//iterate over all databases returned from 'show databases' query
while($row = mysql_fetch_array($result)) {
//DB name is returned in the result set's first element. select that DB
mysql_selectdb($row[0]);
//get all tables in the database
$query = "show tables;";
$result2 = mysql_query($query);
echo "Query: (".$row[0].")$query\n";
echo mysql_error();
//iterate over all tables in the current database
while($row2 = mysql_fetch_array($result2)) {
//the first element of the returned array will always be the table name, so:
$query = "select * from ".$row2[0]." where 1=1;";
$result3 = mysql_query($query);
echo "Query:\t(".$row[0].'/'.$row2[0].")$query\n";
//If mysql_query returns false (i.e., $result3 is false), that means that
// the table is damaged
if(!$result3) {
echo "***Error on table '".$row2[0]."' *** ... Fixing...";
//So, we repair the table
mysql_query("repair table ".$row2[0].";");
}
}
}
?>