Question

From LDAP I'm querying my users and this code sets them as a variable in the quoted format I need to run the MySQL query which would be 'username','other_username', etc...

            foreach ($prefs as $who => $pref) {
                    if (strpos($who, 'public') === false) {
                            $team_users_string .='\'' . $who . '\',';
                    }

When I try to sanitize the command with the following code it converts the string to \'username\',\'other_username\', what can I do to correct this?

    $team_users = rtrim($team_users_string, ",");

            $start_date = $_POST['start_year'] . '-' . $_POST['start_month'];
            $end_date = $_POST['end_year'] . '-' . $_POST['end_month'];

            echo 'Welcome, <strong>' . $user . '</strong><br />';
            echo '<br />';

            echo '<strong>Selected Start Date:</strong> ' . $start_date . '<br />';
            echo '<strong>Selected End Date:</strong> ' . $end_date . '<br />';

                  mysql_real_escape_string($team_users),
                  mysql_real_escape_string($start_date),
                  mysql_real_escape_String($end_date));

            $query = "SELECT * FROM vacation WHERE user_name in ($team_users) AND day BETWEEN '$start_date-01' AND '$end_date-31'";
Was it helpful?

Solution

Your problem is that you're adding the quote characters before you pass the string to mysql_real_escape_string(). So the literal quotes become escaped by that function.

You could avoid this by using mysql_real_escape_string(), and then delimiting the result in quotes.

Also I'd use an array and implode() the array to get commas, instead of being forced to rtrim() the last comma.

foreach ($prefs as $who => $pref) {
    if (strpos($who, 'public') === false) {
        $team_users_array[] = "'" . mysql_real_escape_string($who) . "'";
    }
}
$team_users = implode(",", $team_users_array); // no rtrim needed
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top