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.
Related
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
I am trying to do a preview, from a database, and want the preview to be say, 20 words before and after the keyword. I can think of a couple of ways to do this, but seems it would work the server very hard.
One way is to break the data into a word array, with str_word_count(), then search the array, for the word index, and do the math, but it just seems like it would be hitting the server too hard.
Is there a better way of doing this?
"20" is just an example, and would trap for a length less than 20, so I know about trapping bad values. However, I do see other issues that may arise, such as, the keyword appears more than once, or if more than one search word is used, so I know it is not as easy as grab an array and do the math.
EDIT: It looks like the mod added link will do the trick. Will test now. Also for those that asked about the output:
Data: "this would be from the database, and got selected using full text query, the keyword used is 'selected'"
Output wanted: "database, and got SELECTED using full text".
I reckon the biggest drawback is querying those results, regardless of any string operations performed later on, either way it`s gonna cost you performance.
I'd go with javascript on this one, return the data from the PHP and have javascript find the words you`re looking for. It saves on your server's load by letting the browser figure it out.
But if you're dead set on using PHP, i`d go with what you've suggested, transform the string in an array of words and return the words based on the offset given.
in jQuery and javascript it could like like:
jQuery.ajax({
dataType: "json",
url: "path/to/script.php",
complete: response( response ){
// assuming we`re getting a json result
// in the following format:
// {
// "sentence": "This is my sentence with a word that should highlight the first and last 20 words..",
// "word": "hightlight"
// }
var offset = 20;
var output = createHightlight(response.sentence, response.word, offset);
}
});
function createHighlight(sentence, word, offset ){
var string = "";
var words = sentence.split(" ");
var index = words.indexOf(word);
offset = offset !== undefined ? offset : 20;
var start = 0, end = words.length;
if( index - offset >= 0){
start = index - offset;
}
if( index + offset < words.length){
end = index + offset;
}
for( var i = start; i <= end; i++ ){
string += words[i] + " ";
}
return string;
}
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.
I am new to AS3, and I had tried a few times to pass an array from php to AS3. But i can't manage to do it.
But i managed to narrow down the problem to 1 set of code, so wondering what do i need to change it.
When the function is this
function Asandler(event:Event){
var responseVariables:URLVariables = new URLVariables(event.target.data);
nobed = responseVariables.nobed ;
zip = responseVariables.zip;
Location = responseVariables.Location;
price = responseVariables.price;
}
It returns an error Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
But when i change it to
function Asandler(event:Event){
s1.test.text=event.target.data
}
It displays array with no problem, inside the dynamic text field.
php echo part
$solutions = array();
while ($row = mysqli_fetch_assoc($sql))
{
echo "nobed=".$solutions[1]=$row['nobed'];
echo "&zip=".$solutions[2]=$row['zip'];
echo "&Location=".$solutions[3]=$row['Location'];
echo "&price=".$solutions[4]=$row['price'];
}
Test Data string
nobed=100&zip=100&Location=100&price=100
New try, testing it with dynamic text field, it display the whole string.
var receivedValue:String = event.target.data.replace(/^\s+|\s+$/mg, "");
var test:Array = receivedValue.split(",");
s1.test.text =test[0];
But not too sure how to split the string up.
Hi I have a javascript pre-load script that incorporates a php command to pre-load uploaded images for a future onClick action. Anyway I am having trouble removing the LAST comma from the last image the pre-load script pulls from.
Here is the script:
<div style="display:hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
<?php
for ($i = 0; $i < 6; $i++) {
if (!empty($imgs[$i])) {
echo "'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500',";
}
}
?>
)
//--><!]]>
</script>
</div>
Anyway, I need to find out how to remove the last comma from the last image that is uploaded. Not sure how to do this. Please help me! BTW... the images don't have an extension since they are linking to a php image script that resizes them and places them into a watermark. Hope you guys can help me figure!
Think the other way! the comma could be at the start and then you remove it from the first one :)
if (!empty($imgs[$i])) {
$comma = $i == 0? '' : ',';
echo $comma."'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500'";
}
This way doesn't matter if $i is equal to 5, 8 or 139871!
The easiest way to do it is using the php build in implode() function
<?php echo implode(',', $imgs); ?>
And if you want just the first 6 images, you can make an array like so
$imgs = array_slice($imgs, 0, 6);
So the whole thing must look like that:
preload(
<?php
$imgs = array_slice($imgs, 0, 6);
echo implode(',', $imgs);
?>
)
to remove the last comma from a string, just use this:
$string = rtrim($string, ",");
May I suggest a slightly different approach to your problem? Whenever you want to pass data to JavaScript, JSON is probably the thing you want to generate. json_encode() helps you with that. Your script could look like:
var urls = <?php echo json_encode(array_values($imgs)); ?>;
var images = [];
function preload(urls) {
for (var i = 0; i < urls.length; i++) {
var url = 'http://www.samplegallery.com/upload/image.php?img_source_url='
+ encodeURIComponent(urls[i])
+ '&img_resize_to=500';
images[i] = new Image();
images[i].src = url;
}
}
preload(urls);
please note that I've taken the liberty of adding missing semicolons and var declarations to keep your variables local. I have added the array_values() call to make sure you're passing a numerically indexed array, rather than an associative array that would have resulted in an object literal { ... } rather than an array literl [ ... ].
I have also moved the URL building to JavaScript, as I didn't see a reason to keep it in PHP. If you need this to be in PHP and want to avoid the "manual" loop, look into array_map().
Please also note that I'm running your URL fragment through encodeURIComponent() to properly escape whatever it is you're passing in.
A note on security: should your script at /upload/image.php accept arbitrary URLs (and or "local file resources"), consider white-listing the allowed domains and paths.
You could use a foreach...
<?PHP
if ($count = count($imgs)) {
foreach ($imgs as $key=>$img) {
echo "http://www.samplegallery.com/upload/image.php?img_source_url="
. $img . "&img_resize_to=500";
if ($key < $count-1) echo ",";
}
}
?>