SQL query for displaying teacher attendance - mysql

My teacher table is like:'
I have a teacher attendance table with data like as shown below:-
I'm trying to write codes which when executed will populate an excel file in the format given below. Where A= Absent, P= Present and, S= Sunday.
Logic for Present (P) : For any given date if ta_clock_in_tm & ta_clock_out_tm both are present then it's P.
Logic for Absent (A) : If no records exist for dates of the month in the teacher attendance table then it's A.
I also want to mark Sundays as S and calculate Total Present days and absent days.
I have not done anything like this before. I'm really confused about the sql query. Are both my tables enough to meet my requirement??
function export_to_mwiseallattenexcel($mnth)
{
$columnHeader ='';
$setData='';
$currYr = date("Y");
$noDaysInGvnMonth = cal_days_in_month(CAL_GREGORIAN, $mnth, $currYr);
$columnHeader = "Sl No"."\t"."Emp Name"."\t";
for($i=1; $i<=$noDaysInGvnMonth; $i++)
{
$columnHeader .= $i."\t";
}
$columnHeader .= "Total Working Days"."\t"."Total Absent"."\t"."Total Present"."\t"."Remarks"."\t";
$sql="";//<---WHAT TO WRITE HERE?????
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$rowData = '';
foreach($row as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData)."\n";
}
}
header("Content-Encoding: UTF-8");
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Attendance_as.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader)."\n".$setData."\n";
}
Please help me with the SQL query. Thanks.

Open a connection to your server. There you can query EVERY command you want:
The code is:
try {
$sql = new PDO('mysql: host=localhost:3306; dbname=dbname', 'user', 'pwd');
$sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = "do something";
$sql -> query($statement)
} catch(PDOException $e) {
echo 'Connection failed: (f) ' . $e->getMessage();
}
Some interesting commands are:
CREATE TABLE table (any datatypes); -> creates new table
INSERT INTO table () VALUES (value1),(value2); -> fills table with values
ALTER TABLE table CHANGE old_name new_bane datatype; -> change table
ALTER TABLE table DROP COLUMN user_id; -> drops a column from a database
DELETE FROM table WHERE condition; -> delete all values where condition is true
UPDATE table SET data=value WHERE condition; updates values inside a table where condition is true

Related

How to take values from one MySQl table, multiply them together, and put the results in another table

I have a table with 4 rows, I need to multiply col. 1 and 2 and put the results in col. 1 in the 2nd table. do the same with the other two cols' from table 1.
I'm sure its simple code. I just don't know MySQL
Get the values fetch the rows and insert again to the table 2:
$mysqli = new mysqli('127.0.0.1', 'tu_usuario', 'tu_contraseƱa', 'sakila');
if ($mysqli->connect_errno) {
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
$sql = "SELECT column1, column2 FROM table1";
if ($result = $mysqli->query($sql)) {
/* fetch object array */
while ($row = $result->fetch_row()){
$sql2 = "INSERT INTO table2 (col1) VALUES(".$row['column1']*$row['column2'].");";
$result = $mysqli->query($sql);
}
}
I didn't check if there is any error in theses code, it's just an example that shows the idea. I hope will be enough for you the explanation. If you still having doubts please answer again.

query to show selected options from multi select field in mysql

I am trying to get a query working that shows specific info from a mult-select-field that is part of a phpbb forum.
SELECT d.pf_firstname, d.pf_lastname, d.pf_specialism
FROM phpbb_profile_fields_data d
WHERE d.pf_lastname = 'Linssen'
The query above gives the following Result:
-- firstname: Pierre
-- lastname: Linssen
-- pf_specialism: 1;3;8;10;12;15;16 (which are the selected options)
In another table the relation between the available options (0 to 18)
and the related text is given.
result of a "wrong" query, showing all these options
The query I need should show: firstname and lastname of a user and only the specific options that that user (in this case: Linssen) has selected for a specific profile field (in this case: specialism).
So the result of the query should be something like
-- firstname: Pierre
-- lastname: Linssen
-- specialism: (1) Counseling ; (2) Executive Coaching ; (8) Oplossings gericht coachen; (10) Provocatief coachen ; (12) Sales coaching ; (15) Team coaching ; (16) Wandel coaching
How do I do that?
In order to support multi-language, profile fields values (TEXT) are stored in the _lang table, and the actual _data table only holds indexes to the lang table. So that you have, say, 3 stored in the data table, and then you map that to "Project Manager" in English or "Gestor de Proyectos" in Spanish...
2017-01-22: Thanks for input sofar still struggling to get the query to work.
Please find below the three tables with their relevant content.
phpbb_profile_lang has the following relevant fields
-- field_id (41)
-- lang_id (2)
-- lang_name (specialisme)
phpbb_profile_fields_data has the following relevant fields
-- user_id (90)
-- pf_voornaam (Pierre)
-- pf_achternaam (Linssen)
-- pf_specialisme (1;3;8;10;12;15;16)
phpbb_profile_fields_lang has the following relevant fields
-- field_id (41)
-- lang_id (2)
-- option_id (0) lang_value (Business Coaching)
-- option_id (1) lang_value (Counseling)
-- option_id (2) lang_value (Executive Coaching)
-- option_id (3) lang_value (Holistische Coaching)
-- ...............................................
-- ...............................................
-- option_id (17) lang_value (Zingeving)
-- option_id (18) lang_value (Overige)
Your query to join the tables would look like this:
select pf_voornaam, pf_lastname, lang_value
from phpbb_profile_fields_data pfd
inner join phpbb_profile_fields_lang pfl on pfl.feld_id = pfd.pf_specialisme
inner join phpbb_profile_lang pl on pfl.lang_id = pl.lang_id;
If you have control of the schema, I would strongly recommend to change phpbb_profile_lang.lang_id to be the primary key field_id and remove the lang_id - this is redundant based on the data you've shown.
Based on your example, I have used the following query:
select pf_voornaam, pf_achternaam, pf_specialisme, lang_value
from phpbb_profile_fields_data pfd
inner join phpbb_profile_fields_lang pfl on pfl.field_id = pfd.pf_specialisme
inner join phpbb_profile_lang pl on pfl.lang_id = pl.lang_id;
The result is shown in this image
With all the relevant input here and with help of "Javiexin", the following mysqli-based php-script with the various included mysql-queries did the trick. I am open to any suggestions to further improve the queries and script.
Here is a link to a result page.
<?php
/*Open connection to our database. */
$link = mysqli_connect("localhost", "perspec1", "FLeur0798!", "perspec1");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* check if server is alive */
if (mysqli_ping($link)) {
printf ("A: Our connection is OK!<br/><br/>");
} else {
printf ("Error: %s\n", mysqli_error($link));
}
/* First MYSQL query */
$sql = "SELECT d.pf_voornaam, d.pf_achternaam, d.pf_specialisme FROM phpbb_profile_fields_data d WHERE d.pf_achternaam = 'Linssen'";
if (!$sql) { echo "Error: ".mysqli_error(); die();
} else {
printf ("B: First query is successful!<br/><br/>");
}
if ($result = mysqli_query($link, $sql))
{
echo "<table>";
//header
echo "<tr><td>Voornaam</td>";
echo "<td>Achternaam</td>";
echo "<td>Specialisme</td></tr>";
//data
while ($row = mysqli_fetch_array($result))
{
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td></tr>";
}
echo "</table><br/>";
}
/* Second MYSQL query */
$query2 = mysqli_query($link, $sql );
if (!$query2) { echo "Error: ".mysqli_error(); die();
} else {
printf ("C: Second query is successful!<br/><br/>");
}
while( $row = mysqli_fetch_assoc($query2))
$selected_opts = explode (";", $row['pf_specialisme']);
foreach ($selected_opts as $selected_opt) echo "$selected_opt <br/>";
echo "<br/>";
$selected_opts_string = implode(', ', $selected_opts);
$sql3 = "SELECT fl.option_id, fl.lang_value FROM phpbb_profile_fields f, phpbb_profile_fields_lang fl WHERE f.field_id = fl.field_id AND f.field_name = 'specialisme' AND fl.lang_id = 1 AND fl.option_id IN ($selected_opts_string) ORDER BY fl.option_id ASC";
$query3 = mysqli_query($link, $sql3 );
if (!$sql3) { echo "Error: ".mysqli_error(); die();
} else {
printf ("D: Third query is successful!<br/><br/>");
}
if (!$query3) { echo "Error: ".mysqli_error(); die(); }
echo "<table>";
while( $result = mysqli_fetch_assoc($query3) )
{
echo "<tr><td>$result[option_id]</td>";
echo "<td>$result[lang_value]</td></tr>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($link);
?>

SQL QUERY SELECT INSIDE A FUNCTION

I am trying to work with a voting database system. I have a form to display all the candidates per candidate type. I'm still trying to to explore that. But this time, I want to try one candidate type, lets say for Chairperson, I want to display all candidate names for that type in the ballot form. However, there's an error with the line where i declare $query and made query statements, can somebody know what it is. I am very certain that my syntax is correct.
function returnAllFromTable($table) {
include 'connect.php';
$data = array ();
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1'; //ERROR
$mysql_query = mysql_query ( $query, $conn );
if (! $mysql_query) {
die ( 'Go Back<br>Unable to retrieve data from table ' . $table );
} else {
while ( $row = mysql_fetch_array ( $mysql_query ) ) {
$data [] = $row;
}
}
return $data;
}
As #Darwin von Corax says, I sure that you have a problem between $table and WHERE
Your query:
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1';
If $table = 'Chairperson';
You have:
'SELECT * FROM ChairpersonWHERE candidateId=1';
The your query should be:
$query = 'SELECT * FROM ' . $table. ' WHERE candidateId=1';

Load CSV values then search for matches in mysql database

I'm trying to build a script for a cron job that loads some values from a CSV file. This CSV file has 2 fields
product_id
price
The script will load the values from CSV, then it searches in mysql table for product_id matches. If found, it will update the price for that particular matched product_id in the table with the corresponding price in CSV.
I reached the below code so far but I got stuck at the part where I need to compare the array values from CSV with the array values from mysql.
<?php
// DB part
$con = mysqli_connect('localhost','user','pass','db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"products");
$sql="SELECT product_id, price, FROM products";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
// CSV part
$file_handle = fopen("prices.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$code = str_replace(' ', '', $line_of_text[0]); //
$price = str_replace(' ', '', $line_of_text[1]); //
if (in_array($code, str_replace(' ', '', $row)))
{
echo "Match found";
print $code . " - " . $price . "<br />";
}
else
{
echo "Match not found";
print $code . " - " . $price . "<br />";
}
}
fclose($file_handle);
mysqli_close($con);
?>
You're storing just the first line of your products table in $row. Then you are doing some hard-to-understand comparisons, but all of those comparisons compare just your first row.
Here's what I'd do:
// Untested Code Below, Not Suited For Production Use
// ...
// open the DB connection, open the file, etc.
// ...
// iterate over the complete CSV file
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$product_id = clean_product_id($line_of_text[0]);
$price = $line_of_text[1];
// for any entry in the CSV file check if there is more than one result
$sql="SELECT COUNT(*) FROM products WHERE product_id='$product_id'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
if( $row[0] == 1 ) {
// update the table price for the corresponding row (product), if there is just a single result for this $product_id
$sql="UPDATE products SET price = '$price' WHERE product_id='$product_id' LIMIT 1"; // in production code use mysqli_real_escape_string() on $price and $product_id!
$result = mysqli_query($con,$sql);
} else {
// if there are more results for this $product_id, add an error to your report.txt file
}
}

MySQL - updating the average from one table into another table

I'm a MYSQL/PHP newbie and I'm sure this is a simple question. I'm trying to calculate the average of several questions and respondents from one table and updating a Group table with that value.
For example Table answers consists of (name, group_id, TaskClarity1, TaskClarity2, TaskClarity3) in Table B i want (group_id, avg(TaskClarity1,TaskClarity2,TaskClarity3)).
This is what I've got...
$avg_task_clarity_1 = mysql_query("SELECT AVG(TaskClarity1) WHERE gruppid = '$group_id'");
$avg_task_clarity_2 = mysql_query("SELECT AVG(TaskClarity2) WHERE gruppid = '$group_id'");
$avg_task_clarity_3 = mysql_query("SELECT AVG(TaskClarity3) WHERE gruppid = '$group_id'");
$avg_task_clarity = ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
$print_task_clarity_1" UPDATE results SET results.TaskClarity = '$avg_task_clarity'";
if (mysql_query($print_task_clarity_1)) { echo $print_task_clarity_1; } else { echo "Error TaskClarity1: " . mysql_error();
First, mysql_query() returns a resource, and you then need to extract information from it. Your query doesn't mantion any table name (I'll call it MyTable).
Also, you can get all three averages with one query.
Here's how I would start:
$table = "MyTable";
$sql = "SELECT AVG(TaskClarity1) AS avgClarity1,
AVG(TaskClarity2) AS avgClarity2,
AVG(TaskClarity3) AS avgClarity1
FROM $table WHERE gruppid = '$group_id'";
$resource = mysql_query($sql); //execute the query
if (! $resource = mysql_query($sql) ){
echo "Error reading from table $table";
die;
}
if (! mysql_num_rows($resource ) ){
echo "No records found in $table";
}
else {
$row = mysql_fetch_assoc($resource); // fetch the first row
$avg_task_clarity_1 = $row['avgClarity1'];
$avg_task_clarity_2 = $row['avgClarity2'];
$avg_task_clarity_3 = $row['avgClarity3'];
$avg_task_clarity =
($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
//...
// other stuff you want to do
}
Please comment if this is not helpful enough, and I will revise my answer.