Search only month of a date in database within an if statement - php

I have posted a form to output data form database. I am having trouble within my if statement looking to echo all lines that my month form post == the month within my database i.e if my form post was 04 i want it to equal all data that == XXXX/04/XX and echo them all.
At the moment it is not returning anything as the date formats do not match
Thank you in advance.
if(isset($_POST['submit'])) {//form has been submitted
$search = new Page();
$search->sub_name = $_POST['sub_name'];
$search->location = $_POST['location'];
$search->date_from = $_POST['date_from'];
} ?>
<h2>
<?php echo $search->sub_name; echo " "; echo $search->location;?>
</h2>
<table class="bordered" cellpadding="1" cellspacing="1">
<thead>
<tr> <th>Course</th> <th>Dates</th> <th>Course Type</th> <th>Location</th><th>Price </th><th></th></tr>
</thead>
<?php
$pages = Page::find_all();
foreach($pages as $page){
if($search->sub_name == $page->sub_name && $search->location == $page->subject && $search->date_from == $page->date_one('m')) {
echo "<tbody><tr><td>" . nl2br($page->course_name) . "</td><td>" . nl2br($page->date_from) . "</td><td>" . nl2br($page->sub_name) . "</td><td>" . nl2br($page->subject) . "</td><td>" . nl2br($page->price) . "</td><td><a href=\"hbt_bookings.php?id=" . urlencode($page->id) . "#type\">Book>>></td>" ."</tr></tbody>";
}
}
?>
</table>

Related

How can I use a select box in HTML to search for a specific user in the database and show that information on a table?

I have a select box that shows the names of all the users in the database, however, I need, using a "Find Button" on the selected user on the combo box, that the data attached to that user shows up on the table
Table that currently shows the data of all users
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
$sql = "SELECT * FROM shifts";
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
And here's the form that shows the users in the select box
<form name="form1" method="POST" action="">
<select name="getUser">
<?php
$res = mysqli_query($db, "SELECT * FROM shifts");
while ($row = mysqli_fetch_array($res))
{
?>
<option><?php echo $row ["name"]; ?></option>
<?php
}
?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
I'm trying to make it that so when the selected user in the combo box and the find button is pressed, that the data found goes all into the table described above.
I was maybe gonna try to attach a variable to the select box and compare it with the names field on the database.
Something like this
$query = "SELECT * FROM shifts WHERE $name == $nameSelected ";
Thanks.
first echo the user id into the option's value
<option value-"<?echo your id?>"><?php echo $row ["name"]; ?></option>
then when your form submits you get get the value from the $_POST
$userId = $_POST['getUser'];
not you can use the variable to query the database, but you should NEVER put it straight in, you should use PDO prepared statements to prevent injection.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//something like this
$query = $conn->prepare("SELECT * FROM shifts WHERE id = :id");
$query->bindParam(':id',$userId,PDO::PARAM_INT);
$query->execute()
return $query->fetchAll();// I realised you wanted to get all the shifts so you don want fetchAll(),
notice that in mysql we only use a single = for our comparison unlike php. Also i've changed name to the unique row in the database, as unless your name field is unique how do you know which use called Dan you want?
If you want to do this without re-loading the whole page you will need to look into using Ajax and passing the value of the option tag via jQuery.
Here are some places to start:
https://www.w3schools.com/php/php_mysql_connect.asp
https://www.w3schools.com/xml/ajax_intro.asp
if you are not comfortable with javascript (AJAX), try on your form
<?php $res = mysqli_query($db, "SELECT * FROM shifts"); ?>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"
<select name="getUser">
<option value='All'>All</options>
<?php
while ($row = mysqli_fetch_array($res)) { ?>
<option value='$row ["name"]'><?php echo $row ["name"]; ?></option>
<?php } ?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
And in your table
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
if ($_POST['getUser'] == 'All'){
$sql = "SELECT * FROM shifts";
} else {
$sql = "SELECT * FROM shifts WHERE name = " . $_POST['getUser'];
}
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>

php-mysql - need to match two keywords which are supplementary to each other rather than independent ones

I have a database table cav in mysql.
I need to fetch result using php on the basis of two keywords which would search in two columns viz. 'caseno' and 'year'.
In the user form I provide two input fields namely 'keyword' and 'keyword1'.
Wish to show result only when keyword and keyword1 matched exactly with the values already exist in the column 'caseno' and 'year' (in a single row) in the database .
for example if user put 684 as keyword and 2007 as keyword1 query should fetch data of a row where value of caseno column is 684 and value of year column is 2007.
My problem is that suppose I am putting 684 as keyword and nothing in keyword1 even then it is showing the row containing 684, if I put 684 as keyword and 2010 as keyword1 even then it is showing row containing 684.
Wish to show the data of a row where 'caseno' is 684 (user defined keyword) and 'year' is 2007 (user defined keyword.
Have tried the following code:-
<?php
$db_host="";
$db_user="";
$db_pass="";
$db_name="";
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
if($db->connect_error){
die("Connection failed: " . $db->connect_error);
}
?>
<?php
if(!empty($_POST))
{
$aKeyword = explode(" ", $_POST['keyword']);
$bKeyword = explode(" ", $_POST['keyword1']);
$query ="SELECT * FROM cav WHERE caseno like '%" . $aKeyword[0] . "%' AND
year like '%".$bkeyword[0]."%'";
$result = $db->query($query);
if(mysqli_num_rows($result) > 0) {
$row_count=0;
echo '<br><br><br><br><br>
<center><table class="table-1 mt-2 table-responsive table border="1"
table-bordered"><TABLE BORDER=2 BORDERCOLOR=BLACK font size="2">
<tr>
<th>S.No.</th>
<th>Case Type</th>
<th>Case No.</th>
<th>Year</th>
<th>Petitioner Name</th>
<th>Respondent Name</th>
<th>First Coram</th>
<th>Second Coram</th>
<th>Third Coram</th>
<th>Written By</th>
</tr></center> ';
While($row = $result->fetch_assoc()) {
$row_count++;
echo "<tr><td> ".$row_count." </td><td>". $row['casetype'] . "</td><td>".
$row['caseno'] . "</td><td>". $row['year'] . "</td><td>".
$row['petitioner'] . "</td><td>". $row['respondent'] . "</td><td>".
$row['firstcoram'] . "</td><td>". $row['secondcoram'] . "</td><td>".
$row['thirdcoram'] . "</td><td>". $row['writtenbycoram'] . "</td>
</tr>";
}
echo "</table>";
}
else {
echo "<br>Result Found: NONE";
}
}
?>
html form is
<input type="text" name="keyword" autocomplete "off">
<input type="text" name="keyword1" autocomplete "off">
<input type="submit" value="Search"><FORM><INPUT Type="button"
VALUE="Back" onClick="history.go(-1);return true;">
Wish to show result only when values of both the columns i.e.'caseno' and 'year' match exactly to the keywords given by user. if user put only 684 or only 2007 or 684 and 2010 or 784 and 2007 it will show 'no result found'
I think this code here could solve your issue much easily since I see you were just missing a few points to make it work as you wanted. I have also made the rest code much better to manage
$html = '';
if(!empty($_POST))
{
$aKeyword = explode(" ", $_POST['keyword']);
$bKeyword = explode(" ", $_POST['keyword1']);
$query = 'SELECT * FROM cav WHERE caseno LIKE "%'.$aKeyword[0].'%" OR caseno LIKE "%'.$bKeyword[0].'%"';
$result = $db->query($query);
if(mysqli_num_rows($result) > 0) {
$row_count=0;
$html .= '<br><br><br><br><br>';
$html .= '<center><table class="table-1 mt-2 table-responsive table border="1"
table-bordered"><table border="2" bordercolor="black" font-size="2">';
$html .= '<tr>
<th>S.No.</th>
<th>Case Type</th>
<th>Case No.</th>
<th>Year</th>
<th>Petitioner Name</th>
<th>Respondent Name</th>
<th>First Coram</th>
<th>Second Coram</th>
<th>Third Coram</th>
<th>Written By</th>';
$html .= '</tr></center> ';
While($row = $result->fetch_assoc()) {
$row_count++;
$html .= '<tr><td> '.$row_count.' </td><td>'. $row['casetype'] . '</td><td>'.
$row['caseno'] . '</td><td>'. $row['year'] . '</td><td>'.
$row['petitioner'] . '</td><td>'. $row['respondent'] . '</td><td>'.
$row['firstcoram'] . '</td><td>'. $row['secondcoram'] . '</td><td>'.
$row['thirdcoram'] . '</td><td>'. $row['writtenbycoram'] . '</td>
</tr>';
}
$html .= '</table>';
}
else {
$html .= '<br>No results found';
}
}
echo $html;
Your problem was using AND instead of using OR

Delete MySQL row from PHP while loop

I have a while loop displaying my database columns and rows in table.
I want make a button which can delete specific MySQL row but unfortunately I can't select which of all rows have to be deleted simply because I use "while loop" to display my database content in HTML.
Providing picture for better understanding what I want to do:
So yeah, I want that when the green button is clicked - send MySQL query to delete this row (which is existing in my DB).
Providing code:
<?php
//CONECT TO MYSQL
include 'database.php';
//GET VALUES
$sql = "SELECT * FROM amountcontainer";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
//Table headlines - NOT A PHP
echo "<table class='moneytable'>
<tr>
<th style='background-color: #2d323a; color: white;'>Date</th>
<th style='background-color: #2d323a; color: white;'>Amount</th>
<th style='background-color: #2d323a; color: white;'>Reason</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
//RED //Make statement of amount red if it has a " - "
if(strpos($row['amount'],'-') !== false)
{
echo
"
<tr>
<th style='font-weight: normal;background-color: #ff9999;' class='row-time'>" . $row['time'] . "</th>
<th style='font-weight: normal;background-color: #ff9999;' class='row-amount'>" . $row['amount'] . "</th>
<th style='font-weight: normal;background-color: #ff9999;' class='row-reason'>" . $row['reason'] . "</th>
</tr>
";
}
//NORMAL //Make statement of amount normal if it doesn't have a " - "
else
{
echo
"
<tr>
<th style='font-weight: normal;' class='row-time'>" . $row['time'] . "</th>
<th style='font-weight: normal;' class='row-amount'>" . $row['amount'] . "</th>
<th style='font-weight: normal;' class='row-reason'>" . $row['reason'] . "</th>
</tr>
";
}
}
echo "</table>";
}
else
{
echo "0 results";
}
First, only use <th> elements for the table headers. For the actual data cells use the <td> element.
To allow deletion of individual database rows you can include links in your table. In your loop that creates the table rows:
<tr>
<td>" . $row['time'] . "</td>
<td>" . $row['amount'] . "</td>
<td>" . $row['reason'] . "</td>
<td><a href='?deleteId=$row[keyID]'>Delete</a></td>
</tr>
In this case, when the "Delete" link is selected it calls your same script with a $_GET variable: "deleteId" which you can test for and if found, perform the delete of the row. You can also embed the table in an html form and add a submit button to a cell in each row, with the value of the submit set to the row id to delete.
This sounds like a place for ajax. Heres a crude example that might give you a good starting point.
<?php
while($row = $result->fetch_assoc()) {
$isNegative = strpos($row['amount'],'-') !== false;
echo "<tr class='record' data-id=\"{$row["id"]}\">";
//Use ternary operator & css classes
echo "<td class='standard-record ".$isNegative ? "color-red" : "" ."''>{$row["record"]}</td>";
echo "</tr>";
}
?>
<script>
$(".record").click(function(){
var request = {
id: $(this).data("id")
};
$.post( "delete-record.php", request, function(data){
$(this).remove();
});
});
</script>
Change this
if(strpos($row['amount'],'-') !== false) # wrong way
to this
if($row['amount'] < 0) # detecting negative numbers
You need to add an extra
<th style='font-weight: normal;' class='row-reason'><a class="crossBtn" href="?del_id=".$row['id']."> </a></th>
And the get the del_id and delete this specific records.

Highlighting rows from results

I have a script which returns 5 columns from a php result. I am trying to match one of the columns due date against the current date. If the date returned is older I want to highlight that row. It does not seem to for some reason. I have tested my if statement and it work.
<?php
// First of all initialise the user and check for permissions
require_once "/var/www/users/user.php";
$user = new CHUser(7);
// Initialise the template
require_once "/var/www/template/template.php";
$template = new CHTemplate();
// And create a cid object
require_once "/var/www/WIPProgress/DisplayWIPOnLocation.php";
$WIPProgress= new CHWIPProgress();
$content = "<h1>Check WIP Status on Location </h1>";
$content =
"<form action='index.php' method='get' name ='location'>
<select id='location' name ='location' >
<option>Skin Room</option>
<option>Clicking</option>
<option>Kettering</option>
<option>Closing</option>
<option>Rushden</option>
<option>Assembly</option>
<option>Lasting</option>
<option>Making</option>
<option>Finishing</option>
<option>Shoe Room</option>
</select>
<input type='submit' />
</form>";
if(isset($_GET['location'])) {
$wip = $WIPProgress->ListWIPOnLocation($_GET['location']);
$location = $_GET['location'];
$todays_date = date("Y-m-d H:i:s");
// Now show the details
$content .=
"<h2>Details for $location </h2>
<table>
<tr>
<th>PPDescription</th>
<th>Works Order</th>
<th>Bundle Number</th>
<th>Bundle Reference</th>
<th>Due Date</th>
</tr>";
foreach($wip as $x) {
if(strtotime($x['DueDate']) > strtotime($todays_date)){
$content .=
"<tr bgcolor='#FF0000'>
<td>" . $x['Description'] . "</td>
<td>" . $x['WorksOrder'] . "</td>
<td>" . $x['Number'] . "</td>
<td>" . $x['Reference'] . "</td>
<td>" . $x['DueDate'] . "</td>
</tr>";
}
}
}
else {
$content .= "<h3>Please choose a location to view WIP</h3>";
}
$template->SetTag("content", $content);
echo $template->Display();
?>
Is there any classes available in php which highlights rows returned?
Instead of defining bgcolor with tr define with each td in it.
OR better way to associate a CSS class to the tr and target all the td of this tr through CSS.
$content .= "<tr class='highlight'>...";
<style>
.highlight td
{
background-color:#FF0000;
}
</style>

Order list/ while loop php issue

I have put together a basic order list for admin users in php for checking order contents placed by logged in users.
The aim of this script is to retrieve the order details (item, quantity, price) as well as the user’s first name and surname (where ‘Order for:’ is).
The script below does everything ok in that it retrieves the order (and orders if there are more than one) and it’s/their item, quantity and price.
However, it doesn’t display the user’s name and surname.
I know the problem is that where I am trying to display the name is outside the while loop but Im a little stuck in where it should sit. Any suggestions? Code is below:
<?php
$page_title = 'View Individual Order';
include ('includes/header.html');
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
?>
<h1>Order Details</h1>
<?php
require_once ('database.php'); // Connect to the db.
// Retrieve the user's, order and product information.
$query = "SELECT us.users_id, us.users_sales_id, us.users_first_name, us.users_surname, us.users_dealer_name,
ord.order_id, ord.users_id, ord.total, ord.order_date,
oc.oc_id, oc.order_id, oc.products_id, oc.quantity, oc.price,
prd.products_id, prd.products_name, prd.price
FROM users AS us, orders AS ord, order_contents AS oc, products AS prd
WHERE ord.order_id=$id
AND us.users_id = ord.users_id
AND ord.order_id = oc.order_id
AND oc.products_id = prd.products_id
";
$result = mysql_query ($query) or die(mysql_error());
if (mysql_num_rows($result)) { // Valid user ID, show the form.
echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p>
<table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left"><b>Product</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>Qty</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
while($row = mysql_fetch_array($result, MYSQL_NUM)) { // WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
echo '';
}// end of WHILE loop
echo '</table>
<p> Here:</p>
<br><br>
<p> << Back to Orders</p>
<p> </p>
<p> </p>
<p> </p>
';
} else { // Not a valid user ID.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}
mysql_close(); // Close the database connection.
?>
<p>Footer here</p>
<?php
include ('./includes/footer_admin_user.html'); // Include the HTML footer.
?>
One way you could do it is grab the row first, and then use a do/while loop instead of just a basic while loop. Like this:
if (mysql_num_rows($result)) { // Valid user ID, show the form.
/*********** I added this line ***********/
$row = mysql_fetch_array($result, MYSQL_NUM);
echo '<p>Order for:<strong>' . $row[2] . ' ' . $row[3] . ' </strong> </p>
<table border="0" style="font-size:11px;" cellspacing="1" cellpadding="5">
<tr class="top">
<td align="left"><b>Product</b></td>
<td align="center"><b>Price</b></td>
<td align="center"><b>Qty</b></td>
</tr>';
$bg = '#dddddd'; // Set the background color.
/*********** I changed this from a while loop to a do-while loop ***********/
do { // WHILE loop start
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
echo '';
} while($row = mysql_fetch_array($result, MYSQL_NUM)); // end of WHILE loop
It looks like the problem is when you're trying to display the user's name:
echo '<p>Order for:<strong>'.$row[2].' '.$row[3]
The $row variable doesn't exist yet. Not seeing your database or the result from your database query, my guess is that the user's name is repeated next to every single item in their order, so it might be as simple as just starting the WHILE loop, and checking to see if you've printed their name yet:
$lastUser = NULL;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if ($row[0] !== $lastUser) {
if (isset($lastUser)) {
// finish up the report for the previous user
}
// echo the stuff for the current user's name
$lastUser = $row[0];
}
// go on echo-ing their order information
}
// after the while loop is over,
// close up the last user's report
But like I said, this is just a guess, and might be totally off.
The problem is that you tried to access $row[2] and $row[3] before mysql_fetch_array(). Since you are already echo'ing HTML tags, why don't you "buffer" your output first like this?:
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
$bg = ($bg=='#eaeced' ? '#dddddd' : '#eaeced');
$order = '<tr bgcolor="' . $bg . '">
<td align="left">' . $row[15] . '</td>
<td align="center">' . $row[13] . ' pts</td>
<td align="center">' . $row[12] . '</td>
</tr>';
$orders[$row[2] . " " . $row[3]][] .= $order;
}
Then do a second foreach loop for the $orders
foreach($orders as $name => $orderList)
{
echo "Order for: $name";
echo "<table ...>";
foreach($orderList as $order)
{
echo $order;
}
echo "</table>";
}

Categories