Can't round(max($string)) in a query?

Hey guys , may sound silly but can anyone tell me whats wrong with this code? Does the Round or Max not support a string stored as a variable? I can’t see why my code wont work, i have echo and dumped the variable and its just a string. RH is the name of column which has data in it. When i type in “RH” instead of the $string it works perfectly? :sweat:

        $string = $_GET['name'];    //result from an SQL query
         echo $string;              //this is the result      "RH"
 $sql2 = 'select date, ROUND(MAX("'.$string.'")) as MAX from test WHERE date < DATE(NOW() - INTERVAL 30 DAY)';
                   foreach ($pdo->query($sql2) as $row) {

                            echo '<td>'. $row['MAX'] . '</td>';    
                            echo '</tr>';

How about if you concencate the $string without double quotes to the query? I have a feeling mysql interprets it as a value now instead of column name. And your also open to SQL injections.

I have tried that also doesn’t work :confused: And the name is only selected from a drop down which isn’t vulnerable ?

Every user input coming from a Form, POST/GET params or other source is pretty much vulnerable. Seeing yours coming from $_GET in this piece of code I could just type name=SomeSQLQueryTOfuckUpYourDatabase in the URL and its done.

Unless you use prepared statements. Which you don’t.

Oh wow i see, thanks for the heads up. I am still learning PHP aha, as for the question do you have any other ideas on a potential solution?

NVM. Figured out the solution thanks anyways!

       $sql2 = "select date, ROUND(MAX($value)) as MAX from test WHERE date < DATE(NOW() - INTERVAL 30 DAY)";
                   foreach ($pdo->query($sql2) as $row) {
                            echo '<td>'. $row['MAX'] . '</td>';
                            echo '</tr>';

Interesting that’s how @TenDolla suggested you fix the problem but you said that it didn’t work. Did you change something else that I can’t see in the code, other than the variable name?

Yea my bad , thought he meant the double quotes in the string concatenation! :sweat:Had no idea that the surrounding quotes of the query would effect it.

Just be aware that your query is still vulnerable to sql injections. Hackers are sneaky and can do amazing things with column names. You really need to check for valid submitted column names. Nothing fancy:

$columnName = $_GET['name'];
if (!in_array($columnName,['col1','col2','col3'])) {
    die('Alert: sucking death approaches!');
// All is well
1 Like

Thanks mate have touched it up since :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.