Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

PHP string concatination

Posted on 2011-02-12
13
Medium Priority
?
350 Views
Last Modified: 2012-05-11
Hello,

basically what I am trying to do is to create a basic wizard for creating a query in PHP, interfacing with a MYSQL database. I can work all that. however I am having a problem with concatinating a string properly. my code is as follows:

<?php $tableselection = $_POST["table"];

include ("connection.php");




/*variables used:
$tableselection - tablename
$collum_selections[] - collum selections
$number_menus - number of collums in a table
*/

echo"Table selected:     $tableselection<br/>";

?>





<FORM method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?

/////////////////////////// select columns///////////////////////////


$con = mysql_connect($server,$username,$password);

mysql_select_db($databasename, $con);



$result = mysql_query("SHOW COLUMNS FROM SystemUsers");

//$result = mysql_query("SHOW COLUMNS FROM $tableselection");

$number_fields=mysql_num_rows($result);

//echo "<input type='hidden' name='filtercol_". $i ."' value='". $row[0] ."' />";

echo "<input type='hidden' 'text' name='number_fields' value='$number_fields' />";

$i=0;
while($row = mysql_fetch_array($result, MYSQL_NUM))


{
//    echo "Collum selected :        {$row[0]}";


//echo "Complete sum of fields is:   $number_fields";

//<SELECT name=field_function.$i>
echo"
<SELECT name=field_function[]>
<OPTION value=''>please select</OPTION>
<OPTION value='{$row[0]}, '>None</OPTION>
<OPTION value='AVG({$row[0]}), '>Average</OPTION>
<OPTION value='sum( {$row[0]}) as Total {$row[0]}'>Sum</OPTION>
<OPTION value='COUNT({$row[0]}), '>Count</OPTION>
<OPTION value='$i'>$i</OPTION>
</SELECT>
<br/><INPUT TYPE = 'Text' NAME = 'field_filter[]'><br/>";

$i++;

}

mysql_close($con);

//echo "<input type=Submit value=enter>";

?>
<input type="submit" />
</form>



<?

// passes variables from the above form
$field1 = $_POST['number_fields'];
echo "Number of rows          $field1<br/>";

$field2 = $_POST['field_function'];

$field3 = $_POST['field_filter'];

//counts the number of elements in array
$extra1 = count($field3);

echo "<br/>the number of extra string sectons needed is:  $extra1  <br/>";


$G = 0;
while ($G <= $field1) {
//outputs the results
echo $field2[$G];
echo "<br/>";
// creates the string main sql string
$querystring2 = $querystring2. $field2[$G];
$G++;  
}

//foreach( $field3 as $key => $value){
//      echo "i bet this dont bleedin work <br />";
//}

$H = 0;
while ($H <= $field1){
echo "<br/>";
echo $field3[$H];
// creates the extra sql string
//$querystring3 = $querystring3.$field3[$H]." AND ";
$querystring3 = $querystring3.$field3[$H];
$H++;  
}
echo "extra string here is: $querystring3";

?>

there seems to be 2 problems.
1, for some reason my code will not count the number of values in an array. the array comes from a textbox,  field_filter[] .

basically what I am trying to do is to provide a facility for the user to select a collum and if required add a value to be passed into a MYsql SELECT........ From..........where statement.


2, it adds multiple " AND " to the end of the string

the code for problem 2 is:
//$querystring3 = $querystring3.$field3[$H]." AND ";
$querystring3 = $querystring3.$field3[$H];

if I use the one that is commmented out then it will add multiple 'AND' on the end of the string, but if I miss out the .AND on the end, it adds the requisite number of values.



here is a URL for what I have working so far!
http://www.gavinbuczko.co.uk/phpreportmakerstage2.php

I am sure it is something silly, but I cant see what.

thanks,

Gavin


0
Comment
Question by:GPB1983
  • 7
  • 6
13 Comments
 
LVL 4

Accepted Solution

by:
JayDiablo earned 2000 total points
ID: 34879013
The foreach on $field3 should work, but try removing the $key => $value bit, so it looks more like this:

foreach ($field3 as $value) {

}

Open in new window


It seems to me that it should've worked even with the association mapping you had before.  Your array doesn't come in with any keys (just numerical indexes), so that syntax isn't necessary.

If I understand what you're trying to do correctly (insert an AND between each item in the $field3 array), you may want to try out the PHP implode() function:  http://www.php.net/implode

$querystring3 = implode(' AND ', $field3);

Open in new window


The advantage of using implode vs. string concatenation is that you don't have to strip off that extra AND when you're done looping.  Plus it's a lot less code. ;)
0
 

Author Comment

by:GPB1983
ID: 34879208
Hi,

thanks for your quick reply, I have tried what you suggested and can see where it would work,  however I am having a problem with it. it seems to append loads of AND on the end.

here is the section of code I have changed.


// checks for null values $field3 array
$H = 0;
$L = 0;
while ($H <= $field1){
if ($field3[$L] !== "")
{
$L++;
}
$H++;
}

echo "the number of full values is $L;";



//$pieces = array("Hello", "World,", "I", "am", "Here!");

$gluedTogetherSpaces = implode(" AND ", $field3);

//for($i = 0; $i < count($field3); $i++){
for($i = 0; $i <= $L; $i++){
//      echo "Piece #$i = $pieces[$i] <br />";
}
echo "final section of SQL string = $gluedTogetherSpaces <br />";


as can be seen here:  http://www.gavinbuczko.co.uk/phpreportmakerstage2.php

please can you help me with this. thanks,
regards, Gavin
0
 
LVL 4

Expert Comment

by:JayDiablo
ID: 34879319
I assume you see it adding a lot of ANDs because you only filled out one or two of the text fields right?

You can filter out the empty elements by using PHP's array_filter method (no callback function necessary if you just want to filter out empty array elements):  http://www.php.net/array_filter

$field3 = array_filter($field3);
$gluedTogetherSpaces = implode(" AND ", $field3);

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:GPB1983
ID: 34879409
thanks for the quick reply,

I need to filter out the empty values as that seems to be the problem.  I have tried:
print_r(array_filter($field3, " ")); but I get this message

Warning: array_filter() [function.array-filter]: The second argument, ' NULL ', should be a valid callback in /home/jeekuag/public_html/phpreportmakerstage2.php on line 100

I am sorry but I dont know any other way to represent a null value.

thanks for your help so far. please can you explain this further, thankyou.

regards, Gavin
0
 
LVL 4

Assisted Solution

by:JayDiablo
JayDiablo earned 2000 total points
ID: 34879438
The second parameter of array_filter is optional.

As per the documentation:

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

print_r(array_filter($field3));

Open in new window


In your case, the empty string "" will evaluate as FALSE, so any array elements that are empty will be removed by array_filter.

For example:

$field3 = array(
  '', 'one', 'two', '', '', 'three'
);

print_r(array_filter($field3));

Open in new window


Gives this output:


Array
(
    [1] => one
    [2] => two
    [5] => three
)

Notice that the empty values were removed (and the numerical indexes were retained, but that shouldn't matter for your implementation).
0
 

Author Comment

by:GPB1983
ID: 34879465
I have tried you suggested and it still gives me the same problem. $field3 is already poppulated earlier in the code, so am I right in assuming that:
$field3 = array(
  '', 'one', 'two', '', '', 'three'
);
 isnt needed, as it creates an array?


thanks,
regards,
gavin
0
 
LVL 4

Expert Comment

by:JayDiablo
ID: 34879477
Correct, I added that piece just to show you an example of how array_filter works on an array that has empty values.

When you say it "gives me the same problem", do you mean it gives you the error you posted above?  Or do you mean that it adds too many "AND"s?

If it's giving you that error message, could you paste that part of the code?

If you're getting too many ANDs, could you paste a print_r of $field3 when it's doing this?
0
 

Author Comment

by:GPB1983
ID: 34879490
Hi,

thanks for the reply, I am sorry I didnt explain it clearly.
when I use your code, I get this as the output.
Array ( [0] => alpha [1] => beta [2] => charlie [3] => echo [4] => golf [5] => [6] => [7] => [8] => )

regards, Gavin
0
 
LVL 4

Expert Comment

by:JayDiablo
ID: 34879534
That's the output of print_r(array_filter($field3)) ?
0
 

Author Comment

by:GPB1983
ID: 34879587
0
 
LVL 4

Expert Comment

by:JayDiablo
ID: 34879655
Hmm, that's odd.

Could you paste this code into a new php file on your server and shoot me a link (or fill out the first text box, leave the second one empty, and paste me what it outputs after submitting)?

It's just a simple test case to verify that array_filter is working as it should:

<form method="post" action="">
<input type="text" name="fields[]" />
<input type="text" name="fields[]" />
<input type="submit" />
</form>

<?php
$field3 = $_REQUEST['fields'];

print_r($field3);
print_r(array_filter($field3));

Open in new window

0
 

Author Comment

by:GPB1983
ID: 34879662
mate,

I scrapped the lot of it and started again! basically I has the textbox and a select menu in the same loop!  thanks you all you help and multiple replies! EE needs more people like you!  thanks a million mate.

regards,  Gavin
0
 

Author Closing Comment

by:GPB1983
ID: 34879673
[u][/u][i][/i][b]best damn guy on here![/b]
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

963 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question