Trying to search table in PHP - javascript

I am trying to create a search within my table.
I have the table populated with date already loaded, but when i type into the search box for example a name and press submit, nothing is happening the page just reloads and nothing happens.
Here is the code, (i also need to do the same with a table where the table data is all foreign keys.)
<?php // Include config file
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/config.php");
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/functions.php");
include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/header.php");
$sql = "SELECT * FROM patient";
if (isset($_POST['searchform'])) {
$search_term = ($_POST['searchpat']);
$sql .= " WHERE fName LIKE '{$search_term}'";
$sql .= " OR sName LIKE '{$search_term}'";
$sql .= " OR addLineOne LIKE '{$search_term}'";
}
$query = mysqli_query($db, $sql) or die(mysql_error());
?>
<body>
<div class="container">
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/logo.html"); ?>
<h2>List of Patients</h2>
<p>All Patients Registered with Freddies Medical:</p>
<form name="searchform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Search for Patient</label>
<input type="text" class="form-control" name="searchpat" required><br>
<input type="submit" class="btn btn-primary" name="search" value="Submit">
<span class="help-block"></span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Surname</th>
<th>Address</th>
<th>Phone</th>
<th>Email Address</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td>'.$row['fName'].'</td>
<td>'.$row['sName'].'</td>
<td>'.$row['addLineOne'].", ".$row['addCity'].", ".$row['addPostCode'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['email'].'</td>
<td>View Patient</td>
<td>Delete</td>
</tr>';
$no++;
}?>
</tbody>
</table>
New Patient
Admin Area
</div>
<div class="bottompadding"></div>
<?php include("$_SERVER[DOCUMENT_ROOT]/freddies/inc/footer.php"); ?>
</body>
</html>

$_POST['searchform'] will not be set as far as I know since it is the name of the form and not a form element. Better check for isset($_POST['search']):
if(isset($_POST['search'])) {
$search_term = $_POST['searchpat'];
$sql .= " WHERE fName LIKE '%".$search_term."%'"; // Using % wildcard will search for fields 'containing' searched string rather then 'exact matches'
$sql .= " OR sName LIKE '%".$search_term."%'";
$sql .= " OR addLineOne LIKE '%".$search_term."%'";
}

Related

Filtering db table by date

My goals is to make filter for loading posts from 1 week ago, 1 month ago and two inputs from date from and date to ( if one of them is empty to be filled with current date( y-m-d h:m:s ) format
This is all i tried and could have made it to work, every answer is much appreciated, thank you
Tl:dr
Select filter for week ago, month ago
From date - to date ( if one of those is empty then use current date )
Index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_order ORDER BY order_id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Ajax PHP MySQL Date Range Search using jQuery DatePicker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Ajax PHP MySQL Date Range Search using jQuery DatePicker</h2>
<h3 align="center">Order Data</h3><br />
<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />
</div>
<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />
</div>
<div class="col-md-5">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
</div>
<div style="clear:both"></div>
<br />
<div id="order_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["order_id"]; ?></td>
<td><?php echo $row["order_customer_name"]; ?></td>
<td><?php echo $row["order_item"]; ?></td>
<td>$ <?php echo $row["order_value"]; ?></td>
<td><?php echo $row["order_date"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
And filter.php
<?php
//filter.php
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
$query = "
SELECT * FROM tbl_order
WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
";
$result = mysqli_query($connect, $query);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'. $row["order_id"] .'</td>
<td>'. $row["order_customer_name"] .'</td>
<td>'. $row["order_item"] .'</td>
<td>$ '. $row["order_value"] .'</td>
<td>'. $row["order_date"] .'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Order Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
Use something like this to make sure that you are getting the correct format from your datepicker:
$("#from_date").datepicker({ dateFormat: 'yy-mm-dd' }).val();
Make PHP variables to use in your query for the date:
$fromDate = !empty($_POST['from_date']) ? "'".mysqli_escape_string($_POST["from_date"])."'" : "CURDATE()";
$toDate = !empty($_POST["to_date"]) ? "'".mysqli_escape_string($_POST["to_date"])."'" : "CURDATE()";
$query =
"SELECT *
FROM tbl_order
WHERE order_date
BETWEEN $fromDate
AND $toDate";
NOTE: You should also add some logic in there to make sure that the from_date does not end up being before the to_date.
NOTE 2: This answer is making the assumption that you have not set up PDO. Always make sure to avoid SQL injection attacks in some way. Any values coming from the front end are unsafe and subject to SQL injection. PDO would be preferable, but escaping will work.
You can try casting your $_POST using CAST function to convert values to date.
$query = "SELECT * FROM tbl_order
WHERE order_date
BETWEEN CAST('".$_POST["from_date"]."' AS DATE)
AND CAST('".$_POST["to_date"]."' AS DATE)";
You can read about it on MySQLTutorial .
Also I recommend you to escape variables when working with database :-) Always expect user is up to no good.

how to save multiple ckeditor in php?

I have create a multiple ckeditor in php, it can display the panel of ckeditor correctly, but when I click update after adding something in it, it didn't save to the database.
<?php
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$id = $_POST['id'];
$content = $_POST['content'];
$query_update = "UPDATE `correspond` SET content='$content' WHERE id='$id'";
mysql_query($query_update);
header("Location: correspond.php");
}
?>
<table>
<?php while($row_correspond_result=mysql_fetch_assoc($correspond_result)){ ?>
<tr class="table table-bordered table-striped"><form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center"><div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </div>
<script>
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}});
</script>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>
</form></tr><?php }?> </tbody></table>
To save multiple ckeditor, you have need to pass the name attribute in array format. when you click on submit save the content value using the serialize function.
PHP code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["action"])&&($_POST["action"]=="update")){
$content = $id = '';
$form_data = $_POST['form_data'];
for($i=0 ; $i<count($form_data['id']); $i++){
$content = serialize($form_data['content'][$i]);
$id = $form_data['id'][$i];
$query_update = "UPDATE correspond SET content='$content' WHERE id= $id";
mysqli_query($conn, $query_update);
}
//header("Location: correspond.php");
}
?>
At the time of display unserialize content value and put in textarea field.
HTML Code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.11.4/standard/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var elements = document.getElementsByClassName( 'myContent' );
for ( var i = 0; i < elements.length; ++i ) {
CKEDITOR.replace( elements[ i ]);
//CKEDITOR.inline( elements[ i ], { /* config for this instance */ } );
}
});
</script>
<table>
<tr class="table table-bordered table-striped">
<form action="" method="POST" name="correspond_form" id="correspond_formJoin">
<tbody id="myTable">
<td colspan="3" align="center">
<?php
$sql = "SELECT id, content FROM correspond";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//get the content form database and use unserialize method
$content = unserialize($row["content"]);
?>
<!-- Change div to textarea and use the name attr as array format -->
<textarea contenteditable="true" class="myContent" name="form_data[content][]" id="content"><?php echo $content;?> </textarea>
<!-- add the corresponding id to update the content. -->
<input type="hidden" name = "form_data[id][]" value ="<?php echo $row["id"];?> ">
<?php
}
}
?>
</td>
</tr><tr>
<td colspan="2"></td>
<td align="center">
<input name="action" type="hidden" id="action" value="update">
<input type="submit" name="Submit" value="Update"></td>
</form></tr></tbody></table>
This div Converted to TextArea
From
<div contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </div>
To
<textarea contenteditable="true" class="myContent" id="content"><?php echo $row_correspond_result["content"];?> </textarea>

Passing table row element to a js

I have a bootstrap table which element are loaded from a database.
I have a js function to delete a table row from data base, so I add a button in each row of the table.
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>client</th>
</tr>
</thead>
<tbody>
<?php
require("config.php");
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_row()) {
$user_id=$row[0];
$user_name=$row[1];
?>
<tr>
<!--here showing results in the table -->
<td><?php echo $user_id; ?></td>
<td ><?php echo $user_name; ?></td>
<td>
<input type="button" class="btn btn-danger btn-xs delete" value="Cancella sin id" onclick="deleteFunction()"/>
</td>
</tr>
</tbody>
</table>
How can I pass to deleteFucntion the id or user_name in order to use them into Javascipt like this:
function deleteFunction() {
var username = #MY_ROW_USERNAME;
....
}
TD's should look like this
<td id="user_name_<?=$user_id?>" onClick="deleteFunction(<?=$user_id?>)"><?=$user_name?></td>
Delete function like this
function deleteFunction(user_id) {
var username = document.getElementById('user_name_'+user_id).innerHTML;
}

how to show data from database in textbox in php

i am new in php programming i have problem in this code, i want to show data in text box when i press select button which is in grid, but i am stuck on it because data not shown in text box and my select button also not working, what i do friends for this,
this is my code
FIRST NAME
MIDDLE NAME
LAST NAME
**--//php code--//**
$qrydatabind='SELECT ecode, first_name, middle_name, last_name, father_name, mother_name,
number_of_dependents, dob, gender, identification_mark, marital_status, spouse_name, mobile_number,
email_id, adhar_id, pan_number, passport_number, tin_number, dl_number FROM USER_MASTER ORDER BY user_id DESC
LIMIT 1';
$results= mysql_query($qrydatabind) or die(mysql_error());
while( $row = mysql_fetch_array( $results ) ) {
echo
"
<div class='table-responsive'>
<table border='1' style= 'background-color: #84ed86; color: #761a9b; ' >
<thead>
<tr>
<th></th>
<th>Entity Code</th>
<th>User Id</th> <th>User Name</th> <th>Father Name</th> <th>Mother Name</th> <th>No.Of Dependents</th>
<th>D.O.B</th> <th>GENDER</th> <th>Id Mark</th> <th>MARITAL STATUS</th> <th>SPOUSE NAME</th>
<th>Mob. Number</th> <th>E-Id</th> <th>ADHAR-ID</th> <th>PAN-No.</th> <th>PASSPORT-No.</th>
<th>TIN-NO.</th> <th>DL-No.</th>
</tr>
</thead>
<tr >
<td><button type='submit' class='btn btn-primary' name='select_button'>Select</button> </td>
<td>{$row['ecode']}</td> <td> echo $row[0];</td>
<td>{$row['first_name']} {$row['middle_name']} {$row['last_name']}</td>
<td>{$row['father_name']}</td> <td>{$row['mother_name']}</td>
<td>{$row['number_of_dependents']}</td> <td>{$row['dob']}</td>
<td>{$row['gender']}</td> <td>{$row['identification_mark']}</td>
<td>{$row['marital_status']}</td> <td>{$row['spouse_name']}</td>
<td>{$row['mobile_number']}</td> <td>{$row['email_id']}</td>
<td>{$row['adhar_id']}</td> <td>{$row['pan_number']}</td>
<td>{$row['passport_number']}</td> <td>{$row['tin_number']}</td>
<td>{$row['dl_number']}</td>
</tr> </table>
</div>";
}}
if(isset($_POST['select_button']))
{
$qrydatabind1='SELECT ecode, first_name, middle_name, last_name, father_name, mother_name,
number_of_dependents, dob, gender, identification_mark, marital_status, spouse_name, mobile_number,
email_id, adhar_id, pan_number, passport_number, tin_number, dl_number FROM USER_MASTER';
$results1= mysql_query($qrydatabind1) or die(mysql_error());
while( $row = mysql_fetch_array( $results1 ) ) {
echo'
<tr >
<td> </td>
<td><input type="text" value="{$row["first_name"]}" ></td>
</tr>';
}
}
It is very simple. as you are putting data in .
Your code
<td> echo $row[0];</td>
Text box code:
<input type="text" value="<?php echo $row[0];?>">
PHP Variables will only be evaluated in strings that are quoted in double quotes "
You should either concatinate a string:
echo '<td><input type="text" value="' . $row["first_name"] . '" ></td>';
Or, use <?php and ?> to switch between script and markup
while( $row = mysql_fetch_array( $results1 ) ) {
?><td><input type="text" value="<?php echo $row["first_name"]; ?>" ></td><?php
}
You can also use this as
echo'<tr><td><input type="text" value="'.$row["first_name"].'" ></td></tr>';

How to get the value of multiple checkbox within a while loop before submission using php?

I'm new to php and have encountered some problems with checkbox within a while loop.
I want to add checkbox to each row of a table and check if they are checked. However, the table is a result of a query and the number of output is not sure. So I want to use a while loop to get the value of each output and pass the $_SESSION['n'], and the value of each checkbox should also be linked to n; Then after the user check part of the boxes, those items are to be deleted. I have tried to do things like below but it didn't work. How can I add the checkbox and pass the value of each checkbox within the loop to next page?
<html>
<head><title>ResultCheckUpdateAsset</title></head>
<body>
<form method="post" action="Delete Items.php">
<?php
$result1 = mysqli_query($conn, $query1) ;
print"
<table border=3>
<tr>
<td><input type='checkbox' name='selectAll' value='Y' checked>Select All</td>
<th>Assets number</td>
<th>Serial number</td>
<tr>";
session_start();
$_SESSION['n'] = 0;
$n = $_SESSION['n'];
while($row = mysqli_fetch_array($result1))
{
print "<input type='checkbox' name='check[$n]' value='Y' checked='checked'></td>";
print "<th> $row[0] </td>";
print "<th> $row[1] </td>";
print "<tr>";
$_SESSION['n']++;
//$_SESSION['check'.$_SESSION['n']] = (the value of check[$n])
$_SESSION['assetNo'.$_SESSION['n']] = $row[0];
$_SESSION['serialNo'.$_SESSION['n']] = $row[1];
}
print "</table>";
print"<br>";
?>
<input type="submit" value="Delete" />
</form>
</body>
<html>
Try this and inform. U got bad syntax on HTML and PHP (all basics)
<html>
<head>
<title>ResultCheckUpdateAsset</title>
</head>
<body>
<form method="post" action="Delete Items.php">
<?php
$result1 = mysqli_query($conn, $query1);
?>
<table border=3>
<tr>
<td><input type='checkbox' name='selectAll' value='Y' checked>Select All</td>
<th>Assets number</th>
<th>Serial number</th>
<tr>
<?php session_start();
$_SESSION['n'] = 0;
$n = $_SESSION['n'];
while ($row = mysqli_fetch_array($result1)) { ?>
<td><input type='checkbox' name='check[<?= $n ?>]' value='Y' checked='checked'></td>
<th><?= $row[0] ?></th>
<th><?= $row[1] ?></th>
</tr>
<?php
$_SESSION['n']++;
//$_SESSION['check'.$_SESSION['n']] = (the value of check[$n])
$_SESSION['assetNo' . $_SESSION['n']] = $row[0];
$_SESSION['serialNo' . $_SESSION['n']] = $row[1];
$n++;
} ?>
</table>
<br>
<input type="submit" value="Delete"/>
</form>
</body>
</html>

Categories

Resources