I need to connect a initiative table with locations one, there is a column at initiative table which ill contain multiple ids or single ids, depends on how much is added. The data will be saved like this:
"1,4,3"
public function getallRIS(){
$connect = $this->connect;
/*
THIS QUERY WORKS WITHOUT MULTIPLE IDS ON THE COLUMN
$qx = "SELECT initiatives.location_id as init_location, initiatives.name as init_name, initiatives.startyear as init_startyear, initiatives.endyear as init_endyear, ST_AsText(locations.location) as locations_coord, locations.name as locations_name
FROM locations
JOIN initiatives on initiatives.location_id = locations.id";
*/
$qx = "SELECT GROUP_CONCAT(initiatives.location_id SEPARATOR ',') as init_location, initiatives.name as init_name, initiatives.startyear as init_startyear, initiatives.endyear as init_endyear, ST_AsText(locations.location) as locations_coord, locations.name as locations_name
FROM locations
JOIN initiatives
ON FIND_IN_SET(locations.id, initiatives.location_id)
GROUP BY initiatives.location_id";
$queryx = "SELECT ST_AsText(ri_location) FROM ri;";
if($query = $connect->query($qx)){ }else{ echo $connect->error; }
$count = $query->num_rows;
$row = 1;
while($fetch = $query->fetch_array(MYSQLI_ASSOC)){
$point = $fetch['locations_coord'];
$point = str_replace(array("POINT(",")"),array("",""),$point);
$point = str_replace(" ",",",$point);
$coord = explode(",",$point);
$lat = $coord[0];
$long = $coord[1];
echo'
{
lat: '.$lat.',
lng: '.$long.',
text: "'; echo "<b style='font-size:17px;'>"; echo''.$fetch['init_name'].'</b><br>Country: '.$fetch['locations_name'].'<br>Info: '; echo"<a href=''>"; echo'View</a><br>Start Year: '.$fetch['init_startyear'].'<br>End Year: '.$fetch['init_endyear'].'"
},
';
$row++;
}
}
However is not working properly , shows only first item of each column
Related
Below is my pretty simple attempt at trying to count the number of times $name string occurs in the $related_company string row of a table.
I was hoping it would spit out a number, but when i upload it to my webserver, it doesnt spit out anything.
Any ideas?
<?php
$db = new SQLite3('database.sqlite3');
$red = $db->query('SELECT * FROM news');
$name = strtolower("Tesla");
$related_company = $red->fetchArray($row['related_company']);
while ($row = $red->fetchArray()) {
if (in_array($name, $related_company)){
$count+1;
}}
echo $count;
?>
You can do it all in a single query, without having to loop through the results. SQL has a LIKE operator to perform pattern matching in columns.
$db = new SQLite3('database.sqlite3');
$stmt = $db->prepare("SELECT COUNT(*) AS count FROM news WHERE related_company LIKE :name");
$name = '%' . strtolower("Tesla") . '%';
$stmt->bindParam(':name', $name);
$stmt->execute();
$row = $stmt->fetchArray(SQLITE3_ASSOC);
$count = $row['count'];
echo $count;
If the name comes from another table, you can join the tables.
$result = $db->query("
SELECT c.name, COUNT(*) as count
FROM Companies AS c
JOIN news AS n ON n.related_company LIKE '%' || LOWER(c.name) || '%'");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
echo "{$row['name']}: {$row['count']}<br>";
}
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.
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)";
My application requires to create a stock management table which has a lot of items categorised into subgroups. For and idea, the stock management table looks like:
Location1 Location2 Total
Desktops // Main Category
Microsoft //Sub-Category
Windows 7 23000 150000 173000
Office 2011 203300 3002 206302
....
Apple //Sub-Category
OS Snow Leopard 4000 3000 7003
OS Lion 39494 40034 79528
...
Tablets //Main Category
Lenovo //Sub-Cateogry
LX-243 3434 4399 7833
...
This is a visualisation of what the table should look like, now i have a huge mysql query which does that for me, it is scary. In a gist, what i am doing is the following:
Select 1st category and start a while loop
// echo as the main category
Select sub-category corresponding to the main category and start a while loop again.
// echo as the sub-category
select all items in the sub-category and start a while loop.
select 1st location.
select the current item from 3 and the current location from 4 and echo item.
// echo item names and the quantity in the locations.
Now my question here is is there a better way to display this than using several while loops, i tried using functions but they are becoming a mess too. Also i couldn't figure out where should i perform the calculations to get the total in the last column.
Database structure:
Category: CategoryID, Description
Sub-Cateogry: Sub-Category_ID, Category_ID, Description
Item: Item_ID, Sub-category_id, Description
Location: Location_ID, Description
Stock_Management: Item_ID, Location_ID, Quantity
Code as requested:
$sql = mysql_query("select Board_ID, Title from Board where Company_ID = '$company_id' order by Title");
while($row = mysql_fetch_array($sql)) {
$curr_ID = $row[0];
$curr_category = $row[1];
echo "<tr class='sub-heading' style='background: rgba(76, 178, 255, 0.1)'><td colspan='".$count."'>".$curr_category."</td></tr>";
$sql1 = mysql_query("select Sub_Category_ID, Title from Sub_Category where Category_ID = '$curr_ID' order by Title");
while($row1 = mysql_fetch_array($sql1)) {
$curr_sub_cat_id = $row1[0];
$curr_sub_cate = $row1[1];
echo "<tr style='background: rgba(149, 255, 145, 0.10'><td colspan='".$count."'><b>".$curr_sub_cate."</b></td></tr>";
$sql2 = mysql_query("select Book_ID, title from Book where sub_category_id = '$curr_sub_cat_id' Order by title");
while($row2 = mysql_fetch_array($sql2)) {
$curr_book = $row2[0];
echo "<tr><td>".$row2[1]."</td>";
$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('$locations')");
while($row3 = mysql_fetch_array($sql4)) {
$curr_location = $row3[0];
$sql3 = mysql_query("select Quantity from Stock_Management where Book_ID = '$curr_book' and Location_ID = '$curr_location'");
while($row3 = mysql_fetch_array($sql3)) {
echo "<td>".$row3[0]."</td>";
}
}
echo "</tr>";
}
}
}
How about something like this -
<?php
$locations = array('Location 1', 'Location 2', 'Location 3');
$locationCols = array();
$locationList = array();
foreach ($locations as $location) {
$locationColName = preg_replace('[^a-z0-9]', '_', strtolower($location));
$location = mysql_real_escape_string($location);
$locationCols[] = "SUM(IF(Office.OfficeTitle = '$location', Stock_Management.Quantity, 0)) AS `$locationColName`";
$locationList[] = "'$location'";
}
$locationCols = implode(', ', $locationCols);
$locationList = implode(',', $locationList);
$sql = "SELECT Board.Title AS BoardTitle, Sub_Category.Title AS SubCatTitle, Book.title AS BookTitle, $locationCols, SUM(Stock_Management.Quantity) AS Total
FROM Board
INNER JOIN Sub_Category
ON Board.Board_ID = Sub_Category.Category_ID
INNER JOIN Book
ON Sub_Category.Sub_Category_ID = Book.sub_category_id
INNER JOIN Office
LEFT JOIN Stock_Management
ON Book.Book_ID = Stock_Management.Book_ID
AND Office.OfficeID = Stock_Management.Location_ID
WHERE Board.Company_ID = 2
AND Office.OfficeTitle IN ($locationList)
GROUP BY Board.Title, Sub_Category.Title, Book.title";
$result = mysql_query($sql);
$prevBoard = '';
$prevSubCat = '';
echo '<table>';
while ($row = mysql_fetch_object($result)) {
// if new board print board
if ($prevBoard != $row->BoardTitle) {
echo '<tr class="sub-heading" style="background: rgba(76, 178, 255, 0.1)"><td colspan="">' . $row->BoardTitle . '</td></tr>';
}
$prevBoard = $row->BoardTitle;
if ($prevSubCat != $row->SubCatTitle) {
echo '<tr style="background: rgba(149, 255, 145, 0.10)"><td colspan=""><b>' . $row->SubCatTitle . '</b></td></tr>';
}
$prevSubCat = $row->SubCatTitle;
// print product row
echo '<tr>';
echo "<td>{$row->BookTitle}</td>";
foreach ($locations as $location) {
$locationColName = preg_replace('[^a-z0-9]', '_', strtolower($location));
echo "<td>{$row->$locationColName}</td>";
}
echo "<td>{$row->Total}</td>";
echo '</tr>';
}
echo '<table>';
$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.