Prepare statement before query
160441
protected function beginQuery()
    {
        $autoSlave = $this->db->isAutoSlave();
        if ($autoSlave) {
            $this->db->switchConnection('slave');
        }

        $reconnect = $this->db->getOption('reconnect');
        $reconnectRetries = $this->db->getOption('reconnect_retries', 3);
        $reconnectDelayMS = $this->db->getOption('reconnect_delay_ms', 1000);

        while (true) {
            $e = null;
            $errorCode = null;
            $errorInfo = null;
            $result = null;

            $isReconnectError = false;
            try {
                $this->prepare();
                $result = $this->statement->execute($this->params ? $this->params : $this->positionParams);
            } catch (\Exception $e) {
            }

            if ($result === false || !$e) {
                $errorCode = $this->statement->errorCode();
                $errorInfo = $this->statement->errorInfo();
            }

            $isReconnectError = Util::checkReconnectError($errorCode, $errorInfo, $e);

            // reconnect
            if ($reconnect && $isReconnectError && $reconnectRetries > 0) {
                $reconnectRetries--;
                $this->statement = null;
                $this->db->close();
                $reconnectDelayMS && usleep($reconnectDelayMS * 1000);
                continue;
            }

            break;
        }

        if ($autoSlave) {
            $this->db->switchConnection();
        }

        if ($e) {
            $this->db->logError(sprintf('Statement exception error #%s: %s', $e->getCode(), $e->getMessage()));
            throw $e;
        }

        if ($result === false) {
            $errorMsg = sprintf('Statement execute error #%s: %s', $errorInfo[0], $errorInfo[2]);
            $this->db->logError($errorMsg);
            throw new Exception($errorMsg);
        }
    }
835404
protected function _prepare_filter() {
		$post = \get_queried_object();

		if ( ! empty( $post->post_name ) ) {
			$this->slug = $post->post_name;
		}

		if ( ! empty( $post->post_type ) ) {
			$post_type       = \get_post_type_object( $post->post_type );
			$this->post_type = $post_type->name;
		}
	}
559639
public function prepare($query)
    {
        $this->connect();
        $options = [PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL];
        $isObject = $query instanceof Query;
        if ($isObject && $query->isBufferedResultsEnabled() === false) {
            $options = [];
        }
        $statement = $this->_connection->prepare($isObject ? $query->sql() : $query, $options);

        return new SqlserverStatement($statement, $this);
    }
892403
private function prepare($query, $parameters)
    {
        if (!$parameters) {
            $parameters = array();
        } elseif (!is_array($parameters)) {
            $parameters = array($parameters);
        }

        $this->paramNb = 0;
        $this->params = & $parameters;
        $query = preg_replace_callback('/\?/', array($this, 'replaceParam'), $query);

        return $query;
    }
56041
protected function prepareSql($sql)
    {
        $sql = str_replace(";',", "-CODE-", $sql);
        $sql = trim($sql);
        preg_match_all('#DELIMITER (.+?)\n(.+?)DELIMITER ;#s', $sql, $m);
        foreach ($m[0] as $k => $v) {
            if ($m[1][$k] == '|') {
                throw new \RuntimeException('You can not use "|" as delimiter: '.$v);
            }
            $stored = str_replace(';', '|', $m[2][$k]);
            $stored = str_replace($m[1][$k], ";\n", $stored);
            $sql = str_replace($v, $stored, $sql);
        }
        $query = array();

        $tab = explode(";\n", $sql);
        $size = \count($tab);
        for ($i = 0; $i < $size; $i++) {
            $queryTemp = str_replace("-CODE-", ";',", $tab[$i]);
            $queryTemp = str_replace("|", ";", $queryTemp);
            $query[] = $queryTemp;
        }

        return $query;
    }
195249
def prepare_query(query):
    

    for name in query:
        value = query[name]

        # None is sent as an empty string.
        if value is None:
            query[name] = ""

        # Booleans are sent as 0 or 1.
        elif isinstance(value, bool):
            query[name] = int(value)

        # XXX shouldn't this just check for basestring instead?
        elif isinstance(value, dict):
            raise ValueError("Invalid query data type %r" %
                             type(value).__name__)
200975
private function prepare_statement($stmt, $args=[]) {
		if (!$this->connection) {
			self::$logger->error(sprintf(
				"SQL: connection failed: '%s'.",
				json_encode($this->verified_params)));
			throw new SQLError(SQLError::CONNECTION_ERROR,
				$this->dbtype . " connection error.");
		}

		$conn = $this->connection;
		try {
			$pstmt = $conn->prepare($stmt);
		} catch (\PDOException $e) {
			self::$logger->error(sprintf(
				"SQL: execution failed: %s <- '%s': %s.",
				$stmt, json_encode($args),
				$e->getMessage()));
			throw new SQLError(
				SQLError::EXECUTION_ERROR,
				sprintf("Execution error: %s.", $e->getMessage()),
				$stmt, $args
			);
		}

		try {
			$pstmt->execute(array_values($args));
		} catch (\PDOException $e) {
			self::$logger->error(sprintf(
				"SQL: execution failed: %s <- '%s': %s.",
				$stmt, json_encode($args),
				$e->getMessage()));
			throw new SQLError(
				SQLError::EXECUTION_ERROR,
				sprintf("Execution error: %s.", $e->getMessage()),
				$stmt, $args
			);
		}

		return $pstmt;
	}
39325
public void execute(String query, Object... params) throws SQLException {
        createPreparedStatement(query, 0, params).execute();
    }
53241
private PreparedStatement buildPreparedStatement(Connection connection, QueryModel queryModel)
            throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(buildSelectString(queryModel));

        int parameterLocation = 1;
        for (Condition condition : queryModel.getConditions()) {
            JDBCConstraint jdbcConstraint = (JDBCConstraint) condition.getConstraint();

            if (jdbcConstraint.getParameter1() != null) {
                preparedStatement.setObject(parameterLocation++, jdbcConstraint.getParameter1());
            }

            if (jdbcConstraint.getParameter2() != null) {
                preparedStatement.setObject(parameterLocation++, jdbcConstraint.getParameter2());
            }
        }

        return preparedStatement;
    }
645455
private function prepareStatement()
    {
        //Prepare statement
        $columns = "";
        $fields  = "";
        foreach ($this->fields as $key => $f) {
            if ($f == 'id') {
                continue;
            }
            if ($key == 1) {
                $columns .= "$f";
                $fields .= ":$f";
                continue;
            }

            $columns .= ", $f";
            $fields .= ", :$f";
        }

        $this->statement = $this->pdo->prepare(
            'INSERT INTO `' . $this->table . '` (' . $columns . ') VALUES (' . $fields . ')'
        );
    }
183555
protected void prepareQuery(org.hibernate.query.Query query) {
        if (cacheQueries) {
            query.setCacheable(true);
        }
        if (shouldPassReadOnlyToHibernate()) {
            query.setReadOnly(true);
        }
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
        if (sessionHolder != null && sessionHolder.hasTimeout()) {
            query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
        }
    }
1343325
@Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
760123
protected function _prep_query($sql)
	{
		// mysql_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
		// modifies the query so that it a proper number of affected rows is returned.
		if ($this->delete_hack === TRUE && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql))
		{
			return trim($sql).' WHERE 1=1';
		}

		return $sql;
	}
1291815
protected function prepare_query() 
	{
		$this->query->where( $this->foreign_key, $this->local_model->{$this->local_key} )
			->limit( 1 );
	}
1093800
function before_process() {
    global $response, $db, $order, $messageStack;

    $order->info['cc_owner']    = zen_db_prepare_input($_POST['bank_acct_name']);
    $order->info['cc_type']    = 'eCheck';
    $order->info['cc_number'] = zen_db_prepare_input($_POST['bank_aba_code'] . '-' . str_pad(substr($_POST['bank_acct_num'], -4), strlen($_POST['bank_acct_num']), "X", STR_PAD_LEFT));
    $sessID = zen_session_id();

    // DATA PREPARATION SECTION
    unset($submit_data);  // Cleans out any previous data stored in the variable

    // Create a string that contains a listing of products ordered for the description field
    $description = '';
    for ($i=0; $i<sizeof($order->products); $i++) {
      $description .= $order->products[$i]['name'] . ' (qty: ' . $order->products[$i]['qty'] . ') + ';
    }
    // Remove the last "\n" from the string
    $description = substr($description, 0, -2);

    // Create a variable that holds the order time
    $order_time = date("F j, Y, g:i a");

    // Calculate the next expected order id
    $last_order_id = $db->Execute("select * from " . TABLE_ORDERS . " order by orders_id desc limit 1");
    $new_order_id = $last_order_id->fields['orders_id'];
    $new_order_id = ($new_order_id + 1);
    $new_order_id = (string)$new_order_id . '-' . zen_create_random_value(6, 'chars');

    // Populate an array that contains all of the data to be sent to Authorize.net
    $submit_data = array(
                         'x_login' => trim(MODULE_PAYMENT_AUTHORIZENET_ECHECK_LOGIN),
                         'x_tran_key' => trim(MODULE_PAYMENT_AUTHORIZENET_ECHECK_TXNKEY),
                         'x_relay_response' => 'FALSE', // AIM uses direct response, not relay response
                         'x_delim_data' => 'TRUE',
                         'x_delim_char' => $this->delimiter,  // The default delimiter is a comma
                         'x_encap_char' => $this->encapChar,  // The divider to encapsulate response fields
                         'x_version' => '3.1',  // 3.1 is required to use CVV codes
                         'x_type' => MODULE_PAYMENT_AUTHORIZENET_ECHECK_AUTHORIZATION_TYPE == 'Authorize' ? 'AUTH_ONLY': 'AUTH_CAPTURE',
                         'x_amount' => number_format($order->info['total'], 2),
                         'x_currency_code' => $order->info['currency'],
                         'x_method' => 'ECHECK',
                         'x_bank_aba_code' => $_POST['bank_aba_code'],
                         'x_bank_acct_num' => $_POST['bank_acct_num'],
                         'x_bank_acct_type' => $_POST['bank_acct_type'],
                         'x_bank_name' => $_POST['bank_name'],
                         'x_bank_acct_name' => $_POST['bank_acct_name'],
                         'x_echeck_type' => 'WEB',
                         'x_recurring_billing' => 'NO',
                         'x_email_customer' => MODULE_PAYMENT_AUTHORIZENET_ECHECK_EMAIL_CUSTOMER == 'True' ? 'TRUE': 'FALSE',
                         'x_email_merchant' => MODULE_PAYMENT_AUTHORIZENET_ECHECK_EMAIL_MERCHANT == 'True' ? 'TRUE': 'FALSE',
                         'x_cust_id' => $_SESSION['customer_id'],
                         'x_invoice_num' => (MODULE_PAYMENT_AUTHORIZENET_ECHECK_TESTMODE == 'Test' ? 'TEST-' : '') . $new_order_id,
                         'x_first_name' => $order->billing['firstname'],
                         'x_last_name' => $order->billing['lastname'],
                         'x_company' => $order->billing['company'],
                         'x_address' => $order->billing['street_address'],
                         'x_city' => $order->billing['city'],
                         'x_state' => $order->billing['state'],
                         'x_zip' => $order->billing['postcode'],
                         'x_country' => $order->billing['country']['title'],
                         'x_phone' => $order->customer['telephone'],
                         'x_email' => $order->customer['email_address'],
                         'x_ship_to_first_name' => $order->delivery['firstname'],
                         'x_ship_to_last_name' => $order->delivery['lastname'],
                         'x_ship_to_address' => $order->delivery['street_address'],
                         'x_ship_to_city' => $order->delivery['city'],
                         'x_ship_to_state' => $order->delivery['state'],
                         'x_ship_to_zip' => $order->delivery['postcode'],
                         'x_ship_to_country' => $order->delivery['country']['title'],
                         'x_description' => $description,
                         'x_customer_ip' => zen_get_ip_address(),
                         'x_po_num' => date('M-d-Y h:i:s'), //$order->info['po_number'],
                         'x_freight' => number_format((float)$order->info['shipping_cost'],2),
                         'x_tax_exempt' => 'FALSE', /* 'TRUE' or 'FALSE' */
                         'x_tax' => number_format((float)$order->info['tax'],2),
                         'x_duty' => '0',

                         // Additional Merchant-defined variables go here
                         'Date' => $order_time,
                         'IP' => zen_get_ip_address(),
                         'Session' => $sessID );
    // process Wells-Fargo-SecureSource-specific parameters
    if (MODULE_PAYMENT_AUTHORIZENET_ECHECK_WFSS_ENABLED == 'True') {
      $submit_data['x_customer_organization_type'] = zen_db_prepare_input($_POST['echeck_customer_type']);
      if (zen_db_prepare_input($_POST['echeck_customer_tax_id']) != '') {
        $submit_data['x_customer_tax_id'] = zen_db_prepare_input($_POST['echeck_customer_tax_id']);
      } else {
        $submit_data = array_merge($submit_data,
                   array('x_drivers_license_num' => zen_db_prepare_input($_POST['echeck_dl_num']),
                         'x_drivers_license_state' => zen_db_prepare_input($_POST['echeck_dl_state']),
                         'x_drivers_license_dob' => zen_db_prepare_input($_POST['echeck_dl_dob'])  ));
      }
    }

    // force conversion to USD
    if ($order->info['currency'] != 'USD') {
      global $currencies;
      $submit_data['x_amount'] = number_format($order->info['total'] * $currencies->get_value('USD'), 2);
      $submit_data['x_currency_code'] = 'USD';
      unset($submit_data['x_tax'], $submit_data['x_freight']);
    }

    unset($response);
    $response = $this->_sendRequest($submit_data);
    $response_code = $response[0];
    $response_text = $response[3];
    $this->auth_code = $response[4];
    $this->transaction_id = $response[6];
    $response_msg_to_customer = $response_text . ($this->commError == '' ? '' : ' Communications Error - Please notify webmaster.');

    $response['Expected-MD5-Hash'] = $this->calc_md5_response($response[6], $response[9]);
    $response['HashMatchStatus'] = ($response[37] == $response['Expected-MD5-Hash']) ? 'PASS' : 'FAIL';

    $this->_debugActions($response, $order_time, $sessID);

    // If the MD5 hash doesn't match, then this transaction's authenticity cannot be verified.
    // Thus, order will be placed in Pending status
    if ($response['HashMatchStatus'] != 'PASS' && defined('MODULE_PAYMENT_AUTHORIZENET_ECHECK_MD5HASH') && MODULE_PAYMENT_AUTHORIZENET_ECHECK_MD5HASH != '') {
      $this->order_status = 1;
      $messageStack->add_session('header', MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_AUTHENTICITY_WARNING, 'caution');
    }

    // If the response code is not 1 (approved) then redirect back to the payment page with the appropriate error message
    if ($response_code != '1') {
      $messageStack->add_session('checkout_payment', $response_msg_to_customer . ' - ' . MODULE_PAYMENT_AUTHORIZENET_ECHECK_TEXT_DECLINED_MESSAGE, 'error');
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }
  }
689630
private function prepare($query)
    {
        foreach ($this->aggregations as $agg) {
            $agg->prepareQuery($this, $query);
        }

        // Handle paging
        $this->setPage(
            $this->getQueryParam($query, $this->pageParameterName, 0)
                + $this->pageDelta
        );
    }
1136303
public static function sql_prepare($str, $used_in_like = false)
    {
        if (!self::getInstance()->pdo_db) {
            self::getInstance()->connect();
        }

        if (is_array($str)) {
            foreach ($str as &$v) {
                $v = self::sql_prepare($v);
            }
        } else {
            $str = substr(self::getInstance()->pdo_db->quote(trim((string)$str)), 1, -1);

            if ($used_in_like) {
                $str = str_replace(['_', '%'], ['\_', '\%'], $str);
            }
        }

        return $str;
    }