php select from where and problem - php

$name1 = #$_GET['search'] ;
$name = split(" +",$name1);
$query = "select * from table where field1 = '".$name[0]."'
and field2 = '".$name[1]."'
Order By `date` DESC";
I make a easy search like that, but if $name[0] and $name[1] all have data, the query can work, and if $name[1] is empty, the query is failed. how to add a judge that if $name[1] is empty, hidden and field2 = '".$name[1]."', and make the query like
$query = "select * from table where field1 = '".$name[0]."' Order BydateDESC";

You can do it with an or:
(and field2 = '".$name[1]."' or '".$name[1]."' = '')

Try this
if(!empty($name[0]) or !empty($name[1])){
$sql = "select * from table where ";
if($name[0]){
$fld1 = " field1 = '".$name[0]."'";
}
if($name[1]){
$fld2 = " field2 = '".$name[1]."'";
}
if($fld1 && $fld2)
{
$sql .= $fld1 ." and ".$fld2;
}
elseif($fld1){
$sql .= $fld1;
}
elseif($fld2){
$sql .= $fld2;
}
}

It will be better if you in your PHP script, do this check like this
$query = "select * from table where field1 = '$name[0]'"
if ($name[1]) $query .= " and field2 = '$name[1]'";
$query .= 'order by date desc';

$name[1]?'query of it exists':'query if it doesn't';

Related

How to create multiple search?

try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
i need to do multiple search, with first_name,last_name,middle_name,contact_no1 fields
If you want to do search with all fields add fields in WHERE with OR:
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR last_name LIKE :keyword OR middle_name LIKE :keyword OR contact_no1 LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
public function search($requestArray){
$sql = "";
if( isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE AND (`first_name` LIKE '%".$requestArray['search']."%' OR `last_name` LIKE '%".$requestArray['search']."%')";
if(isset($requestArray['firstname']) && !isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `first_name` LIKE '%".$requestArray['search']."%'";
if(!isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `last_name` LIKE '%".$requestArray['search']."%'";
$STH = $this->DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_OBJ);
$someData = $STH->fetchAll();
return $someData;
}
I used this method in one of my project for searching with two field hope it could help you. where $requestArray will get the data from form and 'firstname' , 'lastname' are two key of the array which you will enter your searchbox and submit to search. I just showed you here the query style and before that you have tor trim the values.

100 rows takes about 20 seconds to list

I am creating an in-house patient calendar, the clinic has more than 40K patients in the database.
I am trying to list around 9000 rows but it is taking extremely long time, I tried with 100 rows, it takes around 20 second, how can I make it much faster?
Here is my code:
$getPatients = $db->query("set names 'utf8'");
$q = "SELECT id, p_type, clinic_id, recommended_doctor, hdyhau, partnership_companies, p_auto_control_date, first_name, last_name, company, mobile, p_city, p_state, p_country, saved_by FROM dg_patients_patients WHERE clinic_id = {$defaultClinic} ORDER BY first_name ASC LIMIT 100";
$getPatients = $db->query($q);
$patientList = "";
while ($row = mysql_fetch_array($getPatients)) {
//Get Patient Type
$getPatientType = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_patient_type WHERE id = {$row['p_type']}";
$getPatientType = $db->query($q);
$patientType = mysql_fetch_array($getPatientType);
//Get Partnership Company
if($row['partnership_companies'] != '' && $row['partnership_companies'] > 0) {
$getPC = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_partnership_companies WHERE id = {$row['partnership_companies']}";
$getPC = $db->query($q);
$pc = mysql_fetch_array($getPC);
$pcname = $pc['pc_name'];
} else {
$pcname = '';
}
if(!empty($row['saved_by'])){
//Get User
$getUser = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_users WHERE id = {$row['saved_by']}";
$getUser = $db->query($q);
$user = mysql_fetch_array($getUser);
$savedby = $user['first_name'];
} else {
$savedby = '';
}
//Get Total Appointments
$q1 = "SELECT * FROM dg_appointments WHERE (appointment_type = 1 OR appointment_type =2 ) AND patient_id = {$row['id']}";
$getApps = $db->query($q1);
$totalAppointments = mysql_num_rows($getApps);
//Get Latest Appointment Date
$q11 = "SELECT * FROM dg_appointments WHERE appointment_status = 4 AND patient_id = {$row['id']} ORDER BY start_date DESC, start_time DESC LIMIT 1";
$getLastesApp = $db->query($q11);
$lastesApp = mysql_fetch_array($getLastesApp);
//Get Clinic
$getClinic = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_clinics WHERE id = {$row['clinic_id']}";
$getClinic = $db->query($q);
$clinic = mysql_fetch_array($getClinic);
//Get Doctor
if($row['recommended_doctor'] != '' && $row['recommended_doctor'] > 0) {
$getDoctor = $db->query("set names 'utf8'");
$q = "SELECT * FROM dg_users WHERE department = 2 AND id = {$row['recommended_doctor']}";
$getDoctor = $db->query($q);
$doctor = mysql_fetch_array($getDoctor);
$doctorID = $doctor['first_name'].' '.$doctor['last_name'];
} else {
$doctorID = '-';
}
//Get HDYHAU
if($row['hdyhau'] != '' && $row['hdyhau'] > 0){
$q = "SELECT * FROM dg_hdyhau WHERE id = {$row['hdyhau']}";
$getHDYHAU = $db->query($q);
$HDYHAU = mysql_fetch_array($getHDYHAU);
$HDYHAUID = $HDYHAU['hdyhau_name'];
} else {
$HDYHAUID = '-';
}
//Get Country
if($row['p_country'] != '' && $row['p_country'] > 0){
$getCountry = $db->query("set names 'utf8'");
$sql = "SELECT * FROM dg_ulke WHERE Id = {$row['p_country']}";
$getCountry = $db->query($sql);
$country = mysql_fetch_array($getCountry);
$countryID = $country['tr_TR'];
} else {
$countryID = '-';
}
//Get Cities
if($row['p_state'] != '' && $row['p_state'] > 0){
$getState = $db->query("set names 'utf8'");
$sql = "SELECT * FROM dg_il WHERE Id = {$row['p_state']}";
$getState = $db->query($sql);
$state = mysql_fetch_array($getState);
$stateID = $state['IlAdi'];
} else {
$stateID = '-';
}
//Get Streets
if($row['p_city'] != '' && $row['p_city'] > 0){
$getCity = $db->query("set names 'utf8'");
$sql = "SELECT * FROM dg_ilce WHERE Id = {$row['p_city']}";
$getCity = $db->query($sql);
$city = mysql_fetch_array($getCity);
$cityID = $city['IlceAdi'];
} else {
$cityID = '-';
}
$btn1 = "<a href='/apps/patients/patient-file.php?patientid=".$row['id']."#treatment_finance' target='_blank'><img src='/assets/images/Letter-T-blue-icon.png' width='24' height='24'></a>";
$btn2 = "<a href='/apps/patients/patient-file.php?patientid=".$row['id']."#patient_information' target='_blank'>".$row['first_name']." ".$row['last_name']."</a>";
if($lastesApp['start_date']){
$latestAppDate = date('d.m.Y', strtotime($lastesApp['start_date']));
} else {
$latestAppDate = '-';
}
if($row['p_auto_control_date'] != '' && $row['p_auto_control_date'] != '0000-00-00'){
$pacd = date('d.m.Y', strtotime($row['p_auto_control_date']));
} else {
$pacd = '-';
}
$btn5 = "<div class='checkbox checkbox-primary'><input id='checkboxPatients".$row['id']."' class='styled checkAllPatients' type='checkbox' name='checkAllPatients[]' value='".$row['id']."'><label for='checkboxPatients".$row['id']."'></label></div>";
$patientList .= "<tr>";
$patientList .= "<td>".$btn5."</td>";
$patientList .= "<td>".$clinic['clinic_name']."</td>";
$patientList .= "<td>".$btn1."</td>";
$patientList .= "<td>".$btn2."</td>";
$patientList .= "<td>".$row['mobile']."</td>";
$patientList .= "<td>".$cityID."</td>";
$patientList .= "<td>".$stateID."</td>";
$patientList .= "<td>".$row['company']."</td>";
$patientList .= "<td>".$pcname."</td>";
$patientList .= "<td>".$totalAppointments."</td>";
$patientList .= "<td>".$latestAppDate."</td>";
$patientList .= "<td>".$pacd."</td>";
$patientList .= "<td>".$savedby."</td>";
$patientList .= "<td>".$doctorID."</td>";
$patientList .= "<td>".$HDYHAUID."</td>";
$patientList .= "<td>".$countryID."</td>";
$patientList .= "</tr>";
}
echo $patientList;
You need to make index to clinic_id and first_name.
See this document http://www.w3schools.com/sql/sql_create_index.asp will help
You using too many queries in this code. reduce query will make better. use join to joining multiple table information to once, with conditions. http://www.w3schools.com/sql/sql_join_left.asp
set names utf8 only need once per code. If problem to fetching other language, checking my.cnf first to define default character set with server and connection.
use indexing in your table, index those fields which are using in where clause.
instead of use select * specify column name
instead of interacting database multiple type,fetch data from database at a time then using php show the data.
Try not using SELECT *.... instead give names of column(s) that you require and create Index on those column(s).
Warning: Just because indexing helps don't create index on all the columns cause index uses extra space
Check how to give indexing. I have attached image for you.
Syntax
ALTER TABLE `Table_name` ADD INDEX ( `Column_name` ) ;
Following are my suggestions:
1) You have 11 select queries. Out of it, 10 are in the loop and at least half of them run in the loop.
2) It means for every records in the top query, you are running 6 queries. For 100 rows, it is 600 queries (600 times database interaction). Therefore, your page is taking 20 seconds at least.
3) Again, every SQL has SELECT *, this takes more time as database tables may have number of fields.
Solution
1) Every SQL has SELECT *, use only required fields.
2) Try not to fire query in the loop.
3) Instead, get all records before loop and access them by key value array.
4) For example, the sql:
$q = "SELECT * FROM dg_users WHERE id = {$row['saved_by']}";
You can have an array of all users in array with key as user id and value as user name
And in the loop, get the value from this array like:
$savedby = isset($users[$row['saved_by']]) ? $users[$row['saved_by']] : '';
Repeat the same for all queries in the loop.
Hope, it will help you.

PHP, MySQL select all if

I have problem with PHP and MySQL please help..
$lokalita_s = $_POST['lokalita_s'];
$query = "SELECT nazov, lokalita FROM reality WHERE lokalita = '".$lokalita_s."' ORDER BY id";
............
But if ($lokalita_s == "nezáleží")... then i want to select every thing from database..
something like this :
$query = "SELECT nazov, lokalita FROM reality ORDER BY id";
............
This is not working :
$lokalita_s = 0;
$lokalita_s = NULL;
$lokalita_s = *;
I really dont want to use it like if else.. because i want to use more variables in that query and it won't be effective
Try
$lokalita_s = $_POST['lokalita_s'];
$wherClause = null;
if($lokalita_s != "nezáleží") {
$wherClause = "WHERE lokalita = '" . $lokalita_s . "'";
}
$query = "SELECT nazov, lokalita FROM reality $wherClause ORDER BY id";
Something along these lines? (This works in Oracle)
$lokalita_s = $_POST['lokalita_s'];
$query = "
SELECT nazov, lokalita FROM reality WHERE lokalita = '". $lokalita_s."'
UNION
select nazov,lokalita from reality where '". $lokalita_s. "' = 'nezáleží'
order by id
"

PHP MYSQL JOIN: Two Similar Tables

Am trying to join two tables with the same column but different values but each time i output it duplicates.
Here is my code:
<?php
$dept = $_SESSION['department'];
$dept1 = strtolower($dept);
$dept2 = str_replace(" ", "_", $dept1);
$dept4 = "$dept2" . "_200";
$dept = $_SESSION['department'];
$level = $_SESSION['level'];
$level2 = str_replace (" ", "_", $level);
if($level ="200_level") {
$query = " SELECT * FROM $dept2 Join $dept4";
}
else
{
$query = " SELCT * FROM $dept2";
}
$result = mysql_query($query) or die('<div class="header5"small_font">Your Courses are not available yet. Pls contact the ICT Unit</div>');
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$status = $row['status'];
$unit = htmlspecialchars($row['unit']);
?>
If you are looking to get the contents of two tables with the same columns, a MySQL UNION should help
UNION is used to combine the result from multiple SELECT statements into a single result set.
Like so:
$query = "(SELECT * FROM $dept2)
UNION
(SELECT * FROM $dept4)";

MySQL: Combining two repetitive queries to make WHERE clause dynamic

How can I combine these two queries into one so I don't have to repeat the same lines again and again?
if(empty($cat_id))
{
$sql = "
SELECT *
FROM root_category_contacts
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);
}
else
{
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql,array($cat_id));
}
I don't need WHERE clause when I don't have the cat_id.
Is it feasible?
Test if ? is null or equals cat_id. Something like this:
Edit based on xdazz's comment. And assuming that cat_id > 0
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC"
if(empty($cat_id)) {
$cat_id = 0;
}
$items_category = $connection->fetch_all($sql,array($cat_id));
if(empty($cat_id)) $where = "";
else $where = "WHERE root_category_contacts.cat_id != '$cat_id'"
$sql = "
SELECT *
FROM root_category_contacts
$where
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);

Categories