How to get values separated with comma from database using PHP - php

I have four files named comma separated in one field in database like this file1,file2,file3,file4. It may change depending on files uploading. User can upload maximum 4 files, minimum one file. But I was not able to get it. I used explode but it's taking too long.
I am using this code:
$imagefiles = $row["imagefiles"];
$cutjobs = explode(",", $imagefiles);
$cutjobs1 = count($cutjobs);
$image1 = $cutjobs[0];
$image2 = $cutjobs[1];
$image3 = $cutjobs[2];
$image4 = $cutjobs[3];
if (empty($image1)) {
$imagefiles1 = "";
} else {
$imagefiles1 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image1;
}
if (empty($image2)) {
$imagefiles2 = "";
} else {
$imagefiles2 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image2;
}
if (empty($image3)) {
$imagefiles3 = "";
} else {
$imagefiles3 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image3;
}
if (empty($image4)) {
$imagefiles4 = "";
} else {
$imagefiles4 = 'http://projects.santabantathegreat.com/glassicam/uploads/'.$registerid.
"/".$viewjobsid.
"/".$image4;
}
}
$data[] = array( 'imagearray' => array($imagefiles, $imagefiles1, $imagefiles2, $imagefiles3));
}
echo json_encode($data);
}
I am getting output like this :
[{"imagearray":["http:\/\/projects.santabantathegreat.com\/glassicam\/uploads\/60\/30\/file1.jpg","http:\/\/projects.santabantathegreat.com\/glassicam\/uploads\/60\/30\/file2.jpg",""]}]
If you see this imageArray last one is getting "" that means some in file1, file2, file3, file4 one name is missing so I want to show if any filename is not there means I don't want to show null values with ""
i have a field with file1,file2,file3,file4 so times we will have file1,file3 then remaining will not there so i want to count file name separated with commas and if file1 is there is should print that if file3 is there not then it shouldn't show with ""

You could have used split(), but its deprecated in PHP 5.3.0. So, instead you are left with:
explode() which is substantially faster because it doesn't split based on a regular expression, so the string doesn't have to be analyzed by the regex parser.
or
preg_split() which is faster and uses PCRE regular expressions for regex splits.
With preg_split() you could do:
<?php
$encoded_data = json_encode($data);
$images = preg_split('/,/', $encoded_data->imagearray);
?>
I would say that explode() is more appropriate for this.
<?php
$encoded_data = json_encode($data);
$images = explode(',', $encoded_data->imagearray);
print_r($images);
?>
Resources: What is the difference between split() and explode()?
You shouldn't have empty values in your array in the first place. But if you still have any empty values you could use preg_split() something like this one here.
Similarly you can use array_filter() to handle removal of values (null, false,'',0):
print_r(array_filter($images));
There are so many answers here in this forum that do exactly what you are asking: Remove empty array elements, Delete empty value element in array.

Related

How do i separate my array strings delimiter (|) using implode function of php

How do I separate my array strings delimiter (|) using the implode function of PHP something like the below String
|Java||PHP||Bootstrap||HTML||CSS|
Actually, I am using a double delimiter to differentiate tags like SQL and MySQL because LIKE "%sql%" will return MySQL results as well. Should be LIKE "%|sql|%"
What I have tried:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
array_push($array_service_offer, $selectedOption);
}
//$service_offer = implode(',',$array_service_offer);
$service_offer = '|' . implode('||', $array_service_offer) . '|';
} else {
$service_offer = "";
}
First of all, according to #Qirel comment, I would also recommend to use $array_service_offer[] = $selectedOption; instead of array_push($array_service_offer, $selectedOption);
now for separation, there are several solutions.
One solution is that:
1- to remove first and last | character (it is like trimming)
2- to explode the trimmed string using || delimiter
for that you may use the following code:
$service_offer_trimmed = preg_replace("~(^\|)|(\|$)~", "", $service_offer);
$service_offer_array = explode('||', $service_offer_trimmed);
The other solution is to use straight forward preg_replace function to separate the string. the command follows:
$service_offer_array = preg_split("~(^\|)|(\|\|)|(\|$)~", $service_offer, 0, PREG_SPLIT_NO_EMPTY);
And one more professional solution is that to store your data in database in JSON format rather than delimited code and then when you need to search in your database you may use MySql JSON_CONTAINS function rather than LIKE command.
I have not personally made a performance check on both two solutions but if it not a big database, then it is not a big concern as well.
Therefore, you initial code to get the data and store it into the database will be:
$array_service_offer = array();
if (isset($_POST['service_offer'])) {
foreach ($_POST['service_offer'] as $selectedOption) {
$array_service_offer[] = $selectedOption;
}
}
// $json_service_offer will be saved to the database
$json_service_offer = json_encode($array_service_offer);
the manual on how to use JSON_CONTAINS is in the following link:
12.17.3 Functions That Search JSON Values

Array values not inserting into database separately

I'm not sure exactly how to phrase this so I will show an example. I'm gathering input values in javascript and passing to my php page where I am trying to insert those values in a database.
Instead of inserting separate values it is inserting the entire string.
Part of my javascript below:
var form = document.forms[0];
var txtS = form["bulletlabels"];
var len = txtS.length;
var bulletlabels = "";
for(i=0;i<len;i++) {
bulletlabels += '"'+[i]+'_'+(txtS[i].value)+'_label",';
}
when I do an alert(bulletlabels); I get this:
"0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",
On my php page I have:
$bulletlabels = array($_POST['bulletlabels']);
$length = count($bulletlabels);
for ($i = 0; $i < $length; $i++) {
mysqli_query($con,"UPDATE bullets SET bullettitle = '".$bulletlabels[$i]."' WHERE bulletrow = ($i+1)");
}
This inserts the below string into the database on ONE Row which is not the desired effect:
"0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",
But here is the key to my confusion - if I manually type the string in, it inserts onto individual database rows as desired.
This inserts values individually as desired when typed manually:
$bulletlabels = array("0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",);
Does NOT work and inserts the full concatenated string:
$bulletlabels = array($_POST['bulletlabels']);
Hope I explained well enough - arrays elude me.
EDIT:
Fix for the trailing comma:
var delim = "";
for(i=0;i<len;i++) {
bulletlabels += delim+[i]+'_'+(txtS[i].value)+'_label';
delim = ",";
}
Reference link for trailing comma fix:
Can you use a trailing comma in a JSON object?
Try changing the following line:
$bulletlabels = array($_POST['bulletlabels']);
to
$bulletlabels = explode(',', $_POST['bulletlabels']);
Also do not add quotes in your javascript:
bulletlabels += '"'+[i]+'_'+(txtS[i].value)+'_label",';
should be
bulletlabels += [i]+'_'+(txtS[i].value)+'_label,';
Explanation:
Currently, $bulletlabels is an array with one element, and this element is the following string: "0_Lot Size_label","1_Rooms_label","2_Bathrooms_label","3_Basement_label",. However, you want to have an array with several strings. That's why you need to use the explode function to convert it into a proper array.
Note:
Make sure not to include , in the label names, as it will break with this implementation. If you need to be able to use , too, you should use json functions.

GET_CONTENT name from txt file

i have this list on name.txt file :
"name1":"Robert"
"name2":"George"
"name3":"Flophin"
"name4":"Fred"
in a web page i need a php code that takes only the name of the person by the name 1 2 3 4 id.
I've use this in test.php?id=name2
$Text=file_get_contents("./name.txt");
if(isset($_GET["id"])){
$id = $_GET["id"];
$regex = "/".$id."=\'([^\']+)\'/";
preg_match_all($regex,$Text,$Match);
$fid=$Match[1][0];
echo $fid;
} else {
echo "";
}
The result should be George ,
how do i change this to work??
Mabe is another way to do this more simply?
$file=file('name.txt');
$id = $_GET["id"];
$result=explode(':',$file[$id-1]);
echo $result[1];
Edit: $result[1] if you want just name.
Heres an ugly solution to your problem, which you can loop trough.
And Here's a reference to the explode function.
<?php
$text = '"name1":"Robert"
"name2":"George"
"name3":"Flophin"
"name4":"Fred"';
$x = explode("\n", $text);
$x = explode(':', $x[1]);
echo $x[1];
Load the text file into an array; see Text Files and Arrays in PHP as an example.
Once the array is loaded you can reference the array value directly, e.g. $fid = $myArray['name' . $id]. Please refer to PHP how to get value from array if key is in a variable as an example.

searching for a string while looping

I am trying to format another sites data to insert into my database. He wants to close his site, so is giving me his sites listings. But im having to format his data from his flatfile database, to go into my mysql database.
Im looping through his text file, and getting his values. Then formatting as needed before inserting them into my DB.
Because our sites use completely different storage formats and fields, im having a few problems with something.
My site has a designer field. His doesnt. so im trying to search through his description field to find a match within my designer table. If there is a match i want to get the designer ID to insert into the designer id field. But i cant get this code to work.
Could someone please suggest a fix? or if theres a better way to do this?
$fp = fopen('listings.txt','r');
if (!$fp) {echo 'ERROR: Unable to open file.'; exit;}
$loop = 0;
while (!feof($fp)) {
$loop++;
$line = fgets($fp,1024); //use 2048 if very long lines
$field[$loop] = explode (' ', $line);
$get_designers = mysql_query("SELECT * FROM dress_designers");
$row_designers = mysql_fetch_array($get_designers);
$totalRows_designers = mysql_num_rows($get_designers);
do{
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
$mystring = strtolower($field[$loop][8]);
$findme = strtolower($row_designers['designer_name']);
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
$designer = "Other";
} else {
$designer = "Siopa Rince";
}
} while ($row_designers = mysql_fetch_assoc($get_designers));
$fp++;
}
fclose($fp);
I only put "Siopa Rince" as a test. But this isnt working. If i take the text from the file, and paste it in the $mystring and put siopa rince in $findme... it works.
Any suggestions would be greatly appreciated!
Thanks,
Danny
OK... what about just entering the info as is? I tried a few different ways, but the result is returning null...
After i insert the data, ill use searches to join the required row to get an ID:
SELECT dress_test.dress_title, (
SELECT dress_designers.designer_id
FROM dress_designers
WHERE MATCH (
dress_test.dress_desc
)
AGAINST (
'dress_designers.designer_name'
IN boolean MODE
)
) AS real_designer_id
FROM dress_test
Another version:
SELECT dress_test.dress_title, dress_designers.designer_name
FROM dress_test
JOIN dress_designers ON MATCH(dress_test.dress_title, dress_test.dress_desc) AGAINST
('dress_designers.designer_name' in boolean mode)
Any other suggestions??
Your first assignment to $row_designers uses mysql_fetch_array, while your second uses mysql_fetch_assoc
Instead of do { ... } while, why not just while () { ... }
Remove this line $row_designers = mysql_fetch_array($get_designers);
And turn your loop into...
while ($row_designers = mysql_fetch_assoc($get_designers)) {
// string search here
}
Everything else looks fine - if you're having troubles, check the values with either echo to print string or print_r to print arrays.

php select specific content from input file to put in array elements

I have an input file (exert from file shown below) with multiple lines that I need to select specific text from and put each selection into an array element:
exert from input file:
"BLOCK","PARTNO"
"ELEMENT","HEADER-"
"NAME","1AB000072186"
"REVISION","0000"
"PARTSHAPE","RECT_074_044_030"
"PACKAGE","120830E"
"PMABAR",""
"PARTCOMMENT","CAP-TANT*150uF*20%*10V7343*4.3mm"
"ELEMENT","PRTIDDT-"
"PMAPP",1
"PMADC",2
"ComponentQty",2
"BLOCK","PARTNO"
"ELEMENT","HEADER-"
"NAME","1AB030430005"
"REVISION","0000"
"PARTSHAPE","RECT_072_042_030"
"PACKAGE","120830E"
"PMABAR",""
"PARTCOMMENT","1.0000 Amp SUBMINIATURE FUSE"
"ELEMENT","PRTIDDT-"
"PMAPP",2
"PMADC",0
"ComponentQty",1
"BLOCK","PARTNO"
"ELEMENT","HEADER-"
"NAME","1AB030430001"
"REVISION","0000"
"PARTSHAPE","RECT_072_042_030"
"PACKAGE","120830E"
"PMABAR",""
"PARTCOMMENT","2.0000 Amp SUBMINIATURE FUSE"
"ELEMENT","PRTIDDT-"
"PMAPP",2
"PMADC",0
"ComponentQty",1
Notice that after each occurrence of the line with the phrase "ComponentQty" the content begins repeating...
Where I need the PartNumber that is next to the occurrence of "NAME" in one dimension of the array element and the content next to the occurrence of "PARTSHAPE" in the second dimension for each element. I am very confused on how to do this though...please help!!!
$fh = fopen('yourfile.txt', 'rb');
$found_stuff = array();
$last_component = null;
while($line = fgets($fh)) { // read a line
$parts = explode(',', $line); // split into components
switch($parts[0]) { // based on which key we're on
case '"NAME"':
$last_component = $parts[1]; // save the key's value
break;
case '"PARTSHAPE"':
$found_stuff[$last_component] = $parts[1]; // store the partshape name
break;
}
}
fclose($fh);
This should do the basic work. Read a line, explode it into pieces where commas occur. The first part will be the "key", the second part will be the value. Then simply keep reading until we either hit a NAME or a PARTSHAPE key, then store the values as appropriate.
Note that I've not stripped the double-quotes off the values. That's left as an exercise to the reader. This code also assumes that the file's format is regular and that a "NAME" will show up before any PARTSHAPE lines, and there'll be a perfect 1:1 alternation between NAME/PARTSHAPE lines. If you get two PARTSHAPES in a row, you'll lose the first one. And if a PARTSHAPE shows up before the first NAME is encounted, you'll sorta lose that one too.
The following steps worked for me:
The section pasted in my OP (repeating many times more) is defined as $PartNoContents
and $BlockData[] is the array that I need to paste selections from $PartNoContents into.
$PartNoContents = str_replace('"', '', $PartNoContents);
$PartLines = explode("\n", $PartNoContents);
$PartData = array();
foreach ($PartLines as $PartLine){
$PartData[] = explode(',', $PartLine);
}
for($p=0;$p<count($PartLines);$p++){
if ( isset( $PartData[$p][1] ) && !empty( $PartData[$p][1] ) ){
$p1 = str_replace(chr(13), '', $PartData[$p][1]);
if ( isset($BlockData[$b][0]) && !empty($BlockData[$b][0]) && $BlockData[$b][7]==$p1 ){
$BlockData[$b][13] = str_replace(chr(13), '', $PartData[$p+$PartDataIncNum][1]);
$p = count($PartLines) ;
}
}
}

Categories