Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 357
  • Last Modified:

PHP string concatination

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
GPB1983
Asked:
GPB1983
  • 7
  • 6
2 Solutions
 
JayDiabloCommented:
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
 
GPB1983Author Commented:
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
 
JayDiabloCommented:
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.

 
GPB1983Author Commented:
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
 
JayDiabloCommented:
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
 
GPB1983Author Commented:
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
 
JayDiabloCommented:
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
 
GPB1983Author Commented:
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
 
JayDiabloCommented:
That's the output of print_r(array_filter($field3)) ?
0
 
GPB1983Author Commented:
0
 
JayDiabloCommented:
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
 
GPB1983Author Commented:
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
 
GPB1983Author Commented:
[u][/u][i][/i][b]best damn guy on here![/b]
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 7
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now