Показать, сколько результатов запроса есть в codeigniter

#php #mysql #codeigniter

#php #mysql #codeigniter

Вопрос:

У меня есть форма поиска на странице, которая выполняет поиск записей из таблицы в моей базе данных. Я хочу показать, сколько результатов дает нам каждый запрос. Все это написано в codeigniter.

Весь мой код на этой странице:

 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	public function index() {
		$data['title'] = "Welcome | randomsite";
		$data['html'] = "";
		if($this->input->post()) {
			$uq = $this->security->xss_clean($this->input->post('query'));
			if(trim($uq) != "") {
				$searchBy = $this->security->xss_clean($this->input->post('searchBy'));
				$searchByJSON = json_encode(array(1 => "Email", 2 => "Username", 3 => "IP", 4 => "FullName", 5 => "Phone"), JSON_FORCE_OBJECT);	
				if(isset(json_decode($searchByJSON)->$searchBy)) {
					$start = microtime(true);
					$this->db->from('Databases');
					$rs = $this->db->get()->result();
					$end = microtime(true);
					$data['html'] .= "Search completed in: " . ($end - $start) . " seconds.<p></p>";
					foreach($rs as $row) {
						$this->db->distinct();
						$this->db->select('Username, Password, Email, FullName, IP, Phone, salt');
						$this->db->from('Accounts');
						$this->db->where(json_decode($searchByJSON)->$searchBy, $uq);
						$this->db->where('DatabaseID', $row->ID);
						$query = $this->db->get();
						if($query->num_rows() > 0) {
							if($searchBy == 5 amp;amp; $query->row()->Phone == 0) {
								break;
							}
							$resultsHTML = "";
							foreach($query->result() as $qr) {
								$resultsHTML .= "<div class='card-block-results' style='table-layout:fixed; word-wrap:break-word;'><table class='table table-hover' style='font-size:13px;'>";
								foreach($qr as $key => $value) {
									if(!empty($value)) {
										if($key == "FullName") {
											$key = "Full Name";

										}
										$resultsHTML .= "<tr><td>" . $key . ": " . $value . "</td></tr>";
									}
								}
								$resultsHTML .= "</table></div>"; 
							}
							$data['html'] .= $row->Website . " has: <b style='color:lime;'>" . $query->num_rows() . "</b> result(s) found. This data was hacked on approximately " . $row->Date . ". <button class='btn btn-success btn-sm' style='margin-bottom:5px;' id='button" . $row->ID . "'>view results</button><div id='results" . $row->ID . "' style='display:none;'><div class='card card-outline-primary' style='margin-bottom:10px;text-align:left;margin-top:5px;'><div class='card-header card-primary'>Results</div>" . $resultsHTML . "</div></div><script type='text/javascript'>$('#button" . $row->ID . "').click(function() { $(this).hide(); $('#results" . $row->ID . "').show(); });</script><br>";
						}
					}
					if($data['html'] == "Search completed in: " . ($end - $start) . " seconds.<p></p>") {
						$data['html'] .= "No results found!<p></p>Are you searching in the right fields? Searching for an email in the phone number field will not work.<br>Make sure first and last names are correct. Example: Mike Tyson";
					}
					$data['html'] .= "<br><br><br>";
					$this->db->from('Lookups');
					$query = $this->db->get();
					$new_lookup = $query->row()->Number   1;
					$qdata = array(
						"Number" => $new_lookup
					);
					$this->db->update('Lookups', $qdata);
				}
			} else {
			$data['html'] = '<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">amp;times;</a>Please enter something in your query before searching!</div>';
			
			}
		}
		$this->load->view('welcome', $data);
	}

}  

Итак, как я могу добавлять это каждый раз, когда кто-то ищет? Например, «Запрос имел x результатов».

Вот так:

введите описание изображения здесь

Я искал на многих разных сайтах об этом, но я ничего не мог найти по своему конкретному вопросу.

Ответ №1:

вы уже использовали его в своем коде,

 $query->num_rows()
  

даст вам количество строк, которые вы получаете из запроса.

Комментарии:

1. Почему он не отображается на моем сайте?

2. Я использую его для отображения количества записей, которые были найдены в конкретной добавленной базе данных, но я хочу показать общее количество строк.

3. попробуйте это, count($query->result())

4. заменить $query->num_rows() . "</b> result(s) found. This data was hacked on approximately " на count($query->num_rows()) . "</b> result(s) found. This data was hacked on approximately "

Ответ №2:

я думаю, что это злоупотребление фреймворком, таким как CI — я даю вам некоторое представление об этом фреймворке — если вы готовы учиться, изучите этот фрагмент кода, потому что вы почти не используете ни одну из его встроенных функций

на мой взгляд, вам нужно реструктурировать свой код до такой степени, что вы даже не узнаете свою предыдущую попытку 😉

я попытаюсь дать вам представление, но для того, чтобы понять, вам нужно поработать с этим кодом

поместите в папку models следующие модели

Модель базы данных

 class Database_model extends CI_Model
{

    private $objCollection;

    public function __construct()
    {
        $this->objCollection = new Database_Collection();
    }

    public function getCollection()
    {
        $this->benchmark->mark('code_start');
        $this->db->from('Databases');
        $this->objCollection->append($this->db->get()->result());
        $this->benchmark->mark('code_end');

        $this->objCollection->queryTime =  $this->benchmark->elapsed_time('code_start', 'code_end');

        return $this->objCollection;
    }

}


class Database_Collection extends ArrayObject
{
    public $queryTime = 0;
}
  

Модель учетных записей

 class Accounts_model extends CI_Model
{

    private $objCollection;

    public function __construct()
    {
        $this->objCollection = new Accounts_Collection();
    }

    public function getCollection()
    {
        $this->benchmark->mark('code_start');

        $this->db
            ->distinct()
            ->select('Username, Password, Email, FullName, IP, Phone, salt')
            ->from('Accounts');

        $this->objCollection->append($this->db->get()->result());
        $this->benchmark->mark('code_end');

        $this->objCollection->queryTime =  $this->benchmark->elapsed_time('code_start', 'code_end');

        return $this->objCollection;
    }

}


class Accounts_Collection extends ArrayObject
{
    public $queryTime = 0;
}
  

Модель поиска

 class Search_model extends CI_Model
{
    private $strSearchQuery = "";

    public function getSearchObject()
    {
        if ($this->isValidSearch())
        {
            $this->load->model("Database_Model");
            $this->load->model("Accounts_Model");

            $objSearch = new Search;

            $objDBCollection = $this->Database_Model->getCollection();

            foreach($objDBCollection AS $objItem)
            {
                $this->db
                    ->where("DatabaseID", $objItem->ID)
                    ->where($this->input->post("searchBy"), $this->strSearchQuery);

                $objItem->collection = $this->Accounts_Model->getCollection();

            }

            $objSearch->addResultCollection($objDBCollection);

            return $objSearch;
        }
        return false;
    }

    public function isValidSearch()
    {
        $strSearchQuery = $this->security->xss_clean($this->input->post('query'));
        $this->strSearchQuery = trim($strSearchQuery);
        if (empty($this->strSearchQuery))   return false;

        $arrValidSearchCriteria = array("Email", "Username", "IP", "FullName", "Phone");
        return (in_array($this->input->post("searchBy"),arrValidSearchCriteria));

    }
}

class Search
{
    public $queryTime = 0;

    private $objCollection;

    public function addResultCollection(Database_Collection $objCollection)
    {
        $this->objCollection = $objCollection;
    }

    public function getRenderedTime()
    {
        if ($this->queryTime == 0)
        {
            $this->queryTime  = $this->objCollection->queryTime;

            foreach($this->objCollection AS $objItem)
            {
                if (isset($objItem->collection)
                {
                    $this->queryTime  = $objItem->collection->queryTime;
                }
            }
        }

        return $this->queryTime;
    }
    public function getCountSearchResults()
    {
        if (!$this->countSearchResults)
        {
            $this->countSearchResults = 0;

            foreach($this->objCollection AS $objItem)
            {
                if (isset($objItem->collection)
                {
                    $this->countSearchResults  = $objItem->collection->count();
                }
            }
        }

        return $this->countSearchResults;
    }
}
  

ваш контроллер

 class Welcome extends CI_Controller 
{
    public function index() 
    {
        $this->load->model("Search_model");

        $data['title'] = "Welcome | randomsite";

        if ($this->Search_model->isValidSearch()
        {
            $objSearch = $this->Search_model->getSearchObject();
            $arrViewData = array("objSearch" => $objSearch);
            $this->load->view("list-search", $arrViewData);

        }


    }
}
  

PS: возможно, есть некоторые опечатки, потому что я только что записал это