Data not required is being displayed - php

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>

Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

Related

Dynamic sort by header in PHP

I'm trying to create a dynamic header on Name which gives the user the ability to sort by ASC or DESC, the results is from the 'register'-table in MySQL. I have tried a couple of codings, but it hasn't given the correct result as of now. Hope anyone is able to help me :)
I have tried making another variable, but I couldn't manage to create the correct one.
<?php
$sql = "SELECT * FROM register";
if($sqlData = mysqli_query($db, $sql)) {
if(mysqli_num_rows($sqlData) > 0) {
echo "<table border ='1' bgcolor='#FFF' width='100%'>";
echo "<tr>";
echo "<th><a href='overview.php?order=name'>Name</a></th>";
echo "<th>Score</th>";
echo "</tr>";
while($row = mysqli_fetch_array($sqlData)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($sqlData);
} else{
echo "No results in DB";
}
} else{
echo "Error couldn't connect $sql. " . mysqli_error($db);
}
mysqli_close($db);
?>
Hm, that's not a good idea to sort table using MySQL each time user clicked on the table's header.
I suggest you to use javascript for it. Example

How to display dates in two html tables side by side according to month?

I am trying to display status of employee for each date in a month in the given application.
i have divided data in two tables.
Now, if you can see , My tables are displaying dates correctly.
But i want to start new table for each month. i.e. whenever 1st date of new month begins, i want to start the procedure of rendering dates for the month again.
So i will be able to distinguish them by their months.
I hope i have explained the problem correctly.
Please provide guidance on this .
Thanks in advance.
My code for the given problem :
<?php
$name=$_SESSION['sess_username'];
$dateofattendance=$_SESSION['sess_date'];
$time="00-00-00";
$status="absent";
$counter=0;
$conn = new mysqli('localhost', '', '', 'test');
$sql="SELECT dateofattendance,timeofattendance, status,timeofdeparture FROM attendance Where emp='$name' ORDER BY dateofattendance ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table class='main'><tbody><tr><td >";
// create the opening table
echo "<div align='left'><table class='sep1'style='float:left;'; border='black' cellpadding='5' ><thead> <tr><th> Date </th><th>IN</th><th>OUT</th><th>Status</th></tr></thead>tbody>";
while($row = $result->fetch_assoc())
{
// create the row
echo "<tr><td>" . $row["dateofattendance"]. "</td><td>" . $row["timeofattendance"]. "</td><td>" . $row["timeofdeparture"]. "</td>";
if($row["status"]=='present')
{
echo "<td ><span class='label label-success'>". $row["status"]."</span></td>";
}
else
{
echo "<td><span class='label label-danger'>". $row["status"]."</span></td>";
}"
</tr>";
$counter++;
// when the counter is 15, close this table and open another
if($counter == 15)
{
echo "</td><td>"; // move to the next cell in our wrap table
echo "</tbody></table></div> ";
echo "<table class='sep2'style='float:left;'border='black'cellpadding='5'><thead> <tr><th> Date </th><th>IN</th><th>OUT</th><th>Status</th></tr></thead><tbody>";
}
}
// close the last table
echo "</tbody></table>";
// close our wrapper table
echo "</td></tr></tbody></table>";
}
$conn->close();
?>
Instead of having a counter and creating a new table when it hits 15, you want to have a variable that stores the month number of the last row rendered, and check if the month number of the next row to be rendered matches. If it doesn't match, generate a new table.
The following code is produces the results you want. I've tested it with a database table with identical structure (table named "test_employees").
Note, the code outputs valid HTML and I re-formatted the echo statements and added newline chars to make the both the PHP and HTML source code more readable.
This code could be cleaned up considerably, so it's by no means good production code, but again, it demonstrates the logic you are after.
One item to note, the code only works within a given year. Additional code would be required if you wanted to display tables across multiple years.
If this helps you, please mark my answer.
I can also spend more time to refactor this code if you want. Let me know and I'll reply faster the next time.
<!DOCTYPE html>
<html>
<head>
<title>table test</title>
</head>
<body>
<?php
$name=$_SESSION['sess_username'];
$dateofattendance=$_SESSION['sess_date'];
$time="00-00-00";
$status="absent";
$counter=0;
$conn = new mysqli('localhost', '', '', 'test_employees');
$sql="SELECT dateofattendance,timeofattendance, status,timeofdeparture FROM attendance Where emp='$name' ORDER BY dateofattendance ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>IN</th>";
echo "<th>OUT</th>";
echo "<th>Status</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
$first_iteration = 1;
$row = $result->fetch_array(MYSQLI_ASSOC);
$last_month_num = split('-', $row["dateofattendance"])[1];
while($row = $result->fetch_assoc())
{
$current_month_num = split('-', $row["dateofattendance"])[1];
if ($first_iteration == 1) { // do nothing the first time around
$first_iteration = 0;
}
else if ($current_month_num == $last_month_num) { // only close row in current table
echo "</tr>";
}
else { // close table and start new table
echo "</tr>";
echo "</table>";
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>IN</th>";
echo "<th>OUT</th>";
echo "<th>Status</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
}
echo "<tr>" . "\n";
echo "<td>" . "\n" . $row["name"] . $row["dateofattendance"] . "\n" . "</td>" . "\n";
echo "<td>" . "\n" . $row["timeofattendance"] . "\n" . "</td>" . "\n";
echo "<td>" . "\n" . $row["timeofdeparture"] . "\n" . "</td>" . "\n";
if($row["status"]=='present')
{
echo "<td><span class='label label-success'>". $row["status"]."</span></td>";
}
else
{
echo "<td><span class='label label-danger'>". $row["status"]."</span></td>";
}
$counter++;
$last_month_num = split('-', $row["dateofattendance"])[1];
}
echo "</tr>";
echo "</table>";
}
$conn->close();
?>
</body>
</html>

Limiting column for fetched data in php

I am trying to put extracted mysql data into a table using php. The issue is that I am able to put the fetched data into either all rows or all columns. What I would like to do is put the fetched data into a column format and as soon as 4 columns are used, the next data should start on the next row and so on.
Currently I am using the logic below, however I am getting everything in a column.
The goal is to limit the data to a page size so the data can be printed.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
while($row = mysql_fetch_array($result))
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?></div>
If I understand your problem correctly you will want to do something like:
Keep a counter to see which number record you're looking at ($i)
$i = 0; // Your counter
while($row = mysql_fetch_array($result))
{
// ...
On every 4th iteration of the loop output something like </tr><tr>.
if ($i % 4 == 0 && $i > 0) // Will return true if `$i` is a multiple of 4 and greater than 0
{
echo "</tr><tr>"; // Output your HTML to start a new row
}
One final note: As others will be pointing out. You should avoid using the MySQL extension. You should use MySQLi or PDO instead.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
$i = 1;
while($row = mysql_fetch_array($result))
{
if($i == 4)
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
$i=0;
}
$i++;
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
</div>

How would I create and bring in a variable from another PHP page

I have a table that is created in
php. I have called this page events. I have used an include function within my user page to display the table so that a user can use the events to book an event. The thing is, I now need to create a page that will run once a user has clicked on the book now button. This page will update the booking table in my database. I am completely lost here and don't know how to go about creating this page as I think I need a variable that is brought in from the events table, perhaps via the button. The booking table in the database has these columns. Booking_ID, User_ID, Event_ID, Payment_Type and Date_Booked. I know I am using mysql but I will get the newer versions after I have this all working. I just don't know where to start on the creation of the booking PHP and inserting the values from the events table into the database. Any help will be greatly appreciated.
This is the events table that is displayed on the user page to book an event
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("flexiflash", $con);
// Creating the foundations for the table headings //
echo "<thead>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Venue</th>";
echo "<th>Event</th>";
echo "<th>Date</th>";
echo "<th>Time</th>";
echo "<th></th>";
echo "</tr>";
echo "</thead>";
// Running a JavaScript function to check for the user's payment type before submitting the form to book_event.php //
echo '<script>
function check() {
if (document.getElementById("checkbox").checked && document.getElementById("card").checked)
{
alert("Pay by card with 20% off");
return true;
}
else if (document.getElementById("checkbox").checked && document.getElementById("paypal").checked)
{
alert("Pay via PayPal with 20% off");
return true;
}
else if (document.getElementById("card").checked)
{
alert("Pay by card without a voucher!");
return true;
}
else if (document.getElementById("paypal").checked)
{
alert("Pay via PayPal without a voucher!");
return true;
}
else
{
alert("Nothing was checked. Please select your payment type");
return false;
}
}
</script>';
$result = mysql_query("SELECT * FROM events");
while($row = mysql_fetch_array($result))
{
// Outputting the data from the $result variable into a formatted table //
echo "<tbody>";
echo "<form class='table-form' action='book_event.php' method='post' onsubmit='return check()'>";
echo "<tr>";
echo "<td>" . $row['Event_ID'] . "</td>";
echo "<td>" . $row['Event_Venue'] . "</td>";
echo "<td>" . $row['Event_Name'] . "</td>";
echo "<td>" . $row['Event_Date'] . "</td>";
echo "<td>" . $row['Event_Time'] . "</td>";
echo "<td><input type='submit' class='sub_btn' value='Book now'></td>";
echo "</tr>";
echo "</form>";
echo "</tbody>";
}
mysql_close($con);
?>
If you need any more code or any other information please feel free to ask.
I know my code is not great and I am using Javascript inside my PHP but I am still learning PHP. Only been doing this for about 2 months, so I know its not the best.
If the page you are sending your data to is on the same host then SESSION might be what youre looking for. You can also use the form to POST data, via a form action to another page to process the data. If the data isnt sensitive then you can pass vars between pages with GET or even cookies, but it seems that passing the data isn't your main concern here.
One option to look at is creating a separate page to handle the form processing and insert the data, this can be called in the form action tag
It sounds like you are new to this and it might over complicate things but it is worth looking at MVC to separate concerns.

Send individual array results to printer based on id table

I'm working on a simple PHP script that stores user details in a MySQL database. I can run a query and have it return the individual records as long as the query matches the last name (pre-defined). Once I have the records, I want to be able to echo a print button next to each record so that the user can individually print each record.
The code is a mashup of several snippets of code and is working great, except the "print user data" part. I'm not a newbie in PHP, but I also know enough to navigate around a script. Here's what I've got so far.
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['keyname']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = "localhost"; //server
$db = "users"; //database name
$user = "root"; //dabases user name
$pwd = "password1"; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM details WHERE lastname LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
/* check whether there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
echo "<tr valign=bottom>";
echo "<td bgcolor=#ffffff background='img/dots.gif' colspan=6><img src=img/blank.gif width=1 height=1></td>";
echo "</tr>";
echo "<tr valign=center>";
echo "<td class=tabval><img src=img/blank.gif width=10 height=20></td>";
echo "<td class=tabval><b>".htmlspecialchars($row['firstname'])."</b> </td>";
echo "<td class=tabval>".htmlspecialchars($row['lastname'])." </td>";
echo "<td class=tabval>".htmlspecialchars($row['address'])."</td> ";
echo "<td class=tabval>".htmlspecialchars($row['phone'])." </td>";
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
echo "<td class=tabval></td>";
echo "</tr>";
$i++;
}
echo "<tr valign=bottom>";
echo "<td bgcolor=#fb7922 colspan=6><img src=img/blank.gif width=1 height=8></td>";
echo "</tr>";
echo $output;
}
else
echo "There was no matching record for the name " . $searchTerm;
?>
<br />
Done
echo "<button type=\"button\" class=\"formbutton\" onclick=\"printpage('" . $lastname . "'); \">Print User Data</button>";
This line is calling a javascript function called "printpage". Once you have that javascript function on the page, you'll be closer to your expected result.

Categories