0

I started learning learning PHP a couple of days ago and have started to make an SQL Database management webpage using AJAX. I am having a problem with errors if I restrict the search to less than all [*] the column's.

Because of this I thought it would be relatively easy to use regular expression on the string sent through AJAX and dynamically write the required table back to the webpage.

I am having issues understanding how to do a loop based on the returned array from preg_split(), append to a new string and then echo the new string out as a new table that I can write the sql table to.

this is the bit I can't figure out

$newString = 'this and ';

for ($i=0; $i < $arrayLength; $i++) { 
    $newString += $repArray[$i];
}

echo $newString;

the regular expression in the code simply gets the text between the 'SELECT' and 'FROM' statements, deletes the whitespace and splits the words into an array. and there are various echo's to show what is happening.

Thanks for any help

Regards,

Andrew

here is my full php code for testing the idea

<?php
$string = 'SELECT ID, username, password, firstName, IP FROM users WHERE ID > 100';
$pattern = '/SELECT (.*) FROM (.*)/i';
$replacement = '$1';
$replaced = preg_replace($pattern, $replacement, $string);

echo '<br> ' . $replaced;

$replaced2 = preg_replace('/\s/' , '', $replaced);

echo '<br> ' . $replaced2;

$repArray = preg_split('/,/', $replaced2, -1, PREG_SPLIT_NO_EMPTY);
echo '<br> ';
print_r($repArray);

$arrayLength = count($repArray);

echo '<br> Array length = ' . $arrayLength;

$newString = 'this and ';

for ($i=0; $i < $arrayLength; $i++) { 
    $newString += $repArray[$i];
}

echo $newString;

?>
synthet1c
  • 6,152
  • 2
  • 24
  • 39
  • 1
    Worth noting that concatenation of strings is done by `.=` and not `+=`, in PHP. – johankj Jan 12 '13 at 21:44
  • LOL.. I knew it would be something stupid on my behalf.. I have been playing with Javascript for the last 6 months and += just came naturally – synthet1c Jan 12 '13 at 21:59

1 Answers1

1

According to the php documentation for preg_split the elements in the resulting array will be arrays, with the first item being the string you want. This is what the result of your preg_split will look like:

Array
(
[0] => Array
    (
        [0] => ID
        [1] => 0
    )

[1] => Array
    (
        [0] => username
        [1] => 4
    )

[2] => Array
    (
        [0] => password
        [1] => 15
    )


[3] => Array
    (
        [0] => firstname
        [1] => 25
    )


[4] => Array
    (
        [0] => IP
        [1] => 36
    )
)

Then you can just get the first element in the array of the array.

for ($i=0; $i < $arrayLength; $i++) { 
    $newString .= $repArray[$i][0];
}
  • 1
    Thanks for the advice, that is something i have overlooked aswell. I love this place such good answers so quickly... I only hope one day I can add to this great place – synthet1c Jan 12 '13 at 22:02