-1

hi i have written the following function to get a value from my database:

function getSlCreatedate($sid) {
    $query1 = "SELECT Sub_type FROM `Sub` where `Sub_id` = $sid";
    $queryresult1 = mysql_query($query1);
    $row1 = mysql_fetch_assoc($queryresult1);
    $type1 = $row1['created_ts'];
    if($type1 == 'SL') {
    $query2 = "SELECT Sub_attr_value FROM `Sub_attr_list` WHERE `Sub_attr_type_id` = 20 AND `Sub_id` = $sid";
    $queryresult2 = mysql_query($query2);
    $row2 = mysql_fetch_assoc($queryresult2);
    $type2 = $row2['Sub_attr_value'];
    if($type2 == " "){
    $query3 = "SELECT Created_ts FROM `Sub` WHERE `Sub_id`= $sid";
    $queryresult3 = mysql_query($query3);
    $row3 = mysql_fetch_assoc($queryresult3);
    return $row3['Created_ts'];
    }
    else {
    return $type2['Sub_attr_value'];
    }
    }
    else
    return 0;
}

what's the condition is I need to first check the Sub_type in Database for the given "sid" value and if returns "SL" as result then I need to get the "Sub_attr_value" from "Sub_attr_list" table, if this value returns empty rows or value NULL, then I've to return the "Created_ts" value for that sid to the page, Here all the queries are working fine when i exectued in my PHP MyAdmin seperately, can anyone guide me to complete this, I'm not able to get the value from here to the page.

The function call in my page is as follows:

  $sldate = db_func::getSlCreatedate($sub_list[$i]['Sub_id']);

fortunately it is not showing any errors as well not showing the expected result.

lucky
  • 83
  • 1
  • 4
  • 17
  • 1
    Don't build SQL by mashing strings together. Don't use `mysql_query`, there is a reason for the big red warning on [the manual page for that function](http://php.net/mysql_query). – Quentin Sep 01 '12 at 10:54
  • looks like you could combine all 3 in to one query with a single join –  Sep 01 '12 at 10:56
  • You code is vulnerable to injections if you are going to keep it the way it is, please read more about SQL injections: http://stackoverflow.com/questions/11939226/sql-injections-and-adodb-library-general-php-website-security-with-examples – Ilia Ross Sep 01 '12 at 10:57
  • though it is....but all my previous functions use the same one which are working fine. – lucky Sep 01 '12 at 10:58
  • can anyone show me the way how can i change this function to get the values – lucky Sep 01 '12 at 10:58

1 Answers1

1
function getSLCreatedDate($sid) {

    $query = "SELECT s.created_ts, sa.Sub_attr_value FROM Sub s
              LEFT JOIN Sub_attr_list sa ON sa.Sub_id=s.Sub_id AND sa.Sub_attr_type_id='20'
              WHERE s.Sub_id='" . mysql_real_escape_string($sid) . "'"
    $sql = mysql_query($query);

    $row = mysql_fetch_array($sql);

    if($row['created_ts'] == 'SL')
        return isset($row['Sub_attr_value']) ? $row['Sub_attr_value'] : $row['created_ts'];

    return 0;
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50