简体   繁体   中英

Trying to dynamically write a table with PHP based on SQL Query

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;

?>

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM