2

我有一个函数可以很好地参数化 MySQL 查询,但我需要它来执行 DROP TABLE IF EXISTS 查询,但我没有任何运气。我没有收到任何错误,但表没有被删除,我不知道为什么。

db_query('DROP TABLE IF EXISTS temp_table', false, false);

这是完整的功能,以防万一,但正如我所提到的,它非常适合插入、更新、删除和选择。

// $query = SQL query, $params = array of parameters (i, s, d, b), $rs = whether or not a resultset is expected, $newid = whether or not to retrieve the new ID value;
// $onedimensionkey = key required to convert array into simple one dimensional array; $admin = if true, use the admin credentials (used only for logins)
function db_query($query, $params, $rs = true, $newid = false, $onedimensionkey = false, $admin = false) {
  (!$admin) ? $link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME) : $link = mysqli_connect(AUTH_SERVER, AUTH_USER, AUTH_PASS, AUTH_NAME);
  if (!$link) { 
    print 'Error connecting to MySQL Server. Errorcode: ' . mysqli_connect_error(); 
    exit; 
  }

  // Prepare the query and split the parameters array into bound values
  if ($sql_stmt = mysqli_prepare($link, $query)) {
    if ($params) {
      $types = '';
      $new_params = array();
      $params_ref = array();
      // Split the params array into types string and parameters sub-array
      foreach ($params as $param) {
        $types .= $param['type'];
        $new_params[] = $param['value'];
      }
      // Cycle the new parameters array to make it an array by reference
      foreach ($new_params as $key => $parameter) {
        $params_ref[] = &$new_params[$key];
      }
      call_user_func_array('mysqli_stmt_bind_param', array_merge(array($sql_stmt, $types), $params_ref));
    }
  }
  else {
    print 'Error: ' . mysqli_error($link);
    exit();
  }

  // Execute the query
  mysqli_stmt_execute($sql_stmt);

  // Store results
  mysqli_stmt_store_result($sql_stmt);

  // If there are results to retrive, do so
  if ($rs) {
    $results = array();
    $rows = array();
    $row = array();
    stmt_bind_assoc($sql_stmt, $results);
    while (mysqli_stmt_fetch($sql_stmt)) {
      foreach ($results as $key => $value) {
        $row[$key] = $value;
      }
      $rows[] = $row;
    }
    if ($onedimensionkey) {
      $i = 0;
      foreach ($rows as $row) {
        $simplearray[$i] = $row[$onedimensionkey];
        $i++;
      }
      return $simplearray;
    }
    else {
      return $rows;
    }
  }
  // If there are no results but we need the new ID, return it
  elseif ($newid) {
    return mysqli_insert_id($link);
  }

  // Close objects
  mysqli_stmt_close($sql_stmt);
  mysqli_close($link);
}
4

1 回答 1

1

像这样试试

 db_query('DROP TABLE IF EXISTS `dbName`.`temp_table`') ;
于 2013-01-28T22:02:29.397 回答