I have a page with 3 input fields, to search a database. But not all users are going to fill in all fields, so I need a way to make sure the database is checked fine.
Now, I wrote 8 different sql-statements, and with if-statements I check which fields are filled out. This works, but I do feel there must be a better to do this.
ID's in the search form are found in other tables in my database and loaded with jQuery's autocomplete.
Code now used:
<form action="" method="post">
<div class="ui-widget">
<section>
<label for="tags">Trefwoord:</label>
<input name="tags" id="tags"><input type="hidden" name="tags_id" class="tags_id" value="">
</section>
<section>
<label for="categorie">Categorie:</label>
<input name="cats" id="categorie"><input type="hidden" name="cats_id" class="cats_id" value="">
</section>
<section>
<label for="competentie">Competentie:</label>
<input name="com" id="competentie"><input type="hidden" name="com_id" class="com_id" value="">
</section>
<input type="submit" name="submit">
</div>
</form>
<?php
if(isset($_POST['submit'])) {
$trefwoord_id = $_POST['tags_id'];
$categorie_id = $_POST['cats_id'];
$p_trefwoord = $_POST['tags'];
$p_categorie = $_POST['cats'];
$competentie_id = $_POST['com_id'];
$p_comptentie = $_POST['com'];
if($trefwoord_id == null) {$sql = "SELECT * FROM spel_cat LEFT JOIN spel_com ON spel_cat.spelid = spel_com.spelid WHERE '$categorie_id' = catid && '$competentie_id' = comid";}
if($categorie_id == null) {$sql = "SELECT * FROM spel_tw LEFT JOIN spel_com ON spel_tw.spelid = spel_com.spelid WHERE '$trefwoord_id' = twid && '$competentie_id' = comid";}
if($competentie_id == null) {$sql = "SELECT * FROM spel_tw LEFT JOIN spel_cat ON spel_tw.spelid = spel_cat.spelid WHERE '$trefwoord_id' = twid && '$categorie_id' = catid";}
if($trefwoord_id == null && $categorie_id == null) {$sql = "SELECT * FROM spel_com WHERE '$competentie_id' = comid";}
if($trefwoord_id == null && $competentie_id == null) {$sql = "SELECT * FROM spel_cat WHERE '$categorie_id' = catid";}
if($categorie_id == null && $competentie_id == null) {$sql = "SELECT * FROM spel_tw WHERE '$trefwoord_id' = twid";}
if($trefwoord_id == null && $competentie_id == null && $categorie_id == null) {$sql = ""; echo "<b>Gebruik minstens 1 zoekterm</b>";}
if($trefwoord_id != null && $categorie_id != null && $competentie_id != null) {$sql = "SELECT * FROM (spel_tw LEFT JOIN spel_cat ON spel_tw.spelid = spel_cat.spelid) LEFT JOIN spel_com ON spel_cat.spelid = spel_com.spelid WHERE '$trefwoord_id' = twid && '$categorie_id' = catid && '$competentie_id' = comid";
}
if($sql != null) {
$games = mysqli_query($link,$sql) or die(mysql_error());
$num = mysqli_num_rows($games);
// AND SO ON...
WORKING CODE (thanks to OrangeHippo)
<?php
if(isset($_POST['submit'])) {
$trefwoord_id = $_POST['tags_id'];
$categorie_id = $_POST['cats_id'];
$p_trefwoord = $_POST['tags'];
$p_categorie = $_POST['cats'];
$competentie_id = $_POST['com_id'];
$p_comptentie = $_POST['com'];
$from = array();
$where = " 1 = 1 ";
if($trefwoord_id != null) {
$from["str"] = "spel_tw str";
$where .= " AND twid = '$trefwoord_id' ";
}
if($categorie_id != null) {
$from["sca"] = "spel_cat sca";
if (isset($from["str"])) {
$where .= " AND sca.spelid = str.spelid ";
}
$where .= " AND catid = '$categorie_id' ";
}
if($competentie_id != null) {
$from["sco"] = "spel_com sco";
if (isset($from["str"])) {
$where .= " AND sco.spelid = str.spelid ";
}else if (isset($from["sca"])) {
$where .= " AND sco.spelid = sca.spelid ";
}
$where .= " AND comid = '$competentie_id' ";
}
$sql = "SELECT * FROM " . implode(",", $from) . " WHERE $where";
if($trefwoord_id == null && $competentie_id == null && $categorie_id == null) {$sql = ""; echo "<b>Gebruik minstens 1 zoekterm</b>";}
//echo $sql;
if($sql != null) {
$games = mysqli_query($link,$sql) or die(mysql_error());
$num = mysqli_num_rows($games);
//AND SO ON ...
Ideally you would construct the query depending on the values that are passed:
$from = array();
$where = " 1 = 1 ";
if($trefwoord_id != null) {
$from["str"] = "spel_tw str";
$where .= " AND twid = '$trefwoord_id' ";
}
if($categorie_id != null) {
$from["sca"] = "spel_cat sca";
if (isset($from["str"])) {
$where = " AND sca.spelid = str.spelid ";
}
$where .= " AND catid = '$categorie_id' ";
}
if($competentie_id != null) {
$from["sco"] = "spel_com sco";
if (isset($from["str"])) {
$where = " AND sco.spelid = str.spelid ";
}else if (isset($from["sca"])) {
$where = " AND sco.spelid = sca.spelid ";
}
$where .= " AND comid = '$competentie_id' ";
}
$query = "SELECT * FROM " . implode(",", $from) . " WHERE $where";
As you see this way you have a lot less of text, making the code cleaner. If you want to have the code even more clean you can look to use some query builder library like doctrine2 DBAL
Related
I need help with my PDO prepared statements.
I know my code is not sanitized and is probably open to a lot of hell, but first I need to overcome this error before I can move on to sanitize my code.
I am trying to write a prepared statement with the WHERE clause, and somehow it keeps giving me an error that I am using a string for a type boolean. But what boolean??
I added a few vardumps before the error. It is in the counting part of my code.
After which, I would also take some pointers on how to make prepared statements out of user input.
I know, it is dangerous, but perhaps I can sanitize all the inner_join, outer_join etc into allowed table names using a in_array after a database table and column name check.
The reason I need to allow this user input is that I am making a website where people can make their own queries to the database and retrieve whatever info they need. But they should only be able to SELECT. Not UPDATE or DROP!
<?php
// Select existing
require_once('ajaxDBQuery.php');
if(!isset($included)) {
$_GET = json_decode($_GET["json"], true);
} else {
$_GET = json_decode($json, true);
}
class GET extends ajaxDBQuery
{
function __construct() {
parent::__construct($_GET['db']);
// ------------------------------------------------
$page = 0;
if (isset($_GET['offset']) && !empty($_GET['offset'])) {
$page = filter_var($_GET['offset'], FILTER_SANITIZE_NUMBER_INT);
}
$per_page = 20;
if (isset($_GET['limit']) && !empty($_GET['limit'])) {
$per_page = filter_var($_GET['limit'], FILTER_SANITIZE_NUMBER_INT);
}
if(isset($_GET['where']) && !empty($_GET['where'])) {
$sqlcount = "SELECT count(*) AS total_records FROM {$_GET['from']['table']} WHERE :test";
$statement = $this->conn->prepare($sqlcount);
var_dump($sqlcount);
var_dump($statement);
var_dump($_GET['where']);
$statement->bindParam(':test', $_GET['where'], PDO::PARAM_STR);
$statement->execute();
} else {
$sqlcount = "SELECT count(*) AS total_records FROM {$_GET['from']['table']}";
$statement = $this->conn->prepare($sqlcount);
$statement->execute();
}
$row = $statement->fetch();
$total_records = $row['total_records'];
$total_pages = ceil($total_records / $per_page);
$offset = ($page) * $per_page;
// ------------------------------------------------
$sql = "SELECT ";
for($i = 0; $i < count($_GET['select']['columns']); $i++) {
if($i == 0) {
$sql .= "{$_GET['select']['columns'][$i]}";
} else {
$sql .= ", {$_GET['select']['columns'][$i]}";
}
}
//{$_GET['select']['columns'][0]}
$sql .= " FROM {$_GET['from']['table']}";
(isset($_GET['from']['as']) && ($_GET['from']['as']) !== "") ? $sql .= " AS {$_GET['from']['as']}" : $sql .= "";
(isset($_GET['inner_join']['table']) && ($_GET['inner_join']['table']) !== "") ? $sql .= " INNER JOIN {$_GET['inner_join']['table']}" : $sql .= "";
(isset($_GET['inner_join']['as']) && ($_GET['inner_join']['as']) !== "") ? $sql .= " AS {$_GET['inner_join']['as']}" : $sql .= "";
if(isset($_GET['inner_join']['on']) && ($_GET['inner_join']['on']) !== "") {
for($i = 0; $i < count($_GET['inner_join']['on']); $i++) {
if($i == 0) {
$sql .= " ON {$_GET['inner_join']['on'][$i]}";
} else {
$sql .= " AND {$_GET['inner_join']['on'][$i]}";
}
}
}
(isset($_GET['left_join']['table']) && ($_GET['left_join']['table']) !== "") ? $sql .= " LEFT JOIN {$_GET['left_join']['table']}" : $sql .= "";
(isset($_GET['left_join']['as']) && ($_GET['left_join']['as']) !== "") ? $sql .= " AS {$_GET['left_join']['as']}" : $sql .= "";
if(isset($_GET['left_join']['on']) && ($_GET['left_join']['on']) !== "") {
for($i = 0; $i < count($_GET['left_join']['on']); $i++) {
if($i == 0) {
$sql .= " ON {$_GET['left_join']['on'][$i]}";
} else {
$sql .= " AND {$_GET['left_join']['on'][$i]}";
}
}
}
(isset($_GET['left_outer_join']['table']) && ($_GET['left_outer_join']['table']) !== "") ? $sql .= " LEFT OUTER JOIN {$_GET['left_outer_join']['table']}" : $sql .= "";
(isset($_GET['left_outer_join']['as']) && ($_GET['left_outer_join']['as']) !== "") ? $sql .= " AS {$_GET['left_outer_join']['as']}" : $sql .= "";
if(isset($_GET['left_outer_join']['on']) && ($_GET['left_outer_join']['on']) !== "") {
for($i = 0; $i < count($_GET['left_outer_join']['on']); $i++) {
if($i == 0) {
$sql .= " ON {$_GET['left_outer_join']['on'][$i]}";
} else {
$sql .= " AND {$_GET['left_outer_join']['on'][$i]}";
}
}
}
(isset($_GET['where']) && ($_GET['where']) !== "") ? $sql .= " WHERE {$_GET['where']}" : $sql .= "";
(isset($_GET['order_by']) && ($_GET['order_by']) !== "") ? $sql .= " ORDER BY {$_GET['order_by']}" : $sql .= "";
(isset($_GET['direction']) && ($_GET['direction']) !== "") ? $sql .= " {$_GET['direction']}" : $sql .= "";
(isset($_GET['limit']) && ($_GET['limit']) !== "") ? $sql .= " LIMIT {$_GET['limit']}" : $sql .= "";
(isset($_GET['offset']) && ($_GET['offset']) !== "") ? $sql .= " OFFSET ".$_GET['offset'] * $_GET['limit']."" : $sql .= "";
$statement = $this->conn->prepare($sql);
$statement->execute();
// ------------------------------------------------
// set the resulting array to associative
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$jsonArray = array();
//$jsonArray["totalrecords"] = $total_records;
$jsonArray["totalrecords"] = 1;
while ( ($row = $statement->fetch(PDO::FETCH_ASSOC) ) !== false) {
$jsonArray[] = $row;
}
// ------------------------------------------------
$this->return($jsonArray);
// ------------------------------------------------
}
private function return($jsonArray) {
header('Content-Type: application/json');
echo json_encode($jsonArray);
}
}
$query = new GET();
?>
OUTPUT:
string(56) "SELECT count(*) AS total_records FROM cb_cat WHERE :test"
object(PDOStatement)#3 (1) {
["queryString"]=>
string(56) "SELECT count(*) AS total_records FROM cb_cat WHERE :test"
}
string(27) "systemgrp BETWEEN 10 AND 19"
<br />
<b>Fatal error</b>: Uncaught PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type boolean: "systemgrp BETWEEN 10 AND 19" ...
I have the following problem: There is a gigantic query that concatenates a set of user-selectable conditions (select boxes, text fields, etc.).
By default, if nothing is selected anyway (not have conditions), sorting according to various parameters (Order by). The problem is that if there is a conditions, we have to add the word "WHERE", and only once, but should not add it if there are no conditions, since it is impossible to write after WHERE ORDER BY. How to solve this problem?
$payment_select = "select payment_id,
payment_agreement,
payment_dateagreement,
payment_action,
payment_close,
payment_charge,
payment_pay,
study_id,
card_id,
name_nominative,
surname_nominative,
patr_nominative,
studgroups_number,
dep_name,
study_kurs`
from
study
inner join card on card_id = study_card_id
inner join name on name_id = card_name_id
inner join surname on surname_id = card_surname_id
inner join dep on dep_id = study_dep_id
inner join studgroups on study_studgroups_id = studgroups_id
left join payment on study_id = payment_study_id
left join patr on patr_id = card_patr_id
";
if (isset($name_filter) && ($name_filter)) {
$payment_select. = " and name_nominative like '%".$name_filter. "%' ";
}
if (isset($surname_filter) && ($surname_filter)) {
$payment_select. = " and surname_nominative like '%".$surname_filter. "%' ";
}
if (isset($patr_filter) && ($patr_filter)) {
$payment_select. = " and patr_nominative like '%".$patr. "%' ";
}
if (isset($group_filter) && ($group_filter)) {
$payment_select. = " and studgroups_number like '%".$group_filter. "%' ";
}
if (isset($agreement_filter) && ($agreement_filter)) {
$payment_select. = " and payment_agreement like '%".$agreement_filter. "%' ";
}
if (isset($debt_filter) && ($debt_filter == 1)) {
$payment_select. = " and (payment_charge - payment_pay) > 0 ";
}
if (isset($debt_filter) && ($debt_filter == 2)) {
$payment_select. = " and (payment_charge - payment_pay) <= 0 ";
}
if (isset($card_filter) && $card_filter) {
$payment_select. = " and card_id = '$card_filter' ";
}
if (isset($study_filter) && $study_filter) {
$payment_select. = " and study_id = '$study_filter' ";
}
if (isset($recordbook_filter) and $recordbook_filter){
$payment_select. = " and study_recordbook like '$recordbook_filter%' ";
}
if (isset($action_filter) && ($action_filter == 1)) {
$payment_select. = " and payment_action = 1 ";
}
if (isset($action_filter) && ($action_filter == 2)) {
$payment_select. = " and payment_action = 0 ";
}
if (isset($close_filter) && ($close_filter == 1)) {
$payment_select. = " and payment_close = 0 ";
}
if (isset($close_filter) && ($close_filter == 2)) {
$payment_select. = " and payment_close = 1 ";
}
if (isset($dep_filter) && ($dep_filter)) {
$dep = select_dep_array();
$payment_select. = " and dep_acronym like '".$dep[$dep_filter]. "' ";
}
if (isset($kurs_filter) && ($kurs_filter > 1)) {
$payment_select. = " and study_kurs = ". ($kurs_filter - 1). " ";
}
if (isset($educform_filter) && ($educform_filter >= 1)) {
$payment_select. = " and study_formeduc_id = ".$educform_filter. " ";
}
if (isset($progr_filter) && ($progr_filter >= 1)) {
$payment_select. = " and study_program_id = ".$progr_filter. " ";
}
if (preg_match("/^\d(\d)?\.\d(\d)?\.\d\d\d\d$/", $date_from_filter)) {
$date_from_mysql = date_user_to_mysql($date_from_filter);
} else {
if ($date_from_filter)
$error_msg = "Дата введена неправильно.";
}
if (preg_match("/^\d(\d)?\.\d(\d)?\.\d\d\d\d$/", $date_to_filter)) {
$date_to_mysql = date_user_to_mysql($date_to_filter);
} else {
if ($date_to_filter)
$error_msg = "Дата введена неправильно.";
}
if ((isset($date_from_mysql) && ($date_from_mysql)) && !(isset($date_to_mysql) && ($date_to_mysql))) {
$payment_select. = "and payment_date_agreement >= '".$date_from_mysql. "' ";
}
if (!(isset($date_from_mysql) && ($date_from_mysql)) && (isset($date_to_mysql) && ($date_to_mysql))) {
$payment_select. = "and payment_dateagreement <= '".$date_to_mysql. "' ";
}
if ((isset($date_from_mysql) && ($date_from_mysql)) && (isset($date_to_mysql) && ($date_to_mysql))) {
$payment_select. = "and payment_dateagreement >= '".$date_from_mysql.
"' and payment_dateagreement <= '".$date_to_mysql. "' ";
}
if (isset($order) && ($order)) {
if ($order == 3) {
if ($desc) {
$payment_select. = " order by surname_nominative desc, name_nominative desc, patr_nominative desc";
} else {
$payment_select. = " order by ".$order_array[$order];
}
} else {
$payment_select. = " order by ".$order_array[$order];
if ($desc) {
$payment_select. = " desc ";
}
}
}
Instead of directly extend your SQL, you can first collect all your "where clauses" in an array and then check if it is not empty and then implode it. Like this:
//your select
$payment_select = "SELECT ....";
//helper var
$where_clauses = [];
//from your example
if (isset($name_filter) && ($name_filter)) {
$where_clauses[] = "name_nominative like '%".$name_filter. "%'";
}
//from your example
if (isset($surname_filter) && ($surname_filter)) {
$where_clauses[] = "surname_nominative like '%".$surname_filter. "%'";
}
//now append the clauses if there any
if (! empty($where_clauses)) {
$payment_select .= " WHERE " . implode(" AND ", $where_clauses)
}
I need help in something.
On the site where I'm working I have the option to search users, but when we search users we can see every user no matter the frontoffice and I need help for each user see only users that belong to the same frontoffice. I tried the following code:
if ($row->idFrontOfficeSinalizador == $idFrontOfficeSinalizador)
Where the $row->idFrontOfficeSinalizador is the users frontoffice id and the $idFrontOfficeSinalizador is my frontoffice id
This is all the code that I have
include('importarBibliotecas.php');
if (!isset($_SESSION['id']) || $_SESSION['idTiposDePermissoes'] == 3 )
echo "<script>window.location='index.php'</script>";
?>
<script src='scriptFormUtentes.js'></script>
<script>
function makeDivVisible(){
document.getElementById('encaminharUtentes').style.display='block';
}
function makeDivInvisible(){
document.getElementById('encaminharUtentes').style.display='none';
}
function makeDivEdInvisible(){
document.getElementById('editarEncaminharUtentes').style.display='none';
}
</script>
<?php
include('menu.php');
include('gerirUtentesFormEditarUtente.php');
include('gerirUtentesFormEditarEncaminhamento.php');
include('gerirUtentesPOSTEditarUtente.php');
if (isset($_POST['NIFS']) || isset($_GET['n'])){ //pesquisar utentes por NIF
include_once('DataAccess.php');
$da = new DataAccess();
if (isset($_POST['NIFS'])){
$nif = $_POST['NIFS'];
$nome = $_POST['Nome'];
$idFrontOfficeSinalizador = $_POST['frontoffice'];
$emailTecnico = $_POST['email'];
$interesseProfissional = $_POST['interesseProfissional'];
$escolaridade = $_POST['Escolaridade'];
$situacaoEmprego = $_POST['situacaoEmprego'];
$estado = $_POST['estado'];
$res = $da->getUtentes($nif, $nome, $idFrontOfficeSinalizador, $emailTecnico, $interesseProfissional, $escolaridade, $situacaoEmprego, $estado);
//PU = Pesquisa de Utentes
$_SESSION['PU_nif'] = $nif;
$_SESSION['PU_nome'] = $nome;
$_SESSION['PU_idFrontOfficeSinalizador'] = $idFrontOfficeSinalizador;
$_SESSION['PU_emailTecnico'] = $emailTecnico;
$_SESSION['PU_interesseProfissional'] = $interesseProfissional;
$_SESSION['PU_escolaridade'] = $escolaridade;
$_SESSION['PU_situacaoEmprego'] = $situacaoEmprego;
$_SESSION['PU_estado'] = $estado;
$numPaginas = mysql_num_rows($res)/15;
$numPaginas = ceil ($numPaginas);
$_SESSION['PU_numPaginas'] = $numPaginas;
$pagAtual = $_GET['pg'];
$res = $da->getUtentesPorPagina($nif, $nome, $idFrontOfficeSinalizador, $emailTecnico, $interesseProfissional, $escolaridade, $situacaoEmprego, $estado, $pagAtual);
//echo "<script>alert('".mysql_num_rows($res)." $numPaginas')</script>";
}else{
$nif = $_GET['n'];
$res = $da->getUtenteNIF($nif);
}
}else{
if (isset($_GET['pg'])){
$nif = $_SESSION['PU_nif'];
$_POST['NIF'] = $nif;
$nome = $_SESSION['PU_nome'];
$_POST['Nome'] = $nome;
$idFrontOfficeSinalizador = $_SESSION['PU_idFrontOfficeSinalizador'];
$_POST['frontoffice'] = $idFrontOfficeSinalizador;
$emailTecnico = $_SESSION['PU_emailTecnico'];
$_POST['email'] = $emailTecnico;
$interesseProfissional = $_SESSION['PU_interesseProfissional'];
$_POST['interesseProfissional'] = $interesseProfissional;
$escolaridade = $_SESSION['PU_escolaridade'];
$_POST['Escolaridade'] = $escolaridade;
$situacaoEmprego = $_SESSION['PU_situacaoEmprego'];
$_POST['situacaoEmprego'] = $situacaoEmprego;
$estado = $_SESSION['PU_estado'];
$_POST['estado'] = $estado;
$res = $da->getUtentesPorPagina($nif, $nome, $idFrontOfficeSinalizador, $emailTecnico, $interesseProfissional,
$escolaridade, $situacaoEmprego, $estado, $_GET['pg']);
if ( mysql_num_rows($res) == 0){ //se a página não devolver resultados, mostra a primeira página
echo "<script>window.location='gerirUtentes.php?pg=1'</script>";
}
}
//pesquisar utente depois de clicar em Encaminhar
if (isset($_GET['f'])){
include_once('DataAccess.php');
$da = new DataAccess();
$res = $da->getUtente($_GET['f']);
}
//inserir encaminhamento
if (isset($_POST['buttonInserirEncaminhamentoUtente'])){
$idUtente = $_POST['idUtente'];
$idTecnico = $_POST['idTecnico'];
$data = $_POST['data'];
$texto = $_POST['observacoes'];
include_once('DataAccess.php');
$da = new DataAccess();
$da->inserirEncaminhamento($data, $texto, $idTecnico, $idUtente);
echo "<script>alert('Diligência inserida com sucesso')</script>";
}else{
//editar encaminhamento
if (isset($_POST['buttonEditarEncaminhamento'])){
$id = $_POST['id'];
$idUtente = $_POST['edit_idUtente'];
$idTecnico = $_POST['edit_idTecnico'];
$data = $_POST['edit_data'];
$texto = $_POST['edit_observacoes'];
include_once('DataAccess.php');
$da = new DataAccess();
$da->editarEncaminhamento($id, $data, $texto, $idTecnico, $idUtente);
echo "<script>alert('Diligência editada com sucesso')</script>";
}
}
}
include('gerirUtentesFormPesquisa.php');
if (isset($_POST['NIFS']) || isset($_GET['f']) || isset($_GET['n'])){
echo "<div class='ink-grid'>
<table style='width:100%' class='ink-table'>
<thead>
<tr>
<th style='width:25%' align='left'>Nome</th>
<th style='width:15%' align='left'>Pedido Inicial</th>
<th style='width:10%' align='left'>Situação</th>
<th style='width:15%' align='left'>Habilitações</th>
<th style='width:20%' align='left'>Interesse Profissional</th>
<th style='width:10%' align='left'>FrontOffice</th>
<th style='width:15%'></th>
</tr>
</thead>
<tbody>";
$numPaginas = $_SESSION['PU_numPaginas'];
if ($numPaginas > 1){
$next = $_GET['pg'] + 1;
if ($next == $numPaginas)
$next = 1;
if ($_GET['pg'] == 1)
$before = $numPaginas;
else
$before = $_GET['pg']-1;
echo "<tr>
<td><a href='gerirUtentes.php?pg=$before' class='button'>Pág. Anterior</a></td>
<td colspan='4'> </td>
<td align='right'><a href='gerirUtentes.php?pg=$next' class='button'>Pág. Seguinte</a></td>
</tr>";
}
while($row = mysql_fetch_object($res)){
if ($row->interesseProfissional1 != -1)
$nomeIP = $da->getInteresseProfissional($row->interesseProfissional1);
else
$nomeIP = "---";
if ($row->idFrontOfficeSinalizador != -1)
$nomeFO = $da->getFrontOfficeName($row->idFrontOfficeSinalizador);
else
$nomeFO = "---";
if ($row->idHabilitacoes != -1)
$Habilitacao = $da->getHabilitacao($row->idHabilitacoes);
else
$Habilitacao = "---";
$situacaoProfissional="";
switch ($row->empregado){
case 1: $situacaoProfissional = "Empregado";
break;
case 0: $situacaoProfissional = "Desempregado";
break;
}
if ($row->Estudante == 1){
if ($situacaoProfissional != "") $situacaoProfissional .= ", ";
$situacaoProfissional .= "Estudante";
}
if ($row->outraSituacao == 1){
if ($situacaoProfissional != "") $situacaoProfissional .= ", ";
$situacaoProfissional .= "Outra Situação";
}
if($situacaoProfissional == "") $situacaoProfissional="---";
$pedidoInicial = "";
if($row->pedidoInicialEmprego == 1)
$pedidoInicial = "Emprego";
if($row->pedidoInicialFormacao == 1){
if ($pedidoInicial != "")
$pedidoInicial .= ", Formação";
else
$pedidoInicial = "Formação";
}
if($row->pedidoInicialOutra == 1){
if ($pedidoInicial != "")
$pedidoInicial .= ", Outra";
else
$pedidoInicial = "Outra";
}
echo "<tr>
<td>
<a href='gerirUtentes.php?i=$row->a&f=$row->a' title='Detalhes do utente'><img src='img/info.png' style='width:25px'/>
<font color='black'>$row->nome</font>
</a>
</td>
<td>$pedidoInicial</td>
<td>$situacaoProfissional</td>
<td>$Habilitacao</td>
<td>$nomeIP</td>
<td>$nomeFO</td>
<td align='right'>
";
if ($row->Email != "")
echo "<a href='enviarEmail.php?i=$row->id' target='_blank'><img title='Enviar E-mail para utente' src='img/mail.png' style='width:20px'/></a> ";
$numEncaminhamentos = $da->getNumEncaminhamentos($row->a);
if ($numEncaminhamentos >0)
echo "<a href='gerirUtentes.php?f=$row->a' style='text-decoration: none;'>
<img title='Diligências efetuadas' src='img/forward.png' style='width:20px'/>
<font size='1'>$numEncaminhamentos</font>
</a>";
else
echo "<a href='gerirUtentes.php?f=$row->a'>
<img title='Diligências efetuadas' src='img/forward.png' style='width:20px'/>
</a>
<br/>";
if ($row->CV != "")
echo "<a href='CVs/$row->CV' target='_blank'><img title='Download do CV' src='img/cv.png' style='width:20px'/></a> ";
//download informações para pdf
echo "<a href='PDF.php?i=$row->a' target='_blank'>
<img title='Download das informações pessoais' src='img/pdf.png' style='width:24px'/>
</a>";
echo "
<a href='gerirUtentes.php?d=$row->a' onclick='return confirmarApagarUtente()'><img title='Apagar utente' src='img/delete3.png' style='width:20px'/></a>
</td>
</tr>";
}
if ($numPaginas > 1){
echo "<tr>
<td><a href='gerirUtentes.php?pg=$before' class='button'>Pág. Anterior</a></td>
<td colspan='4'> </td>
<td align='right'><a href='gerirUtentes.php?pg=$next' class='button'>Pág. Seguinte</a></td>
</tr>";
}
echo "</tbody>
</table>
</div>";
}
if (isset($_GET['d'])) {
include_once('DataAccess.php');
$da = new DataAccess();
$da -> deleteUtente($_GET['d']);
echo"
<script>alert('Utente eliminado com sucesso.');</script>";
}
include('gerirUtentesResultadosEncaminhamento.php');
if(isset($_GET['i'])){
include_once('DataAccess.php');
$da = new DataAccess();
$res = $da->getUtente($_GET['i']);
//ver campos do utente!!
verFormEditarUtente();
}
include('footer.php');
?>
</body>
</html>
DataAcces ->
function getUtentes($nif, $nome, $idFrontOfficeSinalizador, $emailTecnico, $interesseProfissional, $Escolaridade, $situacaoEmprego,$estado){
$this->connect();
$idTecnico = -1;
if ($emailTecnico != "")
{
$query = "select id from tecnicos where email = '$emailTecnico'";
$res = $this->execute($query);
if (mysql_num_rows($res)>0){
$row = mysql_fetch_array($res);
$idTecnico = $row[0];
}
}
$query = "select *, U.id as a from utentes U where estado=$estado ";
if ($nome != "")
$query .= " and nome like '%$nome%' ";
if ($idFrontOfficeSinalizador != "" && $idFrontOfficeSinalizador != "-1")
$query .= " and idFrontOfficeSinalizador = $idFrontOfficeSinalizador ";
if ($nif != "")
$query .= " and NIF = $nif ";
if ($interesseProfissional != -1 && $interesseProfissional != "")
$query .= " and (interesseProfissional1 = $interesseProfissional or interesseProfissional2 = $interesseProfissional or interesseProfissional3 = $interesseProfissional) ";
if ($Escolaridade != -1 && $Escolaridade != "")
$query .= " and idHabilitacoes = $Escolaridade ";
switch ($situacaoEmprego)
{
case 1:
$query .= " and empregado = 1";
break;
case 2:
$query .= " and empregado = 0";
break;
case 3:
$query .= " and Estudante = 1";
break;
case 4:
$query .= " and outraSituacao = 1";
break;
default:
break;
}
if ($idTecnico != -1)
$query .= " and idTecnico = $idTecnico ";
$query .= " order by U.nome asc ";
//echo $query;
$res = $this->execute($query);
$this->disconnect();
return $res;
}
function getUtentesPorPagina($nif, $nome, $idFrontOfficeSinalizador, $emailTecnico, $interesseProfissional, $Escolaridade,
$situacaoEmprego,$estado, $pagina){
$this->connect();
$idTecnico = -1;
if ($emailTecnico != "")
{
$query = "select id from tecnicos where email = '$emailTecnico'";
$res = $this->execute($query);
if (mysql_num_rows($res)>0){
$row = mysql_fetch_array($res);
$idTecnico = $row[0];
}
}
$query = "select *, U.id as a from utentes U where estado=$estado ";
if ($nome != "")
$query .= " and nome like '%$nome%' ";
if ($idFrontOfficeSinalizador != "" && $idFrontOfficeSinalizador != "-1")
$query .= " and idFrontOfficeSinalizador = $idFrontOfficeSinalizador ";
if ($nif != "")
$query .= " and NIF = $nif ";
if ($interesseProfissional != -1 && $interesseProfissional != "")
$query .= " and (interesseProfissional1 = $interesseProfissional or interesseProfissional2 = $interesseProfissional or interesseProfissional3 = $interesseProfissional) ";
if ($Escolaridade != -1 && $Escolaridade != "")
$query .= " and idHabilitacoes = $Escolaridade ";
switch ($situacaoEmprego)
{
case 1:
$query .= " and empregado = 1";
break;
case 2:
$query .= " and empregado = 0";
break;
case 3:
$query .= " and Estudante = 1";
break;
case 4:
$query .= " and outraSituacao = 1";
break;
default:
break;
}
if ($idTecnico != -1)
$query .= " and idTecnico = $idTecnico ";
$query .= " order by U.nome asc ";
$queryAux = $query;
$pagina = ($pagina-1) * 15;
$query .= " limit $pagina, 15 ";
$res = $this->execute($query);
/*
if ( mysql_num_rows($res) == 0){ //se a página não devolver resultados, mostra a primeira página
$pagina = 0;
$queryAux .= " limit $pagina, 15 ";
$res = $this->execute($queryAux);
}*/
$this->disconnect();
return $res;
}
function getUtenteNIF($nif){
$query = "select *, U.id as a from utentes U
where U.NIF = $nif";
$this->connect();
$res = $this->execute($query);
$this->disconnect();
return $res;
}
Whatever your query is, add a new condition to it for that in WHERE clause
AND idFrontOfficeSinalizador = 4 // use correct variable here
I have written a simple search algorithm for my advanced search of my website.
There are several categories that the advanced search helps the user to limit his/her search. %$variable% is the matching that I use. I want the database to return every possible matches if the title is empty...what should be added/removed to/from this code?
if(isset($_POST['type']) && $_POST['type'] != 0)
{
$type = $_POST['type'];
if($wh == true)
{
$statement .= " AND `type` = '$type' ";
}
else
{
$wh = false;
$statement .= " WHERE `type` = '$type' ";
}
}
if(isset($_POST['sex']) && $_POST['sex'] != 0)
{
$sex = $_POST['sex'];
if($wh == true)
{
$statement .= " AND `sex` = '$sex' ";
}
else
{
$wh = false;
$statement .= " WHERE `sex` = '$sex' ";
}
}
if(isset($_POST['start']) && $_POST['start'] != 0)
{
$start = $_POST['start'];
if($wh == true)
{
$statement .= " AND `start` > '$start' ";
}
else
{
$wh = false;
$statement .= " WHERE `start` > '$start' ";
}
}
if($wh==true)
{
$statement .= " $branch_sentence AND( `title` LIKE '%$search_term%' OR `content` LIKE '%$search_term%' OR `keywords` LIKE '%$search_term%') ORDER BY stars DESC ";
}
else
{
$statement .= " WHERE `title` LIKE '%$search_term%' OR `content` LIKE '%$search_term%' OR `keywords` LIKE '%$search_term%' ORDER BY stars DESC ";
}
// echo $statement;
if($transorder = $site_db->query($statement))
{
$i=0;
while($row_obj = $transorder->fetch_object())
{
$item[$i]['id'] = $row_obj->id;
$item[$i]['pic_main'] = $row_obj->pic_main;
$item[$i]['title'] = $row_obj->title;
$item[$i]['province'] = $row_obj->province;
$item[$i]['stars'] = $row_obj->stars;
$i++;
}
}
}
}
What's wrong with:
if (empty($_POST['title']))
{
$statement = "SELECT id, pic_main, title, province, stars FROM "; // Incomplete b/c I don't know your table name from the question.
}
?
I have form like this:
<form method="POST" action="<?php echo base_url() ?>admin/admin_search">
<fieldset>
<label for="nalozi">Nalozi</label><input type="checkbox" name="nalozi" />
<label for="malio_glasi">Mali oglasi</label><input type="checkbox" name="mali_oglasi" />
<label for="zute_strane">Zute strane</label><input type="checkbox" name="zute_strane" />
<label for="berza_rada">Berza rada</label><input type="checkbox" name="berza_rada" />
<label for="vesti">Vesti</label><input type="checkbox" name="vesti" />
<label for="event">Dogadjaji</label><input type="checkbox" name="event" />
</fieldset>
<input type="search" name="keyword" id="keyword" />
<input type="submit" value="Trazi"/>
</form>
and PHP code for searching:
function admin_search(){
$keyword = trim($_POST['keyword']);
$search_explode = explode(" ", $keyword);
$x = 0;
$mgs = isset($_POST['mali_oglasi']) ? 1 : "";
$jbs = isset($_POST['berza_rada']) ? 2 : "";
$nws = isset($_POST['vesti']) ? 3 : "";
$ypg = isset($_POST['zute_strane']) ? 4 : "";
if($mgs != "" || $jbs != "" || $nws != "" || $ypg != ""){$or = " OR ";}else{$or = "";}
if($jbs != "" || $nws != "" || $ypg != "" ){$or1 = " OR ";}else{$or1 = "";}
if($nws != "" || $ypg != "" ){$or2 = " OR ";}else{$or2 = "";}
if($ypg != "" ){$or3 = " OR ";}else{$or3 = "";}
$nlz = isset($_POST['nalozi']) ? "person" : "";
$dgj = isset($_POST['event']) ? "event" : "";
if($nlz != "" || $dgj != ""){$z = ", "; $or_like = " OR "; }else{$z = " "; $or_like = "";}
if($dgj != ""){$z1 = ", ";$or_like1 = " OR ";}else{$z1 = " ";$or_like1 = "";}
if($mgs != "" || $ypg != "" || $jbs != "" || $nws != ""){$gi = "global_info";}else{$gi = "";}
$sql = "SELECT * FROM ";
if($gi != ""){$sql .= " $gi $z";}
if($nlz != ""){$sql .= " $nlz $z1";}
if($dgj != ""){$sql .= " $dgj";}
$sql .= " WHERE ";
if($mgs != ""){$sql .= " global_info.info_type_id = {$mgs} $or1 ";}
if($jbs != ""){$sql .= " global_info.info_type_id = {$jbs} $or2 ";}
if($nws != ""){$sql .= " global_info.info_type_id = {$nws} $or3 ";}
if($ypg != ""){$sql .= " global_info.info_type_id = {$ypg} ";}
$sql .= " AND ";
foreach($search_explode as $each){
$x++;
if($x == 1){
if($gi != ""){$sql .= " global_info.name LIKE '%$each%' $or_like ";}
if($nlz != ""){$sql .= " $nlz.name LIKE '%$each%'$or_like1 ";}
if($dgj != ""){$sql .= " $dgj.name LIKE '%$each%' ";}
} else {
$sql .= " AND global_info.name LIKE '%$each%' ";
}
}
echo $sql;
$q = $this->db->query($sql);
echo $q->num_rows();
return $q = $q->num_rows() == 0 ? FALSE : $q->result_array();
}
Idea behind this search - I must be able to choose witch tables I want to search and the search by the keyword(s) need to work for any table choosen.
When one of the checkboxes is checked, it is working fine, but if two or more are checked, and if there is more than one keyword (for the moment I am trying just global_info table with two or more keywords), function is working fuzzy. Sometimes it does not work, or if it is working it is giving same results multiple times, or everything except the keyword. At the moment I don't quite understand why it is giving results that it is giving. How to make this work?
Try changing it to read like this:
$tables = array();
if(isset($_POST['mali_oglasi'])){
$tables['mgs'] = 1;
}
/*
repeat for the other tables
*/
/* Where you're building your WHERE clause, use this instead of the 'OR' logic */
if(!empty($tables)){
$sql .= 'global_info.info_type_id IN (' . implode(',',$tables) . ')';
}