How do I get a the pending status to automatically show up? - php

I have this leave form where employees can apply for a leave. Everything works fine, the only problem is I can't get the pending status to show up. I've already defined the default value of status on my table.
Here's what it looks like when I view the leaves:
view-leave
and here's my table structure:
Table Structure
I'm not sure if you guys need my view-leave code but here it is:
<div class="table-responsive">
<table class="table">
<tr>
<th>Employee Name</th>
<th>Phone</th>
<th>Email</th>
<th>From</th>
<th>To</th>
<th>Reason</th>
<th>Status</th>
</tr>
<?php
include ('database.php');
$result = $database->prepare ("SELECT * FROM leaves order by id DESC");
$result ->execute();
for ($count=0; $row_message = $result ->fetch(); $count++){
?>
<tr>
<td><?php echo $row_message['full_name']; ?></td>
<td><?php echo $row_message['phone']; ?></td>
<td><?php echo $row_message['email']; ?></td>
<td><?php echo $row_message['fromdate']; ?></td>
<td><?php echo $row_message['todate']; ?></td>
<td><?php echo $row_message['reason']; ?></td>
<td><?php echo $row_message['status']; ?></td>
</tr>
<?php } ?>
</table>
<button type="button" class="btn btn-primary"><i class="glyphicon glyphicon-arrow-left"></i> Back</button>
</div>
</div>

The DEFAULT key word determines behaviour during an INSERT, not during a SELECT. Whatever values are in the table are what you will see, regardless of what the current DEFAULT is.
If you want something similar to a default during a SELECT, try the following...
SELECT
id,
full_name,
phone,
email,
fromdate,
todate,
reason,
COALESCE(status, 'Pending') AS status
FROM
leaves
ORDER BY
id DESC
This will replace all NULL values in status with 'Pending' while you are selecting the data. It won't change anything in the table, just in your results.
If you want to change what is in the table to get rid of those "blank" values, the you need to do an UPDATE.
UPDATE
leaves
SET
status = 'Pending'
WHERE
status IS NULL
OR status = ''
If you want to stop blanks values getting in to the table in the future, you need to specifically mention all the fields except for the the ones that you want to have a default applied.
INSERT INTO
leaves (
full_name,
phone,
email,
fromdate,
todate,
reason
)
VALUES (
'Joe Bloggs',
'555 555 555',
'joe#bloggs.com',
'2017-04-01',
'2018-12-25',
'Just Because'
)
That list of field names at the start is critical.
If you skip it, you're telling the database you want to set the values for every column, and so you never want the default used. The same is true if you include status in the list : Even if you give the value NULL or '', you're telling the database that's the value you want, regardless of what the default might be.

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>

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

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 *

jquery how to get value in a table

I have the following code that generates a table:
<table class="table table-bordered table-striped" id="assignedvs">
<thead>
<tr>
<th>VlId</th>
<th>Name</th>
<th>Status</th>
<th>Voice</th>
<th>Jumbo</th>
<th>Mode</th>
</tr>
</thead>
<tbody>
<?php foreach ($vln as $vlndetail): ?>
<tr>
<td id='vlid'><?php echo $vlndetail['VlId'] ?></td>
<td><?php echo $vlndetail['Name'] ?></td>
<td><?php echo $vlndetail['Status'] ?></td>
<td><?php echo $vlndetail['Voice'] ?></td>
<td><?php echo $vlndetail['Jumbo'] ?></td>
<td><?php echo $vlandetail['Mode'] ?></td>
</tr>
<?php endforeach ?>
I need to find the row where the VlId matches what the user has specified in a text box. Once I've found this record, I want to grab value in the mode column for the particular row.
here's what i've written so far:
$('#delete').live('click', function() {
//get a count of all records. only allowed to delete if you have more than one + the header.
var reccount = $('#assignedvs tr').length;
if (reccount > 2)
{
//loop through the table
$('#assignedvs tr').each(function() {
var temp = $(this).find(".vlid").html();
console.log(temp);
if (temp == $('#uservalue').val){
//grab mode column
}
});
}
else
{
alert("error: must have at least 1 record.");
}
});
problem - the code i have to reference the vlid column is incorrect. it always prints a null to the console.
Can you tell me what I've done wrong?
thanks.
EDIT 1
I changed my id to a class and changed my jquery back to the original code I had. it's working - except for the fact that I think it's including the header . I have 4 rows + header. When i check the console results, the first print out is always NULL and then the correct value for the 4 records. how do it get it to ignore the header?
That's because you are finding by className, not by id. To find by id, use the following instead:
$(this).find("#vlid").html();
However, since ids should be unique across the entire document, a better solution would be to maintain your current code, and instead of using <td id='vlid'>, use <td class='vlid'>.
Also note that val() is a function. Thus, to get the value of a given input, you should use $('#uservalue').val().
EDIT: To exclude the header, use the $('#assignedvs tbody tr') selector. This way, you only get rows that are descendants of tbody, thus ignoring the header rows, which descend from thead.
couple of changes:
<?php echo $vlndetail['VlId']; //missing semi-colon ?>
var temp = $(this).find("#vlid").html(); vlid is an id
You can easily do this via datatables at http://datatables.net
var temp = $(this).find("#vlid").html(); // .vlid (by class) changed to #vlid (by id)
An even easier solution.
Assign an ID to each row with the vlId (possibly prepend tr_ to the ID to avoid duplication).
Assign a class with the column name to each datacell.
Like so:
<?php foreach ($vln as $vlndetail): ?>
<tr id='tr_<?php echo $vlndetail['VlId'] // set the ID ?>'>
<td class='vlid'><?php echo $vlndetail['VlId'] ?></td>
<td class='Name'><?php echo $vlndetail['Name'] ?></td>
<td class='Status'><?php echo $vlndetail['Status'] ?></td>
<td class='Voice'><?php echo $vlndetail['Voice'] ?></td>
<td class='Jumbo'><?php echo $vlndetail['Jumbo'] ?></td>
<td class='Mode'><?php echo $vlandetail['Mode'] ?></td>
</tr>
<?php endforeach ?>
Then to get the Name of the selected vlID just do this JQUERY:
var rowID = "#tr_" + $('#uservalue').val(); // this is optional. I prefer to cache values for increased code readability.
$(rowID + " td.Mode").dostuffhere(); // this selector returns the Mode cell for the row indicated by the user
This will grab the Mode column of that specific row.

Insert/Update Multiple Rows in MySQL with PHP and Jquery

I have a table that is populated by a MS Sql query from one database that gives me values from patient visits and the revenue generated from those visits. I have a checkbox that populates the corresponding text input box showing that visit was paid for. My question is how can I add/update multiple rows using MySQL and PHP. There are two different databases (MySQL and MS SQL).
The HTML table.
<table>
<thead>
<tr>
<th>First Name / Last Name</th>
<th>Alias</th>
<th>Status</th>
<th class="amountDue">$00,000.00</th>
<th colspan="2" class="appliedAmount">$00,000.00<?th>
<th class="variance">$00,000.00</th>
<th>Complete</th>
</tr>
<tr>
<td><td>
<td><td>
<td><?php echo $patRow['VisitNum']; ?></td>
<td><?php echo $patRow['VisitName']; ?></td>
<td><?php echo $patRow['AmountDue']; ?></td>
<td><input type="checkbox"></td>
<td><input type="text" name="Amount[]"></td>
<!-- Invoice Populated from Database --!>
<td><select class="invoiceNumber">
<option>4565</option>
</select>
</tr>
</tr>
</table>
Now the PHP.
<?php
require('../assets/dbconnect.php');
$size_array = count($_POST['Amount']);
for ($i=0; $i<$size_array; $i++){
$query = 'INSERT INTO webportal.test (id, PSID, SysPatVisitID, AmountDue, Amount, InvoiceNum)'.
" VALUES ('', '".mysql_real_escape_string($_POST['PSID'][$i])."',
'".mysql_real_escape_string($_POST['SysPatVisitID'][$i])."'',
'".mysql_real_escape_string($_POST['AmountDue'][$i])."'',
'".mysql_real_escape_string($_POST['Amount'][$i])."'',
'".mysql_real_escape_string($_POST['InvoiceNum'][$i])."')
ON DUPLICATE KEY UPDATE content=VALUES(
'".mysql_real_escape_string($_POST['AmountDue'][$i])."'',
'".mysql_real_escape_string($_POST['Amount'][$i])."'',
'".mysql_real_escape_string($_POST['InvoiceNum'][$i])."''
";
$result = mysql_query($query) or die (mysql_error());
}
So this is what I have so far and when I try to insert into my database it only inserts the first record and I get an error. Eventually I want to pass these variables with Jquery, but I just need to get the PHP working first.
$query = 'INSERT INTO webportal.test (PSID, SysPatVisitID, AmountDue, Amount, InvoiceNum)'.
" VALUES ('".mysql_real_escape_string($_POST['PSID'][$i])."',
'".mysql_real_escape_string($_POST['SysPatVisitID'][$i])."',
'".mysql_real_escape_string($_POST['AmountDue'][$i])."',
'".mysql_real_escape_string($_POST['Amount'][$i])."',
'".mysql_real_escape_string($_POST['InvoiceNum'][$i]).")
ON DUPLICATE KEY UPDATE content=VALUES(
'".mysql_real_escape_string($_POST['AmountDue'][$i])."',
'".mysql_real_escape_string($_POST['Amount'][$i])."',
'".mysql_real_escape_string($_POST['InvoiceNum'][$i])."'
";
You're not matching your 's correctly. '". <stuff> ."''. You only need one closing tick.
You forgot your closing bracket for VALUES.
If you wish for your id to be auto incremented by the DBMS, don't include it in your query at all.
Also, error messages exist for a reason. Learning to understanding them will greatly increase your debugging capabilities. If you don't understand the error, just look it up on MySQL.com.

Categories