query to show selected options from multi select field in mysql - 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);
?>

Related

SQL query for displaying teacher attendance

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

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.

MYSQL Query fail to select possible result

I want to get all emp_ids of employees which is manager_id equal to login user_id. But why this query show only first result of the column. I could not able to find the problem.
$userID=$_SESSION['userID'];
var_dump($userID);
$result1 = mysql_query("SELECT emp_id FROM employee where manager_id='$userID' ORDER BY emp_id");
$array = mysql_fetch_array($result1);
$id1=$array['emp_id'];
Please help !
You should loop over the result
and eg: you can store all the empID in an array
$cnt = 0;
while ($row = mysql_fetch_array($result1)) {
echo "ID: " . $row[0] ;
$myArrayOfEmpID[$cnt] = $row[0];
$cnt++;
}
instead you only set
$array = mysql_fetch_array($result1);
$id1=$array['emp_id'];

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.

Check whether value exist in database

What's the best way to check whether the value is in the database?
Am I doing it correct?
$result = mysql_query("SELECT COUNT(*) FROM table WHERE name = 'John'");
$count = count($result);
you could use straight forward ,
mysql_num_rows() ;
eg :
$con = mysql_connect($host,$uname,$passwd)
mysql_select_db($dbase,$con);
$result = mysql_query($query,$con);// query : SELECT * FROM table WHERE name='jhon';
if( ! mysql_num_rows($result)) {
echo " Sorry no such value ";
}
Yes you are doing it right, if you are only concerned with checking if there are any records where name='john'
SELECT COUNT(*) FROM table WHERE name = 'John'
will return the no. of records where name field is 'John'. if there are no records then it will return 0, and if there are any records it will return the number of records.
But the above query will miss the entries where name is 'John Abraham' or 'V john', to include even these
you can modify your query like this.
SELECT COUNT(*) FROM table WHERE name like '%John%'
I'd say yes.
$result = mysql_query("SELECT COUNT(*) AS 'nb' FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['nb'];
Will give you the number of matching rows.
$result = mysql_query("SELECT COUNT(*) as user FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['user'];
if($count!=0)
{
echo "user exists";
}
else
{
echo "There is no such user";
}