使用isset()动态转换未定义的索引

使用isset()动态转换未定义的索引

问题描述:

I'm writing a generic function that will take a large number of fields from $_POST and build an SQL insert into a table. In this case, I have a number of Undefined indexes and from reading other posts on SO, I am using a ternary to test if the variable exists. This works perfectly when I use it in interactive php, especially since there are no $_POST variables defined.

But when I use it in my form, I seem to get a extra quote and a few returns but I cannot see where they are coming from. I've beaten about this in different ways but am hoping someone can help me see what I'm not seeing.

function SaveDonation($form) {
    try {
        $querystr = "INSERT INTO GeneralDonations(donationForm, firstName, startYear)" 
        . "VALUES(" . "'" . $form . "', "
        . ((!isset($_POST['firstName'])) 
            ? "'', " : ("'" . mysql_real_escape_string($_POST['firstName'])."', "))
        . ((isset($_POST['startDate'])) 
            ? ("'" . mysql_real_escape_string($_POST['startDate'])."' ") : "'' ") 
        .")";

        echo "<pre>query = "; var_dump($querystr);die;


        $donation = $this->db->insertRow($querystr);
        $result = true;

    } catch(MysqlException $e) {
        $result = false;
        $this->errorMsg = $e->getMessage();
    }
    return $result;
}

The startDate is the undefined index value. This is the browser output using var_dump. It appears that the x-debug output is showing instead of the variable. But all table, no useful data? Please help me see what's different here?

string 'INSERT INTO GeneralDonations(
  donationForm, firstName, startYear)VALUES('buy-a-foot', 's', 
  '<br />
<font size=\'1\'><table class=\'xdebug-error xe-notice\'
  dir=\'ltr\' border=\'1\' cellspacing=\'0\' cellpadding=\'1\'>

  <tr><th align=\'left\' bgcolor=\'#f57900\' colspan=' )' (length=284)

Your code has some problems:

  • Please use prepared statements (see below)!

  • The error message (which is not entirely shown) would continue with "Undefined index firstName", since there's an ! too much in (!isset($_POST['firstName'])).

  • The error message is incomplete because your xdebug shortens var_dump output. You can change this behaviour with the settings xdebug.overload_var_dump and xdebug.var_display_max_data. See xdebug documentation.

  • If you can't use prepared statements, consider using some sprintf() construction to improve readability.


// Prepared statements (untested)
$stmt = $db->prepare("
    INSERT INTO GeneralDonations(donationForm, firstName, startYear)
    VALUES (?, ?, ?)");
$stmt->execute(array(
    $form,
    isset($_POST['firstName']) ? $_POST['firstName'] : '',
    isset($_POST['startDate']) ? $_POST['startDate'] : ''
));