February 27, 2013

loop the .append() with selector as variable

Question by user2108245

I am trying to loop the .append() function in order to change the selector each time with different value. But, I don’t know the syntax for the selector in order to meet my target. So, how to change it? Thanks so much!
Ka Ho

<script type="text/javascript">
var a=3;
for (var i=0;i<a;i++)                       {                           
$i.append(i);
}
</script>

<div class="0"></div> // expected: display 0
<div class="1"></div> // expected: display 1
<div class="2"></div> // expected: display 2

Answer by Starx

First of all numeric class and ids are not supported that much as you think it is.

Update your HTML to something like this

<div class="box-0"></div>
<div class="box-1"></div>
<div class="box-2"></div>

Then you can use the script provided by deadlock in his answer.

var a=3;
for (var i=0;i<a;i++) {                           
    $(".box-"+i).append(i); //this is what you need
}
November 6, 2012

How to dynamically create a string in PHP?

Question by All

I have a predefined pattern for building a string, which should be created regularly throughout the script.

$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern

Currently, I am using eval to generate the string in place based on the pattern originally defined. However, as this happens occasionally and eval is generally bad, I wish to find another method.

NOTE that the pattern is defined only one time above all codes, and I can edit the pattern of all the script by one line only. Thus, what makes $string should not be touched for any change.

I tried create_function, but needs the same number of arguments. With eval, I can easily change the pattern, but with create-function, I need to change the entire script. For example, if changing the string pattern to

$str="$first @@ $second"; // One arg/var is dropped

eval Example:

$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("$string = "$str";");

create_function Example:

$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);

Answer by Vulcan

You can use the string formatting capabilities offered by sprintf or vsprintf.

$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);

You can use vsprintf if you wish to pass an array.

$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);

Answer by Starx

Seems to be rather simple thing to me. Use str_replace() and replace based on patterns

$str="$first$ - $second$ @@ $third$"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";

$newstr = str_replace('$first$', $first, $str);
$newstr = str_replace('$second$', $second, $newstr);
$newstr = str_replace('$third$', $third, $newstr);

Find ratio for any number of variables in php?

Question by neha thamman

I want to find ratio for any number of variables in php.

For example: 1:2 10:100:50
30:90:120:150

How can I get such rations?

Answer by Starx

One way would be convert the values to decimal values and covert them to fraction.

I found a function that will do this: [Source]

function decToFraction($float) {
    // 1/2, 1/4, 1/8, 1/16, 1/3 ,2/3, 3/4, 3/8, 5/8, 7/8, 3/16, 5/16, 7/16,
    // 9/16, 11/16, 13/16, 15/16
    $whole = floor ( $float );
    $decimal = $float - $whole;
    $leastCommonDenom = 48; // 16 * 3;
    $denominators = array (2, 3, 4, 8, 16, 24, 48 );
    $roundedDecimal = round ( $decimal * $leastCommonDenom ) / $leastCommonDenom;
    if ($roundedDecimal == 0)
        return $whole;
    if ($roundedDecimal == 1)
        return $whole + 1;
    foreach ( $denominators as $d ) {
        if ($roundedDecimal * $d == floor ( $roundedDecimal * $d )) {
            $denom = $d;
            break;
        }
    }
    return ($whole == 0 ? '' : $whole) . " " . ($roundedDecimal * $denom) . "/" . $denom;
}

Now

$total = 1 / 2;
echo decToFraction($total);

Or, you could use PEAR’s Math_Fraction [Source]

include "Math/Fraction.php";

$fr = new Math_Fraction(1,2); //Put your variable like this    

// print as a string
// output: 1/2
echo $fr->toString();

// print as float
// output: 0.5
echo $fr->toFloat();
May 14, 2012

Using a variable inside an included file from function

Question by Djave

I’d like to have a header.php file throughout my site. I currently have the following:

header.php

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="<?php if(isset($depth)){echo $depth;};?>css/style.css">

functions.php

function include_layout_template($template="", $depth="")
{
    global $depth;
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}

index.php

<?php include_layout_template('header.php', "../"); ?>

But $depth dissappears, I can’t even echo $depth; its just blank. How can I get the depth variable for use in header.php?

Answer by Sergey

You have to rename depth variable in function call

function include_layout_template($template="", $my_depth="")
{
   global $depth;
   //if need $depth = $mydepth

Answer by Starx

Your $depth variable is disappearing, because it is passed as parameter first but then defined to use the global parameter.

I will explain with an example:

$global = "../../"; //the variable outside
function include_layout_template($template="", $depth="")
{
    global $depth; //This will NEVER be the parameter passed to the function
    include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
include_layout_template("header.php", "../");

To solve, simply modify the function parameter other than the depth itself.

function include_layout_template($template="", $cDepth="") { }
May 5, 2012

taking variables from one function to use in another function

Question by Paddy Hallihan

i’m creating a game in javascript for college and i have a button to call a function but i need it to include variables from another function

if i put the function inside the other function where the variables are the button doesn’t call it

is there a way of doing this or to get the variables that were created in the first function and use them in the second function

it is a simple maths game where you get a random number a random sum and another random number
(i.e. 5+7, 4*3, 2/6, etc,)

so i’ve got a function to show the random number using

var ranNum1a=Math.floor(Math.random()*10);

i need the other function to check the users answer but i need to know what the random number was from the other function

Answer by Starx

For simplest case, passing variables to another function might be the best approach to this problem.

Here is an illustration:

fucntion f1(var1, var2) {
    //do you stuff then pass the variable to another function
    f2(var1, var2);
}

function f2(v1, v2) {
    // here v1 will get the value from var1 and v2 from var2 if passed from within the function f1
}
May 3, 2012

how to form select query by range

Question by bonny

hello i have a search engine for my site. i have two selection fields. i would like to give an example:

input_a: 3
input_b: 5

so the queries should look like:

if ( ($input_a == true) && ($input_b == false) ){
        $filter_orders[] = " `col` LIKE '%$input_a%' ";
    } 
    if ( ($input_a == false) && ($input_b == true) ){
        $filter_orders[] = " `col` LIKE '%$input_b%' ";
    } 
    if ( ($input_a == true) && ($input_b == true) ){
        $filter_orders[] = " `col`= `col`>='%$input_a%' AND `col` = `col`<='%$input_b%' ";

now the problem is, that i dont know, if the last query is incorrect or not. the logic behind that will be that in case of my example the range between 3 and 5 should be found.

so 1,2 [3,4,5] 6,7,8…

if there is someone who could help me out i really would appreciate.

thanks a lot.

Answer by Starx

NO, sadly that is everything but correct. It should be something like this.

$filter_orders[] = " `col`>='%$input_a%' AND `col`<='%$input_b%' ";
April 23, 2012

how to change variable when filter is on

Question by bonny

hello i would like to code a filter for an search engine on my site. now i thought it would be the best way to use a simple filter. so my code looks like:

}else if ($filter_a === 1){
        $filter = "WHERE `a` LIKE '%$a%'";
}else if ($filter_b === 1){
        $filter = "WHERE `b` LIKE '%$b%'";
}else if ($filter_c === 1){
        $filter = "WHERE `c` LIKE '%$c%'";
...
}else if ( ($filter_a === 1) && ($filter_b === 1) ){
        $filter = "WHERE `a` LIKE '%$a%' AND `b` LIKE '%$b%'";
}else if ( ($filter_a === 1) && ($filter_c === 1) ){
        $filter = "WHERE `a` LIKE '%$a%' AND `c` LIKE '%$c%'";
... and so on

the problem is that i have 5x N so the permutation of this would be 120 possibilites for $filter

is there a way how i can solve this? if there is someone who could help me out i really would appreciate. thanks a lot.

Answer by Starx

How about this way?

if ($filter_a === 1) {
        $filter[] = "`a` LIKE '%$a%'";
}
if ($filter_b === 1) {
        $filter[] = "`b` LIKE '%$b%'";
}
if ($filter_c === 1) {
        $filter[] = "`c` LIKE '%$c%'";
}
$filter = "WHERE ".implode(" AND ", $filter);
April 20, 2012

Run PHP code when user clicks link and pass variables

Question by user1323294

I need to run a PHP code from external server when user clicks a link. Link can’t lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?

Something like this?

<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?

Answer by Anwar

use something like this in you page with link

Some text

in the same page put this somewhere on top

<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";

$.ajax({

url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
        alert('success');//do something
    }

});
return false;
});
});

</script>

on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple

<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>

hope that helps

Answer by Starx

You can do this with an ajax request too. The basic idea is:

  1. Send ajax request to runcode.html
  2. Configure another AJAX to trigger from that page

Considering, this as the markup

<a id="link" href="runcode.html'">Test</a>

JS

$("#link").on("click", function() {
    $.get("runcode.html", { "id" : ID }, function(data) {
       //on success 
    });
    return false; //stop the navigation 
});
April 12, 2012

Creating variables and reusing within a mysql update query? possible?

Question by miss_piggy

I am struggling with this query and want to know if I am wasting my time and need to write a php script or is something like the following actually possible?

UPDATE my_table 
SET @userid = user_id 
AND SET filename('http://pathto/newfilename_'@userid'.jpg')
FROM my_table 
WHERE filename 
LIKE '%_%' AND filename 
LIKE '%jpg'AND filename 
NOT LIKE 'http%';

Basically I have 700 odd files that need renaming in the database as they do not match the filenames as I am changing system, they are called in the database.
The format is 2_gfhgfhf.jpg which translates to userid_randomjumble.jpg

But not all files in the database are in this format only about 700 out of thousands. So I want to identify names that contain _ but don’t contain http (thats the correct format that I don’t want to touch).

I can do that fine but now comes the tricky bit!!

I want to replace that file name userid_randomjumble.jpg with http://pathto/filename_userid.jpg So I want to set the column user_id in that row to a variable and insert it into my new filename.

The above doesn’t work for obvious reasons but I am not sure if there is a way round what I’m trying to do. I have no idea if it’s possible? Am I wasting my time with this and should I turn to PHP with mysql and stop being lazy? Or is there a way to get this to work?

Answer by Bohemian

Yes you can do it using straightforward SQL:

UPDATE my_table 
SET filename = CONCAT('http://pathto/newfilename_', userid, '.jpg')
WHERE filename LIKE '%_%jpg'
AND filename NOT LIKE 'http%';

Notes:

  • No need for variables. Any columns of rows being updated may be referenced
  • In mysql, use CONCAT() to add text values together
  • With LIKE, an underscore (_) has a special meaning – it means “any single character”. If you want to match a literal underscore, you must escape it with a backslash ()
  • Your two LIKE predicates may be safely merged into one for a simpler query

Answer by Starx

Yes it is possible without the php. Here is a simple example

SET @a:=0;
SELECT * FROM table WHERE field_name = @a;
March 19, 2012

Using variables to check if certain things are allowed

Question by Marshall Mathews

i was thinking of implementing features of turning on and off certain things on my website like registering and logging of.
I could include a file with variables like so

<?php
$upload = 1;
$register = 1;
?>

And then in suppose my register.php file i could do a check like so

if($register == 1){
//Show form
} else { echo "Registration is disabled" }

i was wondering if this would be a security issue as i read somewhere that stuff can be suffixed the url to bring the same effect
Like so

register.php?register=1

But that does not work if register globals are turned off, is this much of a security issue?

Answer by Starx

NO

register.php?register=1 will only be accessed from $_GET['register']
Unless you’re using an older version of PHP with register_globals turned on Thanks Lex

If you are configuring some features on the server, I suggest you use sessions instead.

$_SESSION['upload'] = 1;
$_SESSION['register'] = 1;

Unlike constants, they can be changed, if some criteria is met.

And register_globals() is removed from the latest PHP 5.4.0, so, dont use that.

...

Please fill the form - I will response as fast as I can!