I am using a form to search in a database and I would like to know how to display the search results in a table, on the same page (the page can refresh, I don't mind).
My form looks like this:
<form id="searchform" method="post" action = 'search4.php' target = '_blank'>
<input id="name" style="height: 25px; width: 140px; position: fixed; top: 150px; left: 50px" name="name" type="text" >
<input type="submit" value="Search" class="btn btn-primary btn" style="color: white; font-style: normal; background-color: blueviolet; position: fixed; top: 148px; left: 220px">
</form>
search4.php is the script that does the searching in the database and looks like this:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'official_db';
$mysqli = new mysqli($servername, $username, null, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if (!get_magic_quotes_gpc() ) {
$Name = addslashes($_POST['name']);
} else {
$Name = $_POST['name'];
}
session_start();
$results = "SELECT * FROM b2b_interfaces WHERE Name LIKE CONCAT ('%', $name, '%')";
$resultSet = $mysqli->query($results);
$numRows = $resultSet->num_rows;
if ($numRows > 0) {
while ($row = $resultSet->fetch_object()) {
echo "{$row->name} {$row->address} {$row->county} <br>";
}
} else {
echo "No Results";
}
?>
In the main script I also have defined a table, but I do not know how to have access to the results from search4.php. I would try something like this:
<tbody>
<?php
if ($numRows > 0) {
while ($row = $resultSet->fetch_object()) {
?>
<tr>
<td><?php echo "{$row->name} " ?></td>
<td><?php echo "{$row->address} " ?></td>
<td><?php echo "{$row->county} " ?></td>
</tr>
<?php
}
}
?>
</tbody>
You can place the search script on the same page, so target the search form to the current page, and place the script on top of the page.
Related
I'm trying to search for some data then download it as CSV file, but when I click download button to download the data I have found, it's writing all my HTML code at the beginning of the file then it writes my data in the downloaded file. So how can I get only my data without writing the html code with it?.
Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "CNG492";
$message = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html>
<head>
<title>Search By Keyword</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Upload Data Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<style>
table {
font-family: Raleway;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
body
{
background-color: #722f37;
}
.btn{
background-color: #722f37;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
.box
{
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 80%;
min-width: 300px;
}
.has-error
{
border-color:#cc0000;
background-color:#ffff99;
}
.form{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}
</style>
</head>
<body>
<div class="container box">
<br />
<h1 align="center">Search</h1><br />
<form method="post" id="search_form">
<div class="form-group">
<label>Keyword:</label>
<input type="text" name="keyword" id="keyword" class="form-control"/>
<span id="error_keyword" class="text-danger"></span>
</div>
<div align="inline">
<button type="button" name="find_keyword" id="find_keyword" class="btn btn-dark btn-lg">Find</button>
<button type="button" name="adv_search" id="adv_search" class="btn btn-dark btn-lg">Advance Search</button>
</div>
<br>
<?php
if(isset($_POST["keyword"])){
$keyword = mysqli_real_escape_string($conn,$_POST["keyword"]);
$dataset_result = -1;
//Search for keyword inside tables
$search_query = "SELECT dataset_id,title,description FROM dataset WHERE dataset_id IN (SELECT dataset_id FROM dataset WHERE title LIKE '%{$keyword}%' OR collector LIKE '%{$keyword}%' OR description LIKE '%{$keyword}%' OR d_procedure LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM group_table WHERE group_desc LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM material WHERE m_type LIKE '%{$keyword}%' OR URI LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM task WHERE type LIKE '%{$keyword}%' OR description LIKE '%{$keyword}%'
UNION DISTINCT
SELECT dataset_id FROM dataset WHERE eq_id IN (SELECT e.eq_id FROM tracker t,equipment e WHERE t.tracker_id=e.tracker_id AND (t.brand LIKE '%{$keyword}%' OR t.model LIKE '%{$keyword}%')))";
$search_result = $conn->query($search_query);
$dataset_result = mysqli_num_rows($search_result);
if ($dataset_result == 0) {
echo '
<div class="alert alert-success">
No reasults found.
</div>
';
}else{
echo '
<h4>Results</h4>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Dowload Link</th>
</tr>';
while ($row = mysqli_fetch_assoc($search_result)) {
echo '<tr>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
<td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
</tr>';
}
echo '</table>
';
if (isset($_POST["download"])) {
$d_id = $_POST["download"];
include 'download.php';
}
}
}
mysqli_close($conn);
?>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$('#find_keyword').click(function(){
var error_keyword = '';
if($.trim($('#keyword').val()).length == 0){
error_keyword = 'Enter a keyword please.'
$('#error_keyword').text(error_keyword);
$('#keyword').addClass('has-error');
}else
{
error_keyword = '';
$('#error_keyword').text(error_keyword);
$('#keyword').removeClass('has-error');
}
if(error_keyword != ''){
return false;
}else{
$('#find_keyword').attr("disabled", "disabled");
$(document).css('cursor', 'prgress');
$("#search_form").submit();
}
});
})
</script>
Download.php
<?php
//include database configuration file
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "CNG492";
$message = "";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//get records from database
$query = $connect->query("SELECT * FROM dataset");
if($query->num_rows > 0){
$delimiter = ",";
$filename = "members_" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('title', 'description');
fputcsv($f, $fields, $delimiter);
//output each row of the data, format line as csv and write to file pointer
while($row = $query->fetch_assoc()){
$lineData = array($row['title'], $row['description']);
fputcsv($f, $lineData, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
exit;
?>
The whole problem is then that you echo some html and inside it include download.php
echo '
<h4>Results</h4>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Dowload Link</th>
</tr>';
while ($row = mysqli_fetch_assoc($search_result)) {
echo '<tr>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
<td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
</tr>';
}
echo '</table>
';
if (isset($_POST["download"])) {
$d_id = $_POST["download"];
include 'download.php';
}
just put a link to the download.php instead of including it.
echo '
<h4>Results</h4>
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Dowload Link</th>
</tr>';
while ($row = mysqli_fetch_assoc($search_result)) {
echo '<tr>
<td>'.$row["title"].'</td>
<td>'.$row["description"].'</td>
<td><button type="submit" name="download" id="download" value="'.$row["dataset_id"].'">Dowload</button></td>
</tr>';
}
echo '</table>
';
if (isset($_POST["download"])) {
$d_id = $_POST["download"];
echo 'Download File';
}
If you want to redirect user after submitting form to the download.php automatically then you may use attribute action in form.
See how it is done HTML Attribute where a redirection is set to the page /action_page.php.
I have the following PHP file course.php, which I would like dompdf to render the file. However, when I try to load the external file it tells me headers already loaded.
I have tried some of the tutorials online however when I add inline php the pdf does not render appropriately.
Is there anyway possible to add an external php file?
<?php
include config.php
$course_id= JRequest::getInt('cid');
$dbname = "i2894069_jos2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT en . * , e.full_name, e.level , c.base_level, s.station
FROM enrolled_students AS en
JOIN employees AS e ON en.student = e.user_id
JOIN stations AS s ON e.station = s.id
JOIN courses_instructed AS ci ON en.pid = ci.ci_id
JOIN courses as c on ci.ci_course = c.id
WHERE en.pid =$course_id
ORDER BY e.last_name";
$result = $conn->query($sql);
?>
<style>
.table-fixed thead {
width: 97%;
}
.table-fixed tbody {
height: 230px;
overflow-y: auto;
width: 100%;
}
.table-fixed thead, .table-fixed tbody, .table-fixed tr, .table-fixed td, .table-fixed th {
display: block;
}
.table-fixed tbody td, .table-fixed thead > tr> th {
float: left;
border-bottom-width: 0;
}
</style>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h4>
Fixed Header Scrolling Table
</h4>
</div>
<table class="table table-fixed">
<thead>
<tr>
<th class="col-xs-4">Student</th><th class="col-xs-4">Station</th><th class="col-xs-4">Level</th>
</tr>
</thead>
<tbody>
<?php while($row = $result->fetch_assoc()) {
if($row['level'] == 11){
$level = 'Ambulette';
}elseif($row['level'] == 2){
$level = 'Dispatcher';
}elseif($row['level'] == 3){
$level = 'EMT';
}elseif($row['level'] == 4){
$level = 'AEMT';
}elseif($row['level'] == 5){
$level = 'Paramedic';
}elseif($row['level'] == 6){
$level = 'IT';
}elseif($row['level'] == 7){
$level = 'RN / Medic';
}
else{$level = '';}
$base_level = $row['base_level'];
$elevel = $row['level'];
if($elevel < $base_level){
$style = 'class="table-warning"';
}else{
$style = '';
}
?>
<tr>
<td class="col-xs-4"><?php echo $row['full_name'] ?></td><td class="col-xs-4"><?php echo $row['station'] ?></td><td class="col-xs-4"><?php echo $level ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
If I understand you correctly... what you're looking for is something like this:
<?php
ob_start();
require 'yourtemplate.php'; // the one you posted in your question
$html = ob_get_clean();
Now your HTML is in a variable and you can render it with DOMPDF if you want.
I am facing an issue while trying to retrieve values from the if-else condition.
My query is pasted below:
<?php
session_start();
if(!$_SESSION['login'] && !isset($_POST['submit'])) {
header("Location:LoginPage.php");
}
function filterTable($query)
{
$db_name = "id555865_sales_db";
$mysql_username = "id555865_sales_db";
$mysql_password = "password";
$server_name = "localhost";
$conn = mysqli_connect($server_name, $mysql_username,$mysql_password,$db_name);
$filter_result = mysqli_query($conn,$query);
return $filter_result;
}
if(isset($_POST['submit']) && isset($_POST['fromDate']) && isset($_POST['toDate']) && isset($_POST['userName']) )
{
$from_date = $_POST['fromDate'];
$to_date = $_POST['toDate'];
$name = $_POST['userName'];
if(isset($from_date) && isset($to_date) && isset($name)) {
$query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details WHERE date BETWEEN '$from_date' AND '$to_date' AND name LIKE'$name';";
$search_result = filterTable($query);
}
}
elseif(empty($_POST['userName']) && !empty($_POST['fromDate']) && !empty($_POST['toDate'])) {
$from_date = $_POST['fromDate'];
$to_date = $_POST['toDate'];
$query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details WHERE date BETWEEN '$from_date' AND '$to_date';";
$search_result = filterTable($query);
}
elseif(!empty($_POST['userName']) && empty($_POST['fromDate']) && empty($_POST['toDate'])) {
$name = $_POST['userName'];
$query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details WHERE name LIKE'$name';";
$search_result = filterTable($query);
}
else
{
$query = "SELECT name,date,enquiry,retail,collection,booking,evaluation,test_drive,home_visit FROM employee_details;";
$search_result = filterTable($query);
}
$now = time();
if (($now - $_SESSION['start'] > 600) && (isset($_POST['submit']))){
session_destroy();
echo "Session expired.Please Login again.";
header("Location:LoginPage.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
input,input[type='text']
{
border:1px solid black;
padding:5px 5px;
border-radius:4px;
font-size:12px;
}
table {
font-family: 'Roboto', sans-serif;
font-weight:400;
font-size:16px;
border-collapse: collapse;
width: 80%;
text-align:center;
margin:auto;
}
td, th {
font-family: 'Roboto', sans-serif;
font-weight:400;
font-size:12px;
border: 1px solid #dddddd;
text-align:center;
padding: 5px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.headingstyle
{
font-family: 'Roboto', sans-serif;
font-weight:400;
font-size:14px;
text-align:center;
}
</style>
</head>
<body>
<div class="container;">
<h2 class="headingstyle">Sales App Data</h2>
<form action="https://pranami.000webhostapp.com/salesApp.php" method="post">
<div class="headingstyle">
<label class="headingstyle">From Date:</label>
<input type="text" name="fromDate" placeholder="YYYY-MM-DD" id="datepicker">
<label class="headingstyle" style="margin-left:20px;">To Date:</label>
<input type="text" name="toDate" placeholder="YYYY-MM-DD" id="datepicker">
<label class="headingstyle" style="margin-left:20px;">Name:</label>
<input type="text" name="userName">
<input style="margin-left:20px; background-color:#16367F; font-family:'Roboto', sans-serif;font-weight:400;font-size:14px;color:#ffffff; padding:5px 8px; " type="submit" name="submit" value="Submit">
</div><br/><br/>
<table>
<tr>
<th>Name</th>
<th>Date</th>
<th>Enquiry</th>
<th>Retail</th>
<th>Collection</th>
<th>Booking</th>
<th>Evaluation</th>
<th>Test Drive</th>
<th>Home Visit</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['name'];?> </td>
<td><?php echo $row['date'];?> </td>
<td><?php echo $row['enquiry'];?> </td>
<td><?php echo $row['retail'];?> </td>
<td><?php echo $row['collection'];?> </td>
<td><?php echo $row['booking'];?> </td>
<td><?php echo $row['evaluation'];?> </td>
<td><?php echo $row['test_drive'];?></td>
<td><?php echo $row['home_visit'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
The problem is in the if-else part. I have a HTML form which has 3 input fields and as the user gives values in the input fields,after clicking the submit button, the data will be retrieved from the MySQL Database and shown in a table. If the user inputs data in all the 3 fields and clicks the submit button, the data is retrieved correctly from the database. But what I wanted is that if the user doesnot give any value for the "Name" field, then all the data should be retrieved according to the data value that is given. Or if the user gives value only for the "Name" field, then the data should be retrieved for only the given Name.I mentioned those conditions in the elseif part of the PHP Script,but the elseif part is never executed.It doesnot return any value.The table is empty in those cases.
Can anyone please help me with this issue?
isset simply checks if the field is present or not. It does not check whether the field is empty. You can use empty() to check if user enter something in the field or not
Also text box, text area etc sets an empty value when you submit form
if a value is set but its value is '0' when you try to check if it is check it will be true, so you should use empty() function to check this, however it's better if you optimise your 'if structure'
if (empty($name))
this will return true if name is empty
No need to check isset() here. Because from your code all the three fields post values every time you submit the page. For that only your code always executes first if condition. So change isset() code to empty() code.
your code is like
if(isset($_POST['submit']) && isset($_POST['fromDate']) && isset($_POST['toDate']) && isset($_POST['userName']))
{
......
}
elseif(empty($_POST['userName']) && !empty($_POST['fromDate']) && !empty($_POST['toDate']))
{
......
}
elseif(!empty($_POST['userName']) && empty($_POST['fromDate']) && empty($_POST['toDate']))
{
......
}
else
{
......
}
Change your code to like this below
if(!empty($_POST['submit']) && !empty($_POST['fromDate']) && !empty($_POST['toDate']) && !empty($_POST['userName']))
{
......
}
elseif(empty($_POST['userName']) && !empty($_POST['fromDate']) && !empty($_POST['toDate']))
{
......
}
elseif(!empty($_POST['userName']) && empty($_POST['fromDate']) && empty($_POST['toDate']))
{
......
}
else
{
......
}
It will works. Hope this code will helps you.
I have added update and delete button in the same form using following codes. Deletion is working perfectly. But updating is again not taking the value of "id".
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dp = "tool";
$dp= new mysqli($servername, $username, $password, $dp) or die("Unable to connect");
//echo"Great work";
?>
<!DOCTYPE html>
<html>
<head>
<title>registration</title>
<meta charset="UTF-8">
<link href="site.css" rel="stylesheet">
<div align="center">
<link rel="stylesheet" href="mine.css"/>
<table border="0" align="center" style="border-spacing: 40px 20px;">
<align="center"> <td>
</head>
<body bgcolor=" #b3ffe0">
<style>
html {
font-family: "Lucida Sans", sans-serif;
}
ul li {display: block;position: relative;float: left;border:1px }
ul li a {display: block;text-decoration: none; white-space: nowrap;color: #fff;}
ul {
list-style-type: none;
padding: 2px ;
margin-left: auto;
background-color: #666;
}
li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 10px 20px;
text-decoration: none;
}
li a:hover, .dropdown:hover .dropbtn {
background-color: #111;
}
</style>
</head>
<body>
<form method="post">
<ul>
<li><a class="active" href="df1.php">Disease</a></li>
<li><a href="drug.php" >Drug</a></li>
<li>Interaction</li>
Alternate Drug
</ul>
<?php
$query = "SELECT * FROM disease;";
$result = mysqli_query($dp, $query);
echo "<table border=5>
<tr>
<th>Disease ID</th>
<th>Disease</th>
<th>Sub Disease</th>
<th>Associated Disease</th>
<th>Ethinicity</th>
<th>Source</th>
<th>Edit</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row{'id'}."</td>";
echo "<td>".$row{'Disease'}."</td>";
echo "<td>".$row{'SubDisease'}."</td>";
echo "<td>".$row{'Associated_Disease'}."</td>";
echo "<td>".$row{'Ethinicity'}."</td>";
echo "<td>".$row{'Source'}."</td>";
echo "<td><input type='radio' name='id' value='".$row[id]."'></td>";
echo "</tr>";}
echo "</table>";
// $selectedRow=$_POST['id'];
?>
<div>
<table border="0" align="center" style="border-spacing: 40px 30px;">
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="4" WIDTH="40%">
</br><center>
<button style="color: red">Add</button>
<input type = 'submit' value = 'Update' name = 'submitupdate'>
<input type = 'submit' value = 'Delete' name = 'submitdelete'>
</center></TABLE>
<?php
if(isset($_POST[submitupdate]))
{
header ("Location: http://localhost/card/edit3.php");
}
if ($_POST[submitdelete])
{
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
//
$sql="DELETE FROM disease WHERE id=".$_POST['id'];
echo "Data deleted successfully";
mysqli_query($conn, $sql);
mysqli_close($conn);
}
?>
</body>
</html>
Edit3.php
<?php
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$query = "SELECT * FROM disease where id=".$_POST['id'];
$result = mysqli_query($conn, $query);
$count= mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
echo $count;
?>
<form action="update.php" method="post">
<input type="hidden" value="<?php echo $row['id'];?>" name="id"/>
Disease (ICD10) <select id= "Disease" name="Disease">
<option value="Certain infectious and parasitic diseases">Certain infectious and parasitic diseases</option>
<option value="Neoplasms">Neoplasms</option>
<option value="Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism ">Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism</option>
SubDisease<input type="text" name="SubDisease" value="<?php echo $row['SubDisease'];?>"/>
Associated Disease<input type="text" name="Associated_Disease" value="<?php echo $row['Associated_Disease'];?>"/>
<td>Ethinicity<input type="text" list="Ethinicity" id="color" name="Ethinicity" value="<?php echo $row['Ethinicity'];?>" style="width:100px;">
<datalist id="Ethinicity">
<option value="Indian">
<option value="American">
<option value="Srilankan">
</datalist>
</td>
Source<input type="text" name="Source" value="<?php echo $row['Source'];?>"/>
<input type="submit" value="update">
</form>
update.php
<?php
$conn = mysqli_connect('localhost','root','','tool');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_error());
}
$disease = $_POST['Disease'];
$SubDisease = $_POST['SubDisease'];
$Associated_Disease = $_POST['Associated_Disease'];
$Ethinicity = $_POST['Ethinicity'];
$Source = $_POST ['Source'];
$id = $_POST ['id'];
$update= "Update disease set Disease='".$disease."', SubDisease='".$SubDisease."', Associated_Disease='".$Associated_Disease."', Ethinicity='".$Ethinicity."', Source='".$Source."' where id=".$_POST["id"];
if(!mysqli_query($conn,$update))
echo mysqli_error;
?>
And drop down of Disease, is also not getting reading the databse value and not getting display in the editing page.
I have student table which has student login information like id number , pincode and their detail.
The students id is like: 0123/08 pincode is: 1234
The working condition:
For example when the student is login without slash 0134 and pincode, then the data is fetched successfully.Which means when 0134 id is available.
The problem:
when the student is login with backslash and existing id 0123/08 and pincode, then the student can log but the data is not fetched.
can any one solve the problem:
<?php session_start(); ?>
<html>
<head>
<title>Login</title>
<style type="text/css">
h3{font-family: Calibri; font-size: 22pt; font-style: normal; font-weight: bold; color:SlateBlue;
text-align: center; text-decoration: underline }
table{font-family: Calibri; color:white; font-size: 11pt; font-style: normal;
text-align:; background-color: Silver; border-collapse: collapse;
border: 2px solid navy; float: left;
margin-left: 25%;
margin: 10%; }
table.inner{border: 0px}
</style>
</head>
<body>
<?php
include("db.php");
if(isset($_POST['submit'])) {
//Start session
//Include database connection details
require_once('db.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect("localhost", "root", "");
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
// $db = mysql_select_db("cbe");
//if(!$db) {
// die("Unable to select database");
// }
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$login = clean($_POST['student_id']);
$password = clean($_POST['pincode']);
//Input Validations
if($login == '') {
$errmsg_arr[] = 'Login ID missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
//if($errflag) {
// $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
// session_write_close();
// header("location: login.php");
// exit();
//}
//Create query
$qry="SELECT * FROM student WHERE stud_id='$login' AND stud_pincode='$password'";
$result = mysqli_query($db,$qry) or die("Error: ".mysqli_error($db));
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(is_array($row) && !empty($row)) {
$_SESSION['name'] = $row['stud_fname'];
$_SESSION['id'] = $row['stud_id'];
echo $row['stud_id'];
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
header("location: index.php");
exit();
}else {
echo "Invalid username or password.";
echo "<br/>";
echo "<a href='login.php'>Go back</a>";
}
if(isset($_SESSION['id'])) {
header('Location: index.php');
}
}
else {
?>
<p><font size="+2">Login</font></p>
<form name="form1" method="POST" action="">
<table width="75%" border="0">
<tr>
<td width="15%">ID Number:</td>
<td><input type="text" name="student_id" ></td>
</tr>
<tr>
<td width="15%">Student PIN:</td>
<td><input type="password" name="pincode"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Submit"></td>
<td> </td>
</tr>
<tr><td>Not registered? </td>
<td><a href=/cbe/RegisterStudent.html>Reister Now!</a></td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
specially this things from above code will have any problem?
//Sanitize the POST values
$login = clean($_POST['student_id']);
$password = clean($_POST['pincode']);
$qry="SELECT * FROM student WHERE stud_id='$login' AND stud_pincode='$password'";
$result = mysqli_query($db,$qry) or die("Error: ".mysqli_error($db));
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(is_array($row) && !empty($row)) {
$_SESSION['name'] = $row['stud_fname'];
$_SESSION['id'] = $row['stud_id'];
echo $row['stud_id'];
header("location: index.php");
exit();
}
The php file which fetches the data:
<?php
$query = "SELECT * FROM student WHERE stud_id=".$_SESSION['id']." ORDER BY id DESC";
if ($result = $db->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["stud_fname"], $row["stud_lname"]);
echo "<tr>";
echo "<td>". $row['stud_id']."</td>";
echo "<td>". $row['stud_fname']."</td>";
echo "<td>". $row['stud_lname']."</td>";
echo "<td>". $row['stud_gfname']."</td>";
echo "<td>". $row['stud_gender']."</td>";
echo "<td>". $row['stud_dep']."</td>";
echo "<td>Edit </td>";
//Delete Code: Delete
}
/* free result set */
$result->free();
}
?>
Your clean() function is using stripslashes() which - as the name of the function says - strips slashes from your input data, leading to 0123/08 becoming 012308 in the internal comparison.
For a quick fix, remove the stripslashes() call; it serves to purpose anyway. You could arguably get rid of the entire clean() function and just use mysql_real_escape_string() instead.
For a proper fix, consider using prepared statements, an approach to safely handling incoming data that makes it much more difficult to screw things up.