Gather a row of tableB from buttons row of table A - php

I am working in php and bootstrap with tables.
I have a tableA that for each row contains a button.
Each button has a value assigned equal to the row number. (see below)
$job_id = $row['id'];
<td> <a class='btn btn-primary btn-sm' data-toggle='modal' data-target='#myModal' name='job_id' value=$job_id id='job_id'>Info</a></td>
I cannot achieve this:
- Each button open a modal pop-up that contains the row of a tableB
So if I click on the button of the second row of tableA I want to show in the popup all the data that row2 of the tableB contains and so on.
Basically I cannot find out how to connect the button with a specific row of another table.
With this code in my modal I can only gather the entire tableB, but not the single row.
$sql = "SELECT * from tableb WHERE id=job_id ";
With this code in my modal I gather always the row 3 of tableB for all the buttons...
$sql = "SELECT * from tableb WHERE id=3 ";
With this code in my modal I gather for every button the last row I inserted
$sql = "SELECT * from tableb WHERE id='$job_id' ";
(TableA and TableB are connected with foreign key)
TableB has (id, job_id) with job_id= id of tableA
TableA has (id)
Any suggestion that can help me with what I want to achieve?
UPDATE 1 -> File xxx.php containts the script that load TableA and the script that load the Modal pop up
script that load TableA
<?php
include("../includes/connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
$sql = "SELECT * from TableA";
if (!$result = $link->query($sql)) {
die('There was an error running the query [' . $link->error . ']');
}
echo "
<table class='table'>
<thead>
<tr>";
/* Get field information for all columns */
...
while ($row = $result->fetch_assoc()) {
$job_id = $row['id'];
echo "<form action='' method=post>";
echo "<tr class='info'>
<input type=hidden name=hidden value=" . $row['id'] . ">
<td>" . $row['id'] . "</td>
<td>" . $row['device'] . "</td>
<td>" . $row['model'] . "</td>
<td>" . $row['problem'] . "</td>
<td> <a class='btn btn-primary btn-sm' data-toggle='modal' data-target='#myModal' name='job_id' value=[$job_id] > Info</a></td>
</tr>";
echo "</form>";
} echo " </tbody> </table>"; ?>
script that load the modal popup with tableB
<?php
include("../includes/connection.php");
if ($link->connect_errno > 0) {
die('Unable to connect to database [' . $link->connect_error . ']');
}
$sql = "SELECT * from TableB WHERE job_id=$job_id ";
if (!$result = $link->query($sql)) {
die('There was an error running the query [' . $link->error . ']');
}
echo "
<table class='table'>
<thead>
<tr>";
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
echo "
<th>" . $finfo->name . "</th>";
}
echo "
</tr>
</thead>
<tbody>";
while ($row = $result->fetch_assoc()) {
echo "<tr class='info'>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['mail'] . "</td>
<td>" . $row['number'] . "</td>
<td>" . $row['price'] . "</td>
<td>" . $row['paymenttype'] . "</td>
<td>" . $row['faktura'] . "</td>
<td>" . $row['date'] . "</td>
</tr>";}echo " </tbody></table>";?>

You can use JOIN instruction to link your two tables with one single request.
// For the third button the SQL request will be :
$sql="SELECT * FROM tableA A INNER JOIN tableb B ON B.job_id=A.id WHERE B.id=3";
// For the fourth button the SQL request will be :
$sql="SELECT * FROM tableA A INNER JOIN tableb B ON B.job_id=A.id WHERE B.id=4";
Note that here I use aliases on my request. For instance A is the alias of table A. Thus, A.id is the id column of tableA.
Look at this link for more infos about SQL Joins : http://www.w3schools.com/sql/sql_join.asp.

To get the rows in tableB corresponding to an id of tableA you should write:
$sql = "SELECT * from tableb WHERE job_id = $jobId ";
Note that I put 'WHERE job_id = ', and not 'WHERE id = '.
There's an answer that recommends a JOIN. With a JOIN you'll get the row in tableA and the data in tableB

Related

Group by with rollup does not change column name to TOTAL when using IFNULL or COALESCE

How do i replace column name 'product_name' to 'TOTAL' and other column name 'inv_date' to 'TOTAL'. Tried with as below but to no avail.
$query = "SELECT IFNULL(pm.product_name,'TOTAL') product_name,IFNULL(pt.inv_date,'TOTAL') inv_date, SUM(pt.qty) as total_qty,(SUM(pt.amount)/SUM(pt.qty)) as avg_rate, SUM(pt.amount) as total_amount1,SUM(pt.tcs) as total_tcs, SUM(pt.total_amount) as total_amount_net,
am.acc_name,pgm.product_group,psgm.sub_product_group,pim.pre_insp_name, ptm.purch_type_name, pt.* FROM purch_tble pt LEFT JOIN product_master pm ON pm.product_id = pt.product_id LEFT JOIN acc_master am ON am.acc_id = pt.acc_id LEFT JOIN purch_type_master
ptm ON ptm.purch_type_id = pt.purch_type_id LEFT JOIN prod_group_master pgm ON pgm.prod_group_id = pm.prod_group_id LEFT JOIN prod_sub_group_master psgm ON psgm.prod_sub_group_id = pm.prod_sub_group_id LEFT JOIN pre_insp_master pim ON pim.pre_insp_id
= pt.pre_insp_id $where GROUP BY pt.product_id, DATE_FORMAT(pt.inv_date,'%Y-%m') WITH ROLLUP"; $retval = mysql_query($query); $num_row = mysql_num_rows($retval); echo mysql_error(); if($num_row >= 1){ while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{ echo "
<tr>"; echo "
<td>" . date('m-Y',strtotime($row['inv_date']))."</td>"; echo "
<td>" . $row['product_name']."</td>"; echo "
<td>" . round($row['total_qty'])."</td>"; echo "
<td>" . round($row['avg_rate'],2)."</td>"; echo "
<td>" . round($row['total_tcs'])."</td>"; echo "
<td>" . round($row['total_amount1'])."</td>"; echo "
<td>" . round($row['total_amount_net'])."</td>"; echo "</tr>"; } // while loop finishes } // if statement finishes
I also tried with following but to no avail.
COALESCE(pm.product_name,'TOTAL') product_name,
COALESCE(pt.inv_date,'TOTAL') inv_date,
LASTLY, I also tried with following but to no avail.
IF(GROUPING(pm.product_name),'TOTAL',pm.product_name) product_name,
IF(GROUPING(pt.inv_date),'TOTAL',pt.inv_date) inv_date,
The picture is self explanatory.
I am stuck don't where am I going wrong.
Hope I have been able to express question clearly.

SUM function generates error in SQL query

I'm trying to get information about an SQL table via a php script however, whenever I add a SUM function I get the following error "Notice: Trying to get property 'num_rows' of non-object"
I don't know what's going on but if anyone can please explain/point me in the right direction as to how to fix this problem that would be greatly appreciated
Here's the 'broken' code
<?php
require("connect.php");
$inNo = $_POST["inNo"];
$sql = "SELECT invoice.invoice_no, invoice.date, invoice.cust_id, invoice.emp_id, invoice_line.prod_id,
invoice_line.qty, product.cost_price, (product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`, customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`, employee.last_name AS `emp_lname`,
product.name AS `proname`
FROM invoice INNER JOIN invoice_line ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product ON invoice_line.prod_id = product.id
INNER JOIN customer ON invoice.cust_id = customer.id
INNER JOIN employee ON invoice.emp_id = employee.id, SUM(multi) AS `invoicetotal`
WHERE cust_id = '" . $inNo . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//open table
echo '<table class="table table-striped" id="outTable">';
echo "<tr><th>Product</th><th>Qty</th><th>Price</th><th>Total cost</th></tr>";
// output data of each row
$ctr = 0;
while($row = $result->fetch_assoc()) {
if ($ctr == 0)
{
echo "<h1>Invoice Number: " . $row["invoice_no"]. "</h1>";
echo "<p>Customer: " . $row["customer_fname"]. " " . $row["customer_lname"]."</p>";
echo "<p>Employee: " . $row["emp_fname"]. " " . $row["emp_lname"]. "</p>";
echo "<p>Date: " . $row["date"]. "</p>";
}
echo "
<tr>
<td>" . $row["proname"]. "</td>
<td>" . $row["qty"]. "</td>
<td>" . $row["cost_price"]. "</td>
<td>" . $row["multi"]. "</td>
</tr>";
$ctr++;
}
} else {
echo "0 results";
}
$conn->close();
?>
You need to insert the SUM() in the SELECT part above FROM:
SELECT
invoice.invoice_no,
invoice.date,
invoice.cust_id,
invoice.emp_id,
invoice_line.prod_id,
invoice_line.qty,
product.cost_price,
(product.cost_price * invoice_line.qty) AS `multi`,
customer.first_name AS `customer_fname`,
customer.last_name AS `customer_lname`,
employee.first_name AS `emp_fname`,
employee.last_name AS `emp_lname`,
product.name AS `proname`,
SUM(multi) AS `invoicetotal`
FROM invoice
INNER JOIN invoice_line
ON invoice.invoice_no = invoice_line.invoice_no
INNER JOIN product
ON invoice_line.prod_id = product.id
INNER JOIN customer
ON invoice.cust_id = customer.id
INNER JOIN employee
ON invoice.emp_id = employee.id` WHERE cust_id = 99
BTW, it's wise to format code - SQL code too - fine.

Trouble with Queries and JOINS

The main page I am using is called the Project Details Page which when you select a project number on the form will query the subform for any records pertaining to that project number and display them in this page named the (TasksSubform).
This page called (TasksSubform) uses a php file called mysqli_connect.php to obtain a database connection and assigns that connection to $dbc in the mysqli_connect.php file.
This page then query’s table 1 named 'CommonTasks', and starts displaying the data row by row in a table on the page using
while($row = $result->fetch_assoc())
Currently one of the columns in the record being displayed is named “AssignedTo” which produces the unique ID number in the Employees table instead of the text value of the employees name associated with the ID number. So, I need to be able to list the records in the CommonTasks Table using Fetch then, when it tries to display the value in the “AssignedTo” column within the Common Tasks Table, it must lookup the ID in the Employees table which equals the same value in the Common Tasks Table, and replace the number value of the Assigned To Field with the text value in the Employees table.
COMMONTASKS
EMPLOYEES
* Add
* AssignedTo
* Attachments
* Cost
* CostInDays
* Description
* DueDate
* EmployeeID
* ID
* PercentComplete
* Priority
* StartDate
* SubmissionDate
* Title * ID
* Address
* BusinessPhone
* City
* Company
* CountryRegion
* EmailAddress
* FaxNumber
* FirstName
* HomePhone
* JobTitle
* LastName
* MobilePhone
* Notes
* StateProvince
* WebPage
* ZIPPostal Code
This is what I have. Yet, all it is producing is a blank in the Assigned To field on the php page.
enter image description here
I am a novice to php and mysql.
This is probably something simple which I am overlooking.
Yet, I have been troubleshooting various methods for the past few days, and just cant seem to figure out what I am doing wrong.
<?php
// Get a connection for the database
require_once('../mysqli_connect.php');
// Create a query for the database
$sql = "SELECT * FROM `CommonTasks`";
$employee = "SELECT ID, LastName, LastName FROM Employees JOIN CommonTasks ON Employees.ID=CommonTasks.AssignedTo";
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = CommonTasks.AssignedTo LIMIT 1";
$emp1 = "SELECT id as LastName, FirstName FROM Employees WHERE ID = CommonTasks.AssignedTo LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$result1 = #mysqli_query($dbc, $sql);
$result2 = #mysqli_query($dbc, $emp);
$result = $dbc->query($sql);
$link = "commntasks-insertdata.php"
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Common Tasks-subform</title>
<meta name="viewport"charset="utf-8" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
echo " <table border='1' #6a8fba>
<caption>SUBFORM - Common Tasks</caption>
<tr>
<th>Job Title</th>
<th>Due Date</th>
<th>Start Date</th>
<th>Cost</th>
<th>Priority</th>
<th>Percent Complete</th>
<th>Assigned To</th>
<th>Description</th>
</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
echo "<td>". $row ['SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = $_GET[AssignedTo] LIMIT 1'] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
}
echo "</table>";
?>
</body>
Currently, the results are being produced by this line
$result = $dbc->query($sql);
The following line will not execute a mysql query.
echo "<td>". $row ['SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = $_GET[AssignedTo] LIMIT 1'] . "</td>";
As written, you are trying to find a row value in $result that does not exist. You need to call the second query within the first while loop and pass the value of $_GET[AssignedTo] which is probably $row[AssignedTo]
Something like this
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = '$row[AssignedTo]' LIMIT 1";
$result2 = #mysqli_query($dbc, $emp);
$row2 = $result2->fetch_assoc();
echo "<td>". $row2 ['Firstname'] . " ". $row2 ['Lastname'] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
So, Here are my revisions to your example:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td><a href= $link > $row[Title] </a></td>";
echo "<td>". $row['DueDate'] . "</td>";
echo "<td>". $row['StartDate'] . "</td> " ;
echo "<td>". $row['Cost'] . "</td>";
echo "<td>". $row['Priority'] . "</td>";
echo "<td>". $row['PercentComplete'] . "</td> " ;
$emp = "SELECT LastName, FirstName FROM Employees JOIN CommonTasks WHERE Employees.ID = '$row[AssignedTo]'";
$result2 = #mysqli_query($dbc, $emp);
$row2 = $result2->fetch_assoc();
echo "<td>". $row2['LastName']," , ",$row2[FirstName] . "</td>";
echo "<td>". $row['Description'] . "</td> " ;
echo "</tr>";
}
}
echo "</table>";
?>
Which produces this: Results of modified code
Thank you so much for your Help!
Since I am converting an Access Database to mySQL and recreating all of the queries, forms, and reports.... I am sure I will have an overwhelming amount of questions in the near future.
Eric

Database Retrieval with php

I'm creating a page where it gets contact details from the forum on registered members. I've hit a little problem trying to retrieve the custom fields. For University and flights a drop down menu is used so that users can select from a specific list. However the forum uses 3 different table to store the data.
This is a small part of the tables
db mock up http://www.emuas.co.uk/images/db_mock_up.png
at the moment I get the uni for the uni query and a flight for the flight query, but the result is unrelated to the user_id. Not sure how to change that though.
$user = "SELECT *
FROM profile_fields_data
JOIN users
ON profile_fields_data.user_id = users.user_id
ORDER BY users.username";
$uni = "SELECT *
FROM profile_fields_data
JOIN users
ON profile_fields_data.user_id = users.user_id
JOIN profile_fields_lang
ON profile_fields_data.pf_university = profile_fields_lang.option_id
WHERE field_id =4
ORDER BY users.username";
$flight = "SELECT *
FROM profile_fields_data
JOIN users
ON profile_fields_data.user_id = users.user_id
JOIN profile_fields_lang
ON profile_fields_data.pf_flight = profile_fields_lang.option_id
WHERE field_id =3
ORDER BY users.username";
$userdata = $db->sql_query($user);
$unidata = $db->sql_query($uni);
$flightdata = $db->sql_query($flight);
while($data = $db->sql_fetchrow($userdata))
{
$datauni = $db->sql_fetchrow($unidata);
$dataflight = $db->sql_fetchrow($flightdata);
echo "<tr>
<td> <a href='http://emuas.co.uk/forum/memberlist.php?mode=viewprofile&u=" . $data['user_id'] . "'>" . $data['username'] . "</a></td>
<td> <a href='mailto:" . $data['user_email'] . "'>" . $data['user_email'] . "</a> </td>
<td>" . $data['pf_contact_number'] . "</td>
<td>" . $data['user_birthday'] . "</td>
<td>" . $data['pf_service_number'] . "</td>
<td>" . $datauni['lang_value'] . "</td>
<td>" . $dataflight['lang_value'] . "</td>
<td>" . $data['pf_secondary_duty'] . "</td>
</tr>";
Many thanks
Found the problem. When the forum got the data for option_id it added 1 to the value. I;ve changed it to take this into account

php mysql select from columns from 2 tables Join

I have two tables.
visitors_details, with id,scanner_id,time columns
and visitors_info with scanner_id, name,surname columns
I want to get back
id,name,surname,time in a table
i have written this but is not working
$result = mysql_query("SELECT visitors_details.id AS id,
visitors_info.name AS name, visitors_info.surname AS surname, visitors_details.time
AS time FROM visitors_details AS d LEFT JOIN visitors_info AS i ON
d.scanner_id=i.scanner_id ");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>Time</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "</tr>";
}
echo "</table>";
any ideas??
Its better to enable some debugging for your code like this:
<?php
error_reporting(E_ALL);
$sql = "
SELECT d.id AS id, i.name AS name, i.surname AS surname, d.time AS time
FROM visitors_details AS d
LEFT JOIN visitors_info AS i ON d.scanner_id=i.scanner_id
";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
try this query
$result = mysql_query("SELECT d.id , i.name , i.surname , d.time
FROM visitors_details AS d LEFT JOIN visitors_info AS i
ON d.scanner_id=i.scanner_id ");
Add this to catch errors. saves a lot of time:
if(!$result) {
echo mysql_error();
}

Categories