Вернуть строку, используя подготовленную php-инструкцию [duplicate]

попробуйте использовать этот пароль для пароля, который должен содержать более 6 символов с по крайней мере одним столичным, цифровым или специальным символом

^.*(?=.{6,})(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\\d)|(?=.*[!#$%&? "]).*$

^ assert position at start of the string
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?=.{6,}) Positive Lookahead - Assert that the regex below can be matched
.{6,} matches any character (except newline)
Quantifier: {6,} Between 6 and unlimited times, as many times as possible, giving back as needed [greedy]
(?=.*[A-Z]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[A-Z] match a single character present in the list below
A-Z a single character in the range between A and Z (case sensitive)
(?=.*[a-zA-Z]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[a-zA-Z] match a single character present in the list below
a-z a single character in the range between a and z (case sensitive)
A-Z a single character in the range between A and Z (case sensitive)
(?=.*\\d) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\d match a digit [0-9]
2nd Alternative: (?=.*[!#$%&? "]).*$
(?=.*[!#$%&? "]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[!#$%&? "] match a single character present in the list below
!#$%&? " a single character in the list !#$%&? " literally (case sensitive)
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string

https : //regex101.com/#javascript

больше этого вы можете попробовать ....

Минимум 8 символов не менее 1 Алфавит и 1 номер:

"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"

Минимум 8 символов не менее 1 Алфавит, 1 Номер и 1 Специальный символ:

"^(?=.*[A-Za-z])(?=.*\\d)(?=.*[$@$!%*#?&])[A-Za-z\\d$@$!%*#?&]{8,}$"

Минимум 8 символов не менее 1 Аппер-алфавит, 1 алфавит нижнего регистра и 1 номер:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"

Минимум 8 символов не менее 1 Аппер-алфавитный алфавит, 1 алфавит нижнего регистра, 1 номер и 1 специальный символ:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[d$@$!%*?&#])[A-Za-z\\dd$@$!%*?&#]{8,}"

Минимум 8 и максимум 10 символов не менее 1 Апгрейд-алфавит, 1 строчный алфавит, 1 номер и 1 специальный символ:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&#])[A-Za-z\\d$@$!%*?&#]{8,10}"

12
задан Timm 25 May 2012 в 11:30
поделиться

3 ответа

Вот более аккуратное решение, основанное на том же принципе:

function get_result( $Statement ) {
    $RESULT = array();
    $Statement->store_result();
    for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
        $Metadata = $Statement->result_metadata();
        $PARAMS = array();
        while ( $Field = $Metadata->fetch_field() ) {
            $PARAMS[] = &$RESULT[ $i ][ $Field->name ];
        }
        call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
        $Statement->fetch();
    }
    return $RESULT;
}

С mysqlnd вы обычно делаете:

$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$Result = $Statement->get_result();
while ( $DATA = $Result->fetch_array() ) {
    // Do stuff with the data
}

И без mysqlnd:

$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$RESULT = get_result( $Statement );
while ( $DATA = array_shift( $RESULT ) ) {
    // Do stuff with the data
}

Таким образом, использование и синтаксис почти идентичны. Основное отличие заключается в том, что функция замены возвращает массив результатов, а не объект результата.

28
ответ дан Amirhossein Mehrvarzi 23 August 2018 в 18:47
поделиться

Я столкнулся с той же проблемой и решил ее, используя код, указанный в ответе . Что не так с mysqli :: get_result?

Теперь моя функция выглядит так (обработка ошибок вычеркнутый для ясности):

  function db_bind_array($stmt, &$row)
  {
    $md = $stmt->result_metadata();
    $params = array();
    while($field = $md->fetch_field()) {
        $params[] = &$row[$field->name];
    }
    return call_user_func_array(array($stmt, 'bind_result'), $params);
  }

  function db_query($db, $query, $types, $params)
  {
    $ret = FALSE;
    $stmt = $db->prepare($query);
    call_user_func_array(array($stmt,'bind_param'),
                         array_merge(array($types), $params));
    $stmt->execute();

    $result = array();
    if (db_bind_array($stmt, $result) !== FALSE) {
      $ret = array($stmt, $result);
    }

    $stmt->close();
    return $ret;
  }

Использование, подобное этому:

  $userId = $_GET['uid'];
  $sql = 'SELECT name, mail FROM users WHERE user_id = ?';
  if (($qryRes = db_query($db, $sql, 'd', array(&$userId))) !== FALSE) {
    $stmt = $qryRes[0];
    $row  = $qryRes[1];

    while ($stmt->fetch()) {
      echo '<p>Name: '.$row['name'].'<br>'
             .'Mail: '.$row['mail'].'</p>';
    }
    $stmt->close();
  }
7
ответ дан Community 23 August 2018 в 18:47
поделиться

Я нашел анонимный совет в виде примечания на странице документации API для mysqli_stmt :: get_result очень полезен (я не мог думать о лучшем способе, чем eval trick), так как мы очень часто хотим fetch_array () на нашем результате. Однако, поскольку я хотел обслуживать общий объект базы данных, я обнаружил, что проблема в том, что предполагаемый числовой массив кода был хорош для всех вызовов, и мне нужно было обслуживать всех вызывающих абонентов, используя исключительно массивы-члены. Я придумал это:

class IImysqli_result {
        public $stmt, $ncols;
}   

class DBObject {

    function iimysqli_get_result($stmt) {
      $metadata = $stmt->result_metadata();
      $ret = new IImysqli_result;
      if (!$ret || !$metadata) return NULL; //the latter because this gets called whether we are adding/updating as well as returning
      $ret->ncols = $metadata->field_count;
      $ret->stmt = $stmt;
      $metadata->free_result();
      return $ret;
   }

   //this mimics mysqli_fetch_array by returning a new row each time until exhausted
    function iimysqli_result_fetch_array(&$result) {
      $stmt = $result->stmt;
      $stmt->store_result();
      $resultkeys = array();
      $thisName = "";
      for ( $i = 0; $i < $stmt->num_rows; $i++ ) {
            $metadata = $stmt->result_metadata();
            while ( $field = $metadata->fetch_field() ) {
                $thisName = $field->name;
                $resultkeys[] = $thisName;
            }
      }

      $ret = array();
      $code = "return mysqli_stmt_bind_result(\$result->stmt ";
      for ($i=0; $i<$result->ncols; $i++) {
          $ret[$i] = NULL;
          $theValue = $resultkeys[$i];
          $code .= ", \$ret['$theValue']";
      }

      $code .= ");";
      if (!eval($code)) { 
        return NULL; 
      }

      // This should advance the "$stmt" cursor.
      if (!mysqli_stmt_fetch($result->stmt)) { 
        return NULL; 
      }

      // Return the array we built.
      return $ret;
    }
}
0
ответ дан tonywoode 23 August 2018 в 18:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: