Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - GetSQLValueString function

Tags:

php

I see a function GetSQLValueString and I don't know what is it dealing with, could someone give me some idea?
Thanks you

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

The function used here:

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "";
  $MM_redirectLoginSuccess = "main.php";
  $MM_redirectLoginFailed = "login_form.php";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_connection1, $connection1);

  $LoginRS__query=sprintf("SELECT username, password FROM member WHERE username=%s AND password=%s",
    GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
...
like image 411
Charles Yeung Avatar asked Feb 25 '23 14:02

Charles Yeung


2 Answers

Your function escapes the string using MySQL's built-in string escaping function, then if it is a non-numeric value, surrounding it in single quotes. This function was written for inserting variable data into SQL queries.

$sql = "SELECT * FROM users WHERE username = " . GetSQLValueString($_GET['username'], 'text');
$result = mysql_query($sql);
like image 182
Dan Grossman Avatar answered Feb 28 '23 02:02

Dan Grossman


From my understanding this function is probably to escape some data to pass it to MySQL. The function also handles null values and put some quotes if needed.

it should be used this way

GetSQLValueString("a value that I want to escape's", 'text');

see the SQL injection problem to understand why this function exists

like image 30
RageZ Avatar answered Feb 28 '23 03:02

RageZ