MyPHP and SQL creating a new table based on others - mysql

I have three tables; Table 1 (appointments) that contains the appointment start and end time in YYYY-MM-DD HH:MM:SS format, provider ID, Customer ID and Service ID.
Table 2 (users) contains both Provider and Customer IDs and First/Last names.
Table 3 (services) contains the service ID, service name, and service description.
I need to create a fourth table, called display, that will display the Provider name, Client name, Service name, and start and end times in HH:MM format.
I've tried googling joins, but I'm not seeming to get anywhere.
I'm using a simple script from w3schools, below:
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM ea_appointments INNER JOIN ea_services";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Start: " . $row["start_datetime"]. "End: " . $row["end_datetime"]. " - Provider: " . $row["id_users_provider"]. " - Customer: " . $row["id_users_customer"]. " - Service: " . $row["id_services"]."<br>";
}
} else {
echo "0 appointments";
}
$conn->close();
?>

In this case do not create a table because you just want to combine data from various tables. Just have a query or create a view.
In the query you need to tell mysql how to join your tables using the on clause. I'll show you how to join 2 tables, the rest is up to you:
SELECT *
FROM ea_appointments a
INNER JOIN ea_services s on a.serviceid=s.serviceid

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

SQL SELECT CASE with Where From Looping Value

I have 2 tables :
table names transaction and detail customer
transaction table fields are idtrans and idcust.
detail customer fields are idcust and custname.
i have Problem with my php syntax, i want select table with condition from value lopping, here's my code:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="select * from transaction";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sqlid="select * from detailcust where idcust='$row[idcust]')";
$resultid= $conn->query($sqlid);
if ($resultid->num_rows > 0){
while ($rowid= mysqli_fetch_array($resultid)){
$custname=$rowid["custname"];
echo $custname;
}
result name always first idcust value.
You seem to want the names of customer that have at least one transaction. If so, no need for loops and multiple queries. You can get the result you want with just one query:
select c.*
from detailcust c
where exists (select 1 from transaction t where t.idcust = c.idcust)

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 Multiple Simultaneous Queries From The Same Connection

I'm trying to run multiple queries on a MySQL server at the same time from PHP with the same database connection. I have run the SQL statement on the server itself but the response is as expected. I'm getting no SQL exceptions but just no SQL query response at all (the result is FALSE).
Is this because you can't query when another query is already active on the same connection?
The code loads data from the database table with people's names and last paid date information. This is displayed in a form and then the user can select members to update payments for. Then, the part I'm stuck on is the second query where the selected names are trying to find family_id for families.
Code snippet:
mysql_select_db($database_W3OITesting, $W3OITesting);
$yearnow = date("Y",strtotime('+1 year')).'-12-31';
$yearrecent = date("Y",strtotime('-1 year')).'-12-31';
$query_Recordset1 = "SELECT DISTINCT lname, fname, suffix, fcccall, members.member_id, MaxDateTime " .
"FROM members " .
"INNER JOIN " .
"(SELECT paid.member_id, MAX(paid.year) AS MaxDateTime " .
"FROM paid " .
"GROUP BY paid.member_id) groupedpaid ".
"ON members.member_id = groupedpaid.member_id " .
"Where (MaxDateTime < '$yearnow') AND ".
"(MaxDateTime >= '$yearrecent')" .
"ORDER BY lname, fname, suffix, fcccall";
$Recordset1 = mysql_query($query_Recordset1, $W3OITesting) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
//if a post is received handle it here
function getPostArray($array){
foreach ($array as $key => $value){
//search here for if this member is part of a family
//if not part of a family just update the payment
//record for the member with the value
try {
$query_Recordset3 = "SELECT lname, fname, suffix, `members`.member_id , `family`.member_id " .
"FROM members, family " .
"WHERE (`members`.member_id = `family`.member_id " .
"AND `members`.member_id = $key)";
echo $query_Recordset3. "<br>";
$Recordset3 = mysql_query($query_Recordset3, $W3OITesting);
$row_Recordset3 = mysql_fetch_assoc($Recordset3);
$totalRows_Recordset3 = mysql_num_rows($Recordset3);
echo $totalRows_Recordset3 . "<br>";
echo "$key => $value";
if($totalRows_Recordset3==FALSE) {//Recordset3 is always FALSE
echo " Error - " . $row_Recordset3['lname'];
}
if($totalRows_Recordset3!=0) {
echo " - A Family";
} else {
echo " - Individual";
}
echo "<br>";
}
catch(Exception $e)
{
echo "Exception: $e";
die();
}
if(is_array($value)){ //If $value is an array, get it also
getPostArray($value);
}
}
}

How to get variables from MSQL query with WHERE IN clause

I have a couple of MySQL tables where I run a query on like this:
$sql = "
SELECT my_item
FROM t1
, t2
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
AND t1.spec = t2.spec
";
Note I am using the WHERE IN.
Next I run a query and use WHILE to try to get the results:
$retval = mysql_query($sql) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem = $row['my_item'];
echo "My item is $myitem<br />\n";
}
This prints three results, each with a different value for $myitem, based on the three options from the IN clause in the SELECT statement at the beginning.
How can I extract and store each of these three values in a separate variable each?
Thank you!
use join
SELECT my_item FROM t1 join t2
on t1.spec=t2.spec
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
or create array
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem[] = $row['my_item'];
}
use this array likt that :-
foreach( $myitem as $myitems){
echo "My item is $myitems<br />\n";
}
or use indexing
echo "My item is $myitems[0]";
You can store the $row['my_item'] in an array.
Refer PHP arrays