Import a single CSV file into multiple tables in MySQL - php

I would like to import a single CSV with 7 columns into 2 tables in MySQL.
Columns 1, 2 and 3 go into a single row in table1. Columns 4 and 5 go as a row in table2. Columns 6 and 7 go as a row again in same table2.
How can this be done using PHP or mysql directly?

First fetch all values from csv and store it in an array. Then maintain your array as per your requirement and then start looping and inserting.

<?php
$efected = 0;
$file_temp = $_FILES["file"]["tmp_name"];
$handle = fopen($file_temp, "r"); // opening CSV file for reading
if ($handle) { // if file successfully opened
$i=0;
while (($CSVrecord = fgets($handle, 4096)) !== false) { // iterating through each line of our CSV
if($i>0)
{
list($name, $gender, $website, $category, $email, $subcat) = explode(',', $CSVrecord); // exploding CSV record (line) to the variables (fields)
//print_r($subcat); sub_cat_ids
if($email!='')
{
$chk_sql = "select * from employees where employee_email='".$email."'";
$chk_qry = mysqli_query($conn, $chk_sql);
$chk_num_row = mysqli_num_rows($chk_qry);
$cat_array = array(trim($category));
$subcat_array = explode( ';', $subcat );
if(count($subcat_array)>0)
{
$subcat_array_new = array();
foreach($subcat_array as $key => $val)
{
$subcat_array_new[] = trim($val);
}
}
$cat_sub_cat_merge = array_merge($cat_array, $subcat_array_new);
$cat_subcat_comma = implode( "','", $cat_sub_cat_merge );
foreach($cat_array as $cat_key => $cat_val)
{
$chk_cat_sql = "select * from employee_cats where cats_name = '".$cat_val."'";
$chk_cat_qry = mysqli_query($conn, $chk_cat_sql);
$chk_cat_num_row = mysqli_num_rows($chk_cat_qry);
//$all_cat_array = array();
if($chk_cat_num_row == 0)
{
$new_cat_ins = "insert into employee_cats set cats_name = '".$cat_val."', parent_cat_id = '0' ";
$new_cat_ins_qry = mysqli_query($conn, $new_cat_ins);
}
}
foreach($subcat_array_new as $subcat_key => $subcat_val)
{
$chk_subcat_sql = "select * from employee_cats where cats_name = '".$subcat_val."'";
$chk_subcat_qry = mysqli_query($conn, $chk_subcat_sql);
$chk_subcat_num_row = mysqli_num_rows($chk_subcat_qry);
//$all_cat_array = array();
if($chk_subcat_num_row == 0 && trim($subcat_val)!='')
{
//$category
$get_catid_sql = "select * from employee_cats where cats_name = '".trim($category)."'";
$chk_catid_qry = mysqli_query($conn, $get_catid_sql);
$fetch_cat_info = mysqli_fetch_array($chk_catid_qry);
$fetch_cat_id = $fetch_cat_info['cats_id'];
$new_subcat_ins = "insert into employee_cats set cats_name = '".$subcat_val."', parent_cat_id = '".$fetch_cat_id."' ";
$new_subcat_ins_qry = mysqli_query($conn, $new_subcat_ins);
}
}
$get_cat_sql = "select * from employee_cats where cats_name in ('".$cat_subcat_comma."')";
$get_cat_qry = mysqli_query($conn, $get_cat_sql);
$get_cat_num_row = mysqli_num_rows($get_cat_qry);
$sub_category_ids = array();
if($get_cat_num_row>0)
{
while($fetch_cat_id = mysqli_fetch_array($get_cat_qry))
{
if($fetch_cat_id['parent_cat_id']==0)
{
$category_id = $fetch_cat_id['cats_id'];
}
else
{
$sub_category_ids[] = $fetch_cat_id['cats_id'];
}
}
$sub_cat_id_vals_comma = implode(",", $sub_category_ids);
}
else
{
$category_id = 0;
$sub_cat_id_vals_comma = "";
}
if($chk_num_row>0)
{
// and here you can easily compose SQL queries and map you data to the tables you need using simple variables
$update_sql = "update employees set
employee_name='".$name."',
employee_gender='".$gender."',
employees_website='".$website."',
employees_cat_id='".$category_id."',
sub_cat_ids='".$sub_cat_id_vals_comma."'
where employee_email='".$email."'";
$mysqli_qry = mysqli_query($conn, $update_sql);
}
else
{
// and here you can easily compose SQL queries and map you data to the tables you need using simple variables
$insert_sql = "insert into employees set
employee_name='".$name."',
employee_gender='".$gender."',
employees_website='".$website."',
employees_cat_id='".$category_id."',
sub_cat_ids='".$sub_cat_id_vals_comma."',
employee_email='".$email."'";
$mysqli_qry = mysqli_query($conn, $insert_sql);
}
$efected = 1;
}
}
$i++;
}
fclose($handle); // closing file handler
}
if($efected==1)
{
header('location:'.$site_url.'?import=success');
}
else
{
header('location:'.$site_url.'?import=failed');
}
?>

Related

Multiple Loops running together

$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?

Fetching record from two table and convert into json

Hi I'm new in PHP and trying to get the below response using php sql but i'm not be able to find the such desire output
[{"Id":1, "name": "India", "Cities":[{"Id":1, "Name":"Mumbai", "country_id":1}, {"Id":2,"Name":"Delhi","country_id":1},
"id":3,"Name":Banglore","country_id":1}, {"Id":2, "Name":"USA", "Cities":[{"Id":6, "Name":"New York", "country_id":2},.....
I have two tables one is country based and other is city based.
I tried
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo '{"response": '.json_encode($response).', '.json_encode($mainArray).' "success": true}';
}
}else{
echo '{"response": '.json_encode($response).' "success": false}';
}
?>
currently my response showing
{"response": [{"id":"1","name":"India"},{"id":"2","name":"USA"},{"id":"3","name":"UK"}], {"Cities":{"id":"15","name":"Manchester","country_id":"3"}} "success": true}
For detail code explanation check the inline comments
Modify the SQL query with related column names
The memory you have to take care. By default memory limit in php is 128MB in 5.3
Check the code and let me know the result
<?php
$data = array();
//include your database configuration files
include_once("config.inc.php");
//execute the join query to fetch the result
$sql = "SELECT country.country_id, country.name AS country_name,".
" city.city_id, city.name AS city_name FROM country ".
" JOIN city ON city.country_id=country.country_id ".
" ORDER BY country.country_id ";
//execute query
$sqlQuery = mysqli_query($conn, $sql) or die('error exists on select query');
//check the number of rows count
if(mysqli_num_rows($sqlQuery) > 0 ){
//country id temprory array
$country_id = array();
//loop each result
while($result = mysqli_fetch_assoc($sqlQuery)){
//check the country id is already exist the only push the city entries
if(!in_array($result['country_id'],$country_id)) {
//if the city is for new country then add it to the main container
if(isset($entry) && !empty($entry)) {
array_push($data, $entry);
}
//create entry array
$entry = array();
$entry['Id'] = $result['country_id'];
$entry['name'] = $result['country_name'];
$entry['Cities'] = array();
//create cities array
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
//append city entry
array_push($entry['Cities'], $city);
$country_id[] = $result['country_id'];
}
else {
//create and append city entry only
$city = array();
$city['Id'] = $result['city_id'];
$city['name'] = $result['city_name'];
$city['country_id'] = $result['country_id'];
array_push($entry['Cities'], $city);
}
}
}
//display and check the expected results
echo json_encode($data);
use like this
<?php
include_once("config.inc.php");
$sql = "SELECT * FROM country";
$sqlCity = "SELECT * FROM city";
$cityQuery = mysqli_query($conn, $sqlCity);
$sqlQuery = mysqli_query($conn, $sql);
$mainArray = array();
if(mysqli_num_rows($cityQuery) > 0 ){
$cityResponse = array();
while($resCity = mysqli_fetch_assoc($cityQuery)){
$cityResponse[] = $resCity;
}
if(mysqli_num_rows($sqlQuery) > 0 ){
$response = array();
while($res = mysqli_fetch_assoc($sqlQuery)){
$response[] = $res;
}
foreach($cityResponse as $city){
foreach($response as $country){
if($city['country_id'] == $country['id']){
$mainArray = array("Cities" => $city);
}
}
}
echo json_encode(array('result'=>'true','Cities'=>$mainArray));
}
}else{
echo json_encode(array('result'=>'false','Cities'=>$response));
}
?>
You can use try this. It actually works for me and it's cool. You can extend to 3 or more tables by editing the code.
try {
$results = array();
$query = "SELECT * FROM country";
$values = array();
$stmt = $datab->prepare($query);
$stmt->execute($values);
while($country = $stmt->fetch(PDO::FETCH_ASSOC)){
$cities = null;
$query2 = "SELECT * FROM city WHERE country_id = ?" ;
$values2 = array($country['id']);
$stmt2 = $datab->prepare($query2);
$stmt2->execute($values2);
$cities = $stmt2->fetchAll();
if($cities){
$country['cities'] = $cities;
} else {
$country['cities'] = '';
}
array_push($results, $country);
}
echo json_encode(array("Countries" => $results));
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}

Upload CSV file into SQL database

I am curently trying to upload a CSV file into a sql table, but I don't want to upload the first line which contains the name of every column value that will be inserted. I used a variable c to count the number of rows that will be inserted. For the first line c=0 so I used a condition to upload the values from the row only if c!==0, but it stil uploades the values from the first line.
My code looks like this:
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
if ($_FILES["file"]["type"]=='application/vnd.ms-excel')
{
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$qry = mysql_query("SELECT id FROM beneficiari WHERE `nume` = '".$beneficiar."'");
while ($row = mysql_fetch_assoc($qry)){
$id_client=$row['id'];
}
$qry_id_model=mysqli_query("SELECT id FROM modele WHERE `model` = '".$model."'");
while ($row = mysql_fetch_assoc($qry_id_model)){
$id_model=$row['id'];
}
$adresa1 = $adresa.",".$localitate;
if ($c!==0){
$sql = mysql_query(
"INSERT INTO pos_equipments_other
(id_client, model, tid, beneficiar, adresa, agentie, judet)
VALUES
('$id_client','$id_model','$tid','$beneficiar','$adresa1',
'$locatie','$judet')"
);
}
$c = $c + 1;
}
}

PHP How to read specific words and lines then add to MySQL database

I try to read every word after this word #EXTINF:-1
and the next line from the local file and subsequently add the result to MySQL if it does not exist.
The contents of the file looks like this:
#EXTM3U
#EXTINF:-1,name1
http://www.name1
#EXTINF:-1,name2
http://www.name2
#EXTINF:-1,name3
http://www.name3
#EXTINF:-1,name4
http://www.name4
And my code:
$file = file("file.m3u);
array_shift($file);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$getname[] = substr($row, $pos + 1);
} else {
$geturl[] = $row;
} } }
$count = count($getname);
for($i=0; $i < $count; $i++){
$name = $getname[$i];
$url = $geturl[$i];
if (empty($name)) { exit; };
if (empty($url)) { exit; }
$get_user = mysql_query("select * from users where (name = '$name')");
$show_user = mysql_fetch_array($get_user);
$userid = $show_user['userid'];
$get_url = mysql_query("select * from urls where url = '$url'");
$show_url = mysql_fetch_array($get_url);
$urlid = $show_url['urlid'];
if (empty($userid) && empty($urlid)) {
$add_user = "INSERT INTO users(name)
VALUES('$name')";
mysql_query($add_user);
$userid = mysql_insert_id();
$add_url = "INSERT INTO urls(userid, url)
VALUES('$userid', '$url')";
mysql_query($add_url);
$urlid = mysql_insert_id();
}
}
My code cannot read file correctly, because when I try check the line that I had read from file, it does not work.
The info that I try to read:
name = name1
url = http://www.name1
is for every user.
This might have something to do with it
$file = file("file.m3u);
It should be
$file = file("file.m3u");

Mysql display all records

I need an SQL query that displays all the records if its duplicated also. For instance say
select * from table where true and p_id in(1,2,1,1)
displays only records from 1 and 2 but i need it to be repeated when given in while loop.
Update with code:
$cook = unserialize($_COOKIE["pro_cook"]);
foreach ($cook as $something) {
$merc[] = $something;
}
foreach ($size as $new_size) {
$size_array[] = $new_size;
}
$items = count($merc);
$mer = rtrim(implode(',', array_reverse($merc)), ',');
$fulclr = "and p_id in (".$mer.")";
$asd = "(p_id,".$mer.")";
$result = mysql_query("select * from product_details where true ".$fulclr." order by field".$asd."");
Hope this will help
$ids = "1,2,1,1";
$sql = "select * from table where true and p_id in (".$ids.")";
$rec = mysql_query($sql);
$dbData = array();
while($res = mysql_fetch_assoc($rec)) {
$dbData[$res['p_id']] = $res;
}
$ids = explode(',', $ids);
$newArray = array();
foreach ($ids as $id) {
if (!empty($dbData[$id])) {
$newArray[] = $dbData[$id];
}
}

Categories