Convert MySQL insert from comma separated to piping - php

I have a problem to insert detail from one table into another in MySQL table. The compatibility differs as the one table accepts commas to separate detail in a column and the other table accepts piping. What PHP code can I use to convert the commas into piping?
Ok guys let me re-phrase. I am doing a data dump from another db to my db, the problem is that the content formats of the two tables aren't compatible, meaning that my one table uses UPPERCASE and the other one uses camelCase, and that the one uses (,) without spaces behind or infront where the other table uses (|) with spaces on both sides. I'm lost and need help

Take a look at http://php.net/manual/en/function.strtr.php

I found the answer:
$replace = str_replace(", "," | ", $result2);

Related

How to extract one value from imploded array in MySQL row

I'm using implode to insert few values into one row in MySQL database.
implode(' ', $_POST['tag']);
Assuming that I have table named product with row named tags with 3 different values that inserted inside like this:
usb adapter charger
I have tried using this method using like operator (%), but that didn't worked.
$sql = "SELECT * FROM product WHERE tags='%usb%'";
How can I extract only one value from the imploded array using WHERE in mysql query?
I agree with the comments about re-designing the database. At first read it seems that using LIKE would definitely get the result you want but after reading #Patrick Q's pan - panther example, it makes a lot sense that LIKE is not really a good solution. There are ways to get exactly the tag string you're looking for but it may hurt the performance and the query will be longer and complex. Hence the following are to demonstrate how the query would look like with your current tags data value:
MySQL query:
SELECT tags,
SUBSTRING_INDEX(SUBSTRING_INDEX(tags,' ',FIND_IN_SET('usb',REPLACE(tags,' ',','))),' ',-1) v
FROM mytable
HAVING v = 'usb';
As you can see, there are a few functions being used just to get the exact string from the data cell. Since your example data was separating with spaces and FIND_IN_SET identify value separation by comma, REPLACE take place on the tags column first to replace spaces with comma. Then with SUBSTRING_INDEX twice to get the string using the location extracted in FIND_IN_SET. Finally at the end HAVING to get only the tag you're looking for.
Further demo here : https://www.db-fiddle.com/f/joDa7MNcQL2RakTgBa7qBM/3

How to handle an array in a SQL field?

I have a feed that comes from the State of Florida in a CSV that I need to load daily into MySQL. It is a listing of all homes for sale in my area. One field has a list of codes, separated by commas. Here's one such sample:
C02,C11,U01,U02,D02,D32,D45,D67
These codes all mean something (pool, fenced in area, etc) and I have the meanings in a separate table. My question is, how should I handle loading these? Should I put them in their own field as they are in the CSV? Should I create a separate table that holds them?
If I do leave them as they are in a field (called feature_codes), how could I get the descriptions out of a table that has the descriptions? That table is simply feature_code, feature_code_description. I don't know how to break them apart in my first query to do the join to bring the description in.
Thank you
As a general rule, csv data should never stored in a field, especially if you actually need to consider individual bits of the csv data, instead of just the csv string as a whole.
You SHOULD normalize the design and split each of those sub "fields" into their own table.
That being said, MySQL does have find_in_set() which allows you sort-of search those csv strings and treat each as its own distinct datum. It's not particularly efficient to use this, but it does put a bandaid on the design.
You should keep the information about feature codes in a separate table, where each row is a pair of house identifier, and feature identifier
HouseID FeatureID
1 C07
1 D67
2 D02
You can use explode() to separate your CSV string : http://php.net/manual/en/function.explode.php
$string = 'C02,C11,U01,U02,D02,D32,D45,D67';
$array = explode(',', $string);
Then with your list of feature_codes you can easily retrieve your feature_code_description but you need to do another query to get an array with all your feature_codes and feature_code_description.
Or split your field and put it in another table with the home_id.
You can save it in your DB as is and when you read it out you can run the php function explode. Go check that function out. It will build an array for you out of a string separating the values by whatever you want . In your case you can use:
$array_of_codes = explode(",", $db_return_string);
This will make an array out of each code separating them by the commas between them. Good luck.

PHP Imported CSV data cut short when encounterng a comma

I have a simple PHP script that loops over data in a CSV file, and adds the records to the database accordingly. One of my fields is a description field, but that description field itself has a comma (or multiple comma's) in it. It seems as though data for that field is only read up until the comma, however the next field is correct, so it is not as though the field after that is the remainder of the description, is is using the next column which is right.
Am I supposed to escape the comma? I am adding this data to a MySQL database, could that be where the issue is being caused?
My SQL query could be something like:
$description = $data[7]; //description column eg: "hello, my name is xxxxx, I am old"
INSERT INTO tblsomething (id, description) VALUES ($id, '$description');
The above statement only inserts the description as "hello" and nothing after the first comma it encounters.
Any ideas why this is?
Many thanks,
Simon
EDIT: This is solved, apologies to all as it was a silly mistake. It appears that the person who did the front end was creating arrays of content using the patter ',' to split the content. IT seems that the description - although supposed to be one array entry - was being split into multiple entries due to it containing comma's. This will be solved by using a more rare character like the pipe symbol to create our separators.
Thanks to all
Because it's not a CSV file. Fields in a CSV file that contain commas are supposed to be delimited by double quotes; this way the CSV functions in PHP will handle them properly.

How to read a bulk data feed via php?

I have a large file that I would like to read via php, and then insert various fields into MySQL.
Each file in the feed is in plain text format, separated into columns and rows. Each record has the same set of fields. The following are the delimiters for each field and record:
Field Separator (FS): SOH (ASCII character 1)
Record Separator (RS) : STX (ASCII character 2) + "\n"
If I look at the first few lines of the file they look like this:
#export_dateapplication_idlanguage_codetitledescriptionrelease_notescompany_urlsupport_urlscreenshot_url_1screenshot_url_2screenshot_url_3screenshot_url_4screenshot_width_height_1screenshot_width_height_2screenshot_width_height_3screenshot_width_height_4
#primaryKey:application_idlanguage_code
#dbTypes:BIGINTINTEGERVARCHAR(20)VARCHAR(1000)LONGTEXTLONGTEXTVARCHAR(1000)VARCHAR(1000)VARCHAR(1000)VARCHAR(1000)VARCHAR(1000)VARCHAR(1000)VARCHAR(20)VARCHAR(20)VARCHAR(20)VARCHAR(20)
#exportMode:FULL
I am struggling to no where to start in order to read this file into PHP, can anyone help with the basic PHP to read each record, and assign a variable to each field, which I then will be able to write into MySQL. I can handle the writing into SQL once I have the various fields set up.
Thanks in advance,
Greg
files greator than 2gb cant be read in PHP (32 bit limit).
For lower size use simple fopen function
And inserting mysql is all the work of macthing patterns and inserts.
If structure of table is same every row then better make it manual once and then just execute inserts by extracting values either by regex or other functions like explode and split .
If every line has delimiters between each field, you may look at fgetcsv().
When you use fgetcsv() on a line, it will return an array with the contents from that line. Since you have several lines, put the funciton inside a while()-loop (look at example #1)

How to replace all instances of a particular value in a mysql database with another?

I'm looking for a MySQL equivalent of what str_replace is for PHP. I want to replace all instances of one word with another, I want to run a query that will replace all "apples" with "oranges".
The reason why:
UPDATE fruits SET name='oranges' WHERE name='apples';
isn't going to work for my situation, is because I often times have multiple words in a table row separated by commas like: "apples, pears, pineapples". In this case I want just apples to be replaced by oranges and pear and pineapples to stay in tact.
Is there any way to do this?
You have a database design problem, as Ignacio has pointed out. Instead of including separate pieces of information included in a single column, that column should become a separate table with one piece of information per row. For instance, if that "fruits" field is in a table called "hats", you would have one table for "hats" with a column "hat_id" but no information about fruits and a second column "hat_fruits" with two columns, "hat_id" and "fruit_name". In your example, the given hat would have three rows in "hat_fruits", one for each fruit.
Once you implement this design (if you have control of the database design) you can go back to use the simple UPDATE command you originally had. In addition, you will be able to index by fruit type, search more easily, use less disk space, validate fruit names, and not have any arbitrary limit on the number of fruits that fit into the database
That said, if you absolutely cannot fix the database structure, you might try something like this:
REPLACE(REPLACE(CONCAT(',', fruits, ','), ', ', ','), ',apples,', ',oranges,')
This monstrosity first converts the fruits field to begin and end with commas, then removes any spaces before commas. This should give you a string in which fruit names are unambiguously delimited by commas. Finally, it replaces the ,apples, (note the delimiters) with ,oranges,.
After that, of course, you ought to strip off the beginning and ending commas and put back the spaces after the commas (that's left as an exercise for the reader).
Update: Okay, I couldn't resist looking it up:
REPLACE(TRIM(',' FROM REPLACE(REPLACE(CONCAT(',', fruits, ','), ', ', ','), ',apples,', ',oranges,')), ',', ' ,')
Note that this isn't tested and I'm not a MySQL expert anyway — I don't know if MySQL has function nesting issues or anything like that.
PS: Don't tell anyone I was the one who showed you this!
Not reliably. There is REPLACE(), but that will only work until you decide to add pineapples to your menu.
Putting your database in First Normal Form and then using UPDATE is the only reliable solution.
I think you want to use REPLACE():
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.
Below will replace all occurances of 'apples' with 'oranges' in the 'Name' column for all the rows in the 'Fruits' table.
UPDATE fruits SET Name=REPLACE(Name,'apples','oranges')

Categories