Matching id's from two database tables to get username from one - php

I am wanting to match my user_id column from my announcements table to the id column in my users table. I then want to get the username from the users table where the id's match.
I initially had the following query
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements"))
I am getting the following error with my current code..
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in
Which I know what this means, but do I need to add in every column table from my users table for this to work or is there another way to do this? If I do need to add all of the columns as variables in my bind_result, does it matter which order I put them in? Announcements first or users or vise versa?
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id,
$announcements_user_id, $announcements_messages, $announcements_date);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
update..
if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.messages, announcements.date, users.username FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id,
$announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}

The warning indicates when you are binding the result fields into variables, the number of variables does not match the number of fields in the result set:
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
The easy way around this is to always specify the fields in the SELECT statement (just an example):
SELECT t1.id, t1.user_id, t1.messages, t1.date, t2.username
Instead of:
SELECT *

Related

Fetch data that don't exist in a table with a specific id from another table

I'm new to MySQL and PHP and I need your help.
I have made a web application for the check-ins that employees make at the company.
I have an SQL table named tblemployees that has the employees' emp_id, Name, Email ID etc.
The other table is named tblentries and has all the entries of each employee and variables such as id. emp_id, Name, Date, Hour etc.
The primary key of tblemployees is emp_id and emp_id is the foreign key of the tblentries table.
I want to make a table in my web app that shows the pending checks of the day.
To be more specific, my code so far is:
<div class = "pb-20" id = "tab">
<table class = "data-table table stripe hover nowrap">
<thead>
<tr>
<th class = "table-plus">Full Name</th>
<th>Email</th>
<th>1st Comp.</th>
<th>2nd</th>
<th>3rd</th>
<th>4th</th>
<th>5th</th>
<th>Department</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$sql = "SELECT tblemployees.Name, tblemployees.EmailId, tblemployees.Company1, tblemployees.Company2, tblemployees.Company3, tblemployees.Company4, tblemployees.Company5, tblemployees.Department, tblemployees.role FROM tblemployees LEFT JOIN tblentries ON tblentries.Date < '$todaysdate'";
$query = mysqli_query($conn, $sql) or die(mysqli_error());
while ($row = mysqli_fetch_array($query)) {
?>
<td class = "table-plus">
<div class = "name-avatar d-flex align-items-center">
<div class = "txt">
<div class = "weight-600"><?php echo $row['Name']; ?></div>
</div>
</div>
</td>
<td><?php echo $row['EmailId']; ?></td>
<td><?php echo $row['Company1']; ?></td>
<td><?php echo $row['Company2']; ?></td>
<td><?php echo $row['Company3']; ?></td>
<td><?php echo $row['Company4']; ?></td>
<td><?php echo $row['Company5']; ?></td>
<td><?php echo $row['Department']; ?></td>
<td><?php echo $row['role']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
*'$todaysdate' is a variable that stores today's date. It has the same format as tblentries.Date.
Whatever I have tried so far I haven't managed to show the right results.
I have made some entries for testing the app and the table that I want to make shows the names of the employees whose entries I have made for testing. (The test entries have made in the past, so their dates are smaller than $todaysdate.
I don't know which is better to use and how Not In, Not Exists or a Left Join?
Thank you :)
Found the solution. I used WHERE NOT EXISTS(), so as to fetch the names etc of those who belong to tblemployees table and do not have an entry for CURATE() in tblentries table :
$sql = "SELECT DISTINCT tblemployees.Name, tblemployees.EmailId, tblemployees.Company1, tblemployees.Company2, tblemployees.Company3, tblemployees.Company4, tblemployees.Company5, tblemployees.Department, tblemployees.role
FROM tblemployees
WHERE NOT EXISTS ( SELECT DISTINCT tblentries.emp_id, tblentries.Date FROM tblentries WHERE tblentries.emp_id = tblemployees.emp_id AND tblentries.Date = '$todaysdate')";

Creating arrays from columns in database that I can echo in html

Im sorry if this has been answered before but I am new to PHP and MySQL and I can't figure this out.
Pretty much every time I alter my code to include an array I get a fatal error. What I am trying to do is display all the data in 3 columns from my table.
I have my site set up where you log in and I store that user's name as a "code" in a session. I have a table that has multiple user form entries that are differentiated by the user's code because in my form, I grab the code as a hidden field and add it to the entry in the table.
So far I have been able to isolate those entries by the users code, in one column I have the sum of all of the user's numerical data and I am able to echo this as a total.
I want the other 3 columns to display all the values in their columns and for each value have a line break in between them. And I am trying to print or echo these results in specific parts on a confirmation page.
I have seen examples with PDO using fetch_all and other examples of storing arrays but I can't seem to figure it out with my existing code.
Here is my existing code:
<?php
$user = *****;
$pass = *****;
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
$stmt = $dbh->prepare("SELECT sum(price),part_number,location,price FROM products WHERE code = :usercode");
$stmt->bindParam(':usercode', $_SESSION['MM_Username']);
if ($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
And here is where I want to display the results:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
</tbody>
</table>
Try like this:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><? echo $user['part_number']; ?></td><!--all column values-->
<td><? echo $user['location']; ?></td><!--all column values-->
<td><? echo $user['price']; ?></td><!--all column values-->
<td><? echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
There are a few things in your question that jumped out at me.
It looks like you're attempting to display both raw data (each row) and aggregate data (the sum of prices). It can be simpler to fetch the information separately instead of in the same request.
You had mentioned fetch_all in PDO, but the method is fetchAll.
Instead of working with PDO within the HTML (like iterating through while calling fetch), write code so that you're simply iterating over an array.
Based on your description of the problem, it sounds like you want to separate the total price from the raw data, so you can reduce your table down to three columns and use the table footer to show the total price.
Based on those, I have the following solution that
Separates the calls to get data into descriptive functions
Use money_format to better display prices
Removes any database-specific manipulation from the view itself.
<?php
function getTotalPriceForUser(PDO $database_handler, $user_code)
{
// If no rows are returned, COALESCE is used so that we can specify a default
// value. In this particular case, if there aren't any products that would
// match, we'd still get a result with a value of 0.
$sql = 'SELECT COALESCE(SUM(price), 0) FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// This fetches the first row of the result; the result is given as an array with numerical keys.
$result = $stmt->fetch(PDO::FETCH_NUM);
// [0] refers to the first column
return $result[0];
}
function getProductsForUser(PDO $database_handler, $user_code)
{
$sql = 'SELECT part_number, location, price FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// fetchAll returns all rows, with each row being an associative array (where part_number, location and price are the keys)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Set up the database information
$user = '*****';
$pass = '*****';
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
// money_format to use the below money formatting; this makes sure there's a dollar sign to represent USD, for example
setlocale(LC_MONETARY, 'en_US.UTF-8');
// Store $_SESSION['MM_Username'] in a local variable
$user_code = $_SESSION['MM_Username'];
// Get the list of products associated with this user code
$products = getProductsForUser($dbh, $user_code);
// Get the total cost of the products
$total_cost = getTotalPriceForUser($dbh, $user_code);
?>
<table style="margin:0 auto;" cellspacing="7" width="100%">
<thead>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<td style="text-align: right" colspan="2">Total:</td>
<td style="text-align: right; border-top: 1px solid #999"><?= money_format('%.2n', $total_cost) ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?= $product['part_number'] ?></td>
<td><?= $product['location'] ?></td>
<td style="text-align: right"><?= money_format('%.2n', $product['price']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Change to this
<? echo
to
<?php echo
Try this:
...
$keys = array_keys($user);
foreach ($keys as $k) :
?>
<td><?= $user[$k]?></td>
<?php endforeach?>
<table>
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>

retrieving information from two tables

I have a table called incidents, that i'd like to retrieve 4 fields/columns from, but i need firstname and lastname from the customer table. I keep getting the following error:
Warning: Invalid argument supplied for foreach()
This is the relevant code:
public static function get_incidents_unassigned(){
$db = Database::getDB();
$query = 'SELECT concat(customer.firstName,customer.lastName) AS name, incident.productCode, incident.dateOpened, incident.title, incident.description FROM incidents
INNER JOIN customers
ON incident.customerID = customer.customerID
WHERE techID IS NULL';
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetch();
$incidentList = array();
foreach ($rows as $row){
$incidents = new Incident(
$row['name'], $row['productCode'],
$row['dateOpened'], $row['title'], $row['description']);
$incidentList[] = $incident;
}
$statement->closeCursor();
return $incidentList;
}
******but this is the involved table
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Date Opened</th>
<th>Title</th>
<th>Description</th>
<th> </th>
</tr>
<?php foreach ($incidents as $incident) :
$ts = strtotime($incident->getDate_Opened());
$date_opened_formatted = date('n/j/Y', $ts);
?>
<tr>
<td><?php echo htmlspecialchars($customer->getFullName()); ?></td>
<td><?php echo htmlspecialchars($incident->getProduct_Code()); ?></td>
<td><?php echo htmlspecialchars($incident->getTitle()); ?></td>
<td><?php echo htmlspecialchars($incident->getDescription()); ?></td>
<td><?php echo $date_opened_formatted; ?></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="select_incident">
<input type="hidden" name="product_code"
value="<?php echo htmlspecialchars($incident->getIncident_id()); ?>">
<input type="submit" value="Select">
</form></td>
</tr>
<?php endforeach; ?>
</table>
//****may have been looking at too long!
You should add some error handling to your code. The db could tell you that incident is not defined. The data is selected from incidents but incident is used to identify the fields.
I mean try changing your statement to match your circumstances
$query = 'SELECT concat(customer.firstName,customer.lastName) AS name,
inc.productCode, inc.dateOpened, inc.title,
inc.description FROM incidents inc
INNER JOIN customers
ON inc.customerID = customer.customerID
WHERE techID IS NULL';
Your database is able to give you error messages. These error messages describe what is your problem with your statement

PHP INSERT It Show only one

<table border="1" width="500">
<tbody>
<tr>
<th>ProFileID</th>
<th>CogID</th>
<th>FileValue</th>
<th> Count </th>
<?php
$sql="Select * From idtable"; // Read idtable
$result=mysql_query($sql); // Query sql
$num=mysql_num_rows($result); // Check record
if($num>0){ // If record > 0
$count=1; //
while($recordset=mysql_fetch_assoc($result)){ // loop
?>
<tr>
<td align="center"><?php echo $count; ?></td>
<td><?php echo $cogid = $recordset['CogID']; ?></td>
<td><?php echo $FileValue = $recordset['FileValue']; ?></td>
<td><? $url = "https://s3-ap-southeast-1.amazonaws.com/cloudpoc2/".$cogid."/Contacts/contactsversion3/".$FileValue."";
//example "https://s3-ap-southeast-1.amazonaws.com/cloudpoc2/us-east-1%3Ab9b09e99-5921-494a-b5a7-54f289131eaa/Contacts/contactsversion3/Contacts_1437450598237.txt";
$getText = file_get_contents("$url", true);
$Contact = substr_count($getText ,"FIRSTNAME");
echo $countupdate = $Contact; ?>
</tr>
<?
$count+=1; // Increase count +1
}
}
?>
</tbody>
<?php // UPDATE TO DATABASE
$updatecount = "INSERT INTO counttable (ProfileID,Count,Timestamp)
VALUES('','$countupdate','')";
mysql_query($updatecount);
?>
**I want to update count to phpmyadmin Table name is Countable I have 2 data but it show only one data i don't know what happen ** Some on kind please help me
This my pic
You do an update after while loop is over. After loop is over $updatecount stores the last value of $Contact. If you want to update table on each iteration of while loop, move your update query in the loop:
while($recordset=mysql_fetch_assoc($result)) { // loop
// do something here
$updatecount = "INSERT INTO counttable (ProfileID,Count,Timestamp) VALUES('','$countupdate','')";
mysql_query($updatecount);
}

Null results for a specific column - php/mysql

My query returns the correct data when executed on the db, but when run live the company_title comes back null. All other fields work.
$row['company_name'] is the code i can't get to work:
$query = "select * from invoices i, company_lookup cl, students s where i.company_id = cl.company_id and i.student_id = s.student_id;";
$results = $DB->query($query);
$invoices = mysql_query("select * from invoices");
?>
<table border="1" id="hl" name="hl">
<tr>
<th>Month/Year</th>
<th>Full Amount</th>
<th>Company</th>
</tr>
<?php while ($row = mysql_fetch_array($invoices)) {
$invoice_date = $row['invoice_date'];
?>
<tr onMouseOver="showInvoicePayments(<? echo $row['invoice_id'] ?>);this.bgColor = '#C0C0C0'" onMouseOut ="this.bgColor = '#FFFFFF'" bgcolor="#FFFFFF">
<td><? echo date('F Y',strtotime($invoice_date)) ?></td>
<td><? echo '$' . $row['full_amount'] ?></td>
<td><? echo $row['company_name'] ?></td>
</tr>
<?
}
?>
try adding COALESCE in some of your fields.
like this one:
SELECT ..., COALESCE(company_title, ''),
COALESCE(company_name, '')
...
Instead of null value, it will return an empty string.

Categories