Replace echo data shown with new echo data when searching - php

I am creating a page in PHP, HTML and using MySQL. Currently When I load the page, it selects all the data from the staff table and displays it.
I have a search function so the user can filter by first name, last name or full name.
When the user clicks the search button, is it possible to have the data that's showing every row and just to replace it with my searched criteria.
Currently my code is searching correct but its just adding it as a row to all the data rows. I thought i could use a regex to replace but the variable is not accessible globally since it is inside an if statement.
<?php
$output = NULL;
if(isset($_POST['submit'])) {
$regex = '/<table[^>]*>.*?<\/table>/s'; //test doesnt work
$replace = ''; //test doesnt work
$result = preg_replace($regex, $replace, $html); //test doesnt work "no html variable"
echo($result); //test doesnt work
$search = $con->real_escape_string($_POST['search']);
$res = $_POST['searchGroup'];
if($res == "first") {
$resultSet = $con->query("SELECT * FROM staff WHERE firstname LIKE '%$search%'");
if($resultSet->num_rows > 0) {
while($rows = $resultSet -> fetch_assoc()) {
$field1name = $rows["firstname"];
$field2name = $rows["lastname"];
$field3name = $rows["dob"];
$field4name = $rows["created"];
$field5name = $rows["last_updated"];
$field6name = $rows["is_user"];
$output .= '<tr>
<td>'.$field1name.'</td>
<td>'.$field2name.'</td>
<td>'.$field3name.'</td>
<td>'.$field4name.'</td>
<td>'.$field5name.'</td>
<td>'.$field6name.'</td>
</tr>';
}
}
else {
$output = "No Results";
}
}
And then my code which is currently displaying all the data
<?php
$query = "SELECT * FROM staff";
echo '<div class="tableFixHead">
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td> <font face="Arial"><b>First Name</b></font> </td>
<td> <font face="Arial"><b>Last Name</b></font> </td>
<td> <font face="Arial"><b>Date of Birth</b></font> </td>
<td> <font face="Arial"><b>Creation Date</b></font> </td>
<td> <font face="Arial"><b>Last Updated</b></font> </td>
<td> <font face="Arial"><b>Is User</b></font> </td>
</tr>
</div>';
echo $output;
if ($result = $con->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["firstname"];
$field2name = $row["lastname"];
$field3name = $row["dob"];
$field4name = $row["created"];
$field5name = $row["last_updated"];
$field6name = $row["is_user"];
$html= '<tr>
<td>'.$field1name.'</td>
<td>'.$field2name.'</td>
<td>'.$field3name.'</td>
<td>'.$field4name.'</td>
<td>'.$field5name.'</td>
<td>'.$field6name.'</td>
</tr>';
echo $html;
}
$result->free();
}
?>
My approach is probably wrong but I was wondering if it is possible to somehow remove that data that is in the current $html echo tag when my search button is pressed.

Besides the code style, vulnerabilities i would like to offer you an example of some sorts. as i presume that you are still a student.
just a simple example what you could do;
$query = "SELECT * FROM staff";
if(isset($_POST['submit'])) {
$search = $con->real_escape_string($_POST['search']);
$query .= " WHERE firstname LIKE '%$search%'"
}
This should be sufficient to help you forward.

Related

How do I display different table from 1 table? Like each table has unique code

This are my db table:
But my query only get 1 row for each table like this:
As you can see, there are 2 tables for 1003 because it has 2 rows. It should be only one (1) table of 1003 with 2 rows. How do I fix this? EXPECTED RESULT:
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone GROUP BY model";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row["model"]?></td>
</tr>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You have at least 5 problems here,
[edit: problem 1 removed & changed sample based on extended answer]
Inside your while { ... } loop, you're printing an entire table, when you should only be printing the <tr>...</tr> part there. This is what causes additional table(s).
And 3rd problem: your "no_record" line is a loose <td>. Not only isn't it inside the table (which is covered in problem #2), it's also not wrapped with a <tr>.
4th problem: You're randomly printing the echo $row["brand_code"] outside of the table.
5th problem: you're printing raw data from the database as if it is valid html, it more than likely is not. it has to be probably encoded with htmlentities/htmlspecialchars.
Quick & dirty fixed version:
function tableOpen($row) {
printf( '<h1>%s</h1>', htmlentities($row["brand_code"]) );
echo '<table id="table_stock" class="">';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
}
function tableClose() {
echo '</tbody>';
echo '</table><br>';
}
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone ORDER BY brand_code";
$lastBrand = null;
if ($result = mysqli_query($db, $query)) {
if (mysqli_num_rows($result) > 0) {
if ($lastBrand !== $row["brand_code"] && !is_null($lastBrand)) tableClose();
if ($lastBrand !== $row["brand_code"]) tableOpen($row);
$lastBrand = $row["brand_code"];
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
printf( '<td>%s</td>', htmlentities($row["model"]) );
echo '</tr>';
}
tableClose();
/// Free result
mysqli_free_result($result);
} else {
echo '<p class="no_record">No records found.</p>';
}
} else {
echo "ERROR: Not able to execute \$query: <br>" . htmlentities($query) . '<br>' . htmlentities(mysqli_error($link));
}
you need additional loop. Also in the first query you need to use group by codes.
$query = "SELECT model, brand_code FROM smartphone GROUP BY brand_code";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
if ($result1 = mysqli_query($db, "SELECT DISTINCT model, brand_code FROM smartphone WHERE brand_code={$row["brand_code"]}"))
{
while ($row1 = mysqli_fetch_array($result1))
{
// get count for each model within brand_code
$cnt = ($result2 = mysqli_query($db, "SELECT COUNT(*) AS cnt FROM smartphone WHERE brand_code={$row["brand_code"]} AND model='{$row1["model"]}'")) && ($row2 = mysqli_fetch_array($result2)) ? $row2["cnt"] : "---";
?>
<tr>
<td><?php echo $row1["model"] ({$cnt})?></td>
</tr>
<?php
}
mysqli_free_result($result1);
}
?>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

MySQL - Select row values from url ID

I created a table which is updated through a form and each row gets assigned a specific number.
When viewing this table, I want to click on that assigned number and get a page where all the details of that row are displayed.
If I do $sql = "SELECT * FROM clients WHERE nif_id='114522';"; - where the nif_id is the assigned number - I get the values for that number, but I need it to change with every number in the table.
Any ideas?
UPDATE
This is the table code:
<div class="card card-body">
<table class="table">
<thead>
<tr>
<th>NIF</th>
<th>Nome</th>
<th>Apelido</th>
<th>Telemóvel</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
include_once '../includes/db.inc.php';
$sql = "SELECT * FROM clients ORDER BY nif_id ASC;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$first = $row["prm_nome"];
$last = $row["apelido"];
$phone = $row['nmr_tlm'];
$email = $row['mail'];
$nif = $row['nif_id'];
echo '<tr>';
echo '<td>'.$nif.'</td>';
echo '<td>'.$first.'</td>';
echo '<td>'.$last.'</td>';
echo '<td>'.$phone.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
You can use the get request parameters.
ex: www.myapp.com/table?id=3920393
add functionality in your PHP file as follows
if(isset($_GET["id"])){
$id = $_GET["id"];
$sql = "SELECT * FROM clients WHERE nif_id='".$id."';";
//make db call & display HTML
}
This is a very simple implementation and does not implement any security or SQL injection security. This was more of a conceptual answer as to how you can tackle your problem.
This is quite a common scenario for web-based systems.
<div class="card card-body">
<table class="table">
<thead>
<tr>
<th>NIF</th>
<th>Nome</th>
<th>Apelido</th>
<th>Telemóvel</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
include_once '../includes/db.inc.php';
$sql = "SELECT * FROM clients ORDER BY nif_id ASC;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$first = $row["prm_nome"];
$last = $row["apelido"];
$phone = $row['nmr_tlm'];
$email = $row['mail'];
$nif = $row['nif_id'];
echo '<tr>';
echo '<td>'.$nif.'</td>';
echo '<td>'.$first.'</td>';
echo '<td>'.$last.'</td>';
echo '<td>'.$phone.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
where the detail.php is another page to query specific details regarding the query nifid.
As a reminder, if the data type of the column is INT, there is no need to use single quotes to surround the value in the SQL statement.
Sample detail.php:
<?php
if(!isset($_GET['nifid']) || (int)$_GET['nifid'] <= 0) {
// Invalid or missing NIFID
header('Location: table.php');
}
include_once '../includes/db.inc.php';
$id = (int)$_GET['nifid'];
$sql = "SELECT * FROM clients WHERE nif_id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
// TODO: display the result in whatever way you like
?>

Output Multiple Database Results

I currently have this code set up:
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
$data_exist = true;
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
}
}
And then:
<?php if ($data_exist){?>
<p><?php echo $id ?></p>
<p><?php echo $teacher_set?></p>
<p><?php echo $name?></p>
<p><?php echo $description?></p>
<?php
}?>
However, the issue is if there is multiple results in the database it only outputs one of them, how can I prevent this from happening and output two?
I want to make it so every row has their own section, like this: http://prntscr.com/hcgtqn so if there is only one result, one one will show etc.
You have to echo data in a loop. Right now you are reassigning values in while($row = mysqli_fetch_assoc($result)) iterations and printing just the last one.
You need to print each time you read a row from the database.
about the styles, you can represent it in many ways. In the code below I present it in a table.
<table>
<thead>
<tr>
<th>id</th>
<th>teacher set</th>
<th>name</th>
<th>description</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$teacher_set = $row["teacher_set"];
$class = $row["class"];
$name = $row["name"];
$description = $row["description"];
// you need to print the output now otherwise you will miss the row!
// now printing
echo "
<tr>
<td>".$id."</td>
<td>".$teacher_set."</td>
<td>".$name."</td>
<td>".$description."</td>
</tr>";
}
}
else // no records in the database
{
echo "not found!";
}
?>
</tbody>
</table>
</body>
</html>

Website interface on 2 screens

I'm making this website, and it's only gonna be opened on 2 screens at the same time. I'm going to generate a table with php with output from a database.
My goal is that if the table doesn't fit on the main screen it goes to the second screen.
Is this even possible?
I've tried to come up with something but couldn't figure anything out. I have tried for loops but it has to do with the style and html or maybe javascript or jquery?
If this isn't possible should I generate a second window with jquery?
Thanks in advance!
if (!empty($_POST['check_list']))
{
$idArr = $_POST['check_list'];
$id = $idArr[0];
$parameters = array(':medId'=>$id);
$sth = $pdo->prepare("SELECT naam FROM medewerkers WHERE medewerkerid = :medId");
$sth->execute($parameters);
while ($row = $sth->fetch())
{
echo "<h2>" . $row['naam'] . "</h2>";
}
?>
<table class="table">
<tr>
<th>Donderdag <br> 31-05</th>
<?php
$datum = "2017-05-31";
$parameters = array(':date'=>$datum,
':aid'=>$id);
$sth = $pdo->prepare("SELECT DISTINCT opdrachten.KRITISCHE_DATUM, opdrachten.PLANNINGS_DATUM, opdrachten.OPDRACHTID, onderzoekactiviteiten.A_UITVOERDER
FROM opdrachten
INNER JOIN onderzoekactiviteiten
ON opdrachten.OPDRACHTID=onderzoekactiviteiten.OPDRACHTID
WHERE PLANNINGS_DATUM = :date
AND A_UITVOERDER = :aid");
$sth->execute($parameters);
while ($row = $sth->fetch())
{
$cutKritDate = substr($row['KRITISCHE_DATUM'], 0, 10);
$cutPlanDate = substr($row['PLANNINGS_DATUM'], 0, 10);
echo "<td>Krit= " . $cutKritDate . "<br>";
echo "Plan= " . $cutPlanDate . "<br>";
echo "Opdracht= " . $row['OPDRACHTID'] . "</td>";
}
?>
</tr>
<tr>
<th>Vrijdag <br> 02-06</th>
</tr>
<tr>
<th>Maandag <br> 03-06</th>
</tr>
<tr>
<th>Dinsdag <br> 04-06</th>
</tr>
<tr>
<th>Woensdag <br> 05-06</th>
</tr>
</table>
<?php
}
else
{
$check_list = NULL;
$id = NULL;
echo "U bent vergeten een medewerker aan te vinken.";
}
I have a form with names, if one is selected it generates a table. this is how I generate the table. The goal is that the tables are below each other. But when it doesn't fit anymore (when you can scroll) the table needs to go to the second screen.

Multiple While Loop Replaces the first Data with the 2nd Data

i have a problem with my code below..
I want to display the data that is not associated with the ID of my $jid but i think i have a problem with my loop. the First data displayed is removed and replaced with the last result...
heres the code. can somebody help me out on this
$check_exist_query = mysql_query("SELECT * FROM physical_abilities_assignment where job_title_id = $jid");
while($check_exist_row = mysql_fetch_array($check_exist_query)){
$list = "";
$physical_title_id = $check_exist_row['2'];
if(empty($physical_title_id)){
$display_abilities_query = "SELECT * FROM physical_abilities";
}else{
$display_abilities_query = "SELECT * FROM physical_abilities WHERE id != $physical_title_id";
}
$display_abilities_result = mysql_query($display_abilities_query);
while($display_abilities_row = mysql_fetch_array($display_abilities_result)){
$abilities_name = $display_abilities_row[2];
$abilities_id = $display_abilities_row[0];
$list .= "<tr>
<td $bgcolor align=center><input type=\"checkbox\" ".$check." name=\"job_title[]\" value=".$title_id." id=\"".$title_id."\"></td>
<td $bgcolor style=\"padding-left:5px;\">".$abilities_name."</td>
<td $bgcolor align=center><a onClick=\"return confirm('Are you sure you want to delete this entry?');\" href=?do=delete&id=". $row[0] ."><img src=\"images/delete-icon.png\" border=0 ></a> <img src=\"images/edit-icon.png\" title=\"Edit This\" border=0/></td>
</tr>";
}
$list = "";
$check_exist_query = mysql_query("SELECT * FROM physical_abilities_assignment where job_title_id = $jid");
while($check_exist_row = mysql_fetch_array($check_exist_query)){
$physical_title_id = $check_exist_row['2'];
if(empty($physical_title_id)){
$display_abilities_query = "SELECT * FROM physical_abilities";
}else{
$display_abilities_query = "SELECT * FROM physical_abilities WHERE id != $physical_title_id";
}
$display_abilities_result = mysql_query($display_abilities_query);
while($display_abilities_row = mysql_fetch_array($display_abilities_result)){
$abilities_name = $display_abilities_row[2];
$abilities_id = $display_abilities_row[0];
$list .= "<tr>
<td $bgcolor align=center><input type=\"checkbox\" ".$check." name=\"job_title[]\" value=".$title_id." id=\"".$title_id."\"></td>
<td $bgcolor style=\"padding-left:5px;\">".$abilities_name."</td>
<td $bgcolor align=center><a onClick=\"return confirm('Are you sure you want to delete this entry?');\" href=?do=delete&id=". $row[0] ."><img src=\"images/delete-icon.png\" border=0 ></a> <img src=\"images/edit-icon.png\" title=\"Edit This\" border=0/></td>
</tr>";
}
echo $list;
Try this.

Categories