Solved

PHP string concatination

Posted on 2011-02-12
13
324 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 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:GPB1983
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 4

Expert Comment

by:JayDiablo
Comment Utility
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
Comment Utility
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
Comment Utility
That's the output of print_r(array_filter($field3)) ?
0
 

Author Comment

by:GPB1983
Comment Utility
0
 
LVL 4

Expert Comment

by:JayDiablo
Comment Utility
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
Comment Utility
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
Comment Utility
[u][/u][i][/i][b]best damn guy on here![/b]
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

This article discusses how to create an extensible mechanism for linked drop downs.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now