PHP if-else condition not working - php

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.

Related

Display search results on the same page in a table with PHP

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.

Backslash or forwardslash with login id is preventing successful data fetching in php?

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.

Admin / Member login PHP not redirecting

I am building a login system where there is a member and a user. I have a table that has a column of name, username, password, email and type. Type designates the type of user. I have created already a working log-in form. My problem is every time I try to log in it does not redirect to the designated page. It stays on the same page but gives me a blank page. I've been figuring out what is wrong with the code. Can someone help me ?
Thank you.
PHP Login code:
<?php
include 'try_connect.php';
if (isset($_POST['login'])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$hsl = mysql_query("SELECT name, username, password, type FROM users WHERE username='$user' and password='$pass'");
$data = mysql_fetch_array($hsl);
$username = $data['username'];
$password = $data['password'];
$type = $data['type'];
$name = $data['name'];
if ($user==$username && $pass==$password) {
session_start();
$_SESSION['name']=$name;
if ($type =='admin') {
header('Location: try_admin.php');
}
elseif ($type =='user') {
header('Location:try_user.php');
}
}
}
?>
LOG IN FORM
<form action="try_login.php" method="POST">
<table style="margin-left: 30%; margin-bottom: 1%;">
<tr>
<th style="font-family: Arial; line-height: 5px;">Username:</th>
<td><input type="text" name="username" style="margin-left: 10%; width: 120%; margin-bottom: 5%;"></td>
</tr>
<tr>
<th style="font-family: Arial;">Password:</th>
<td><input type="password" name="password" style="margin-left: 10%; width: 120%; margin-bottom: 0%; margin-top: 10%;"></td>
</tr>
</table>
<input type="submit" value="login" name="login" style="background-color: black; color: white; margin-bottom: 5%; margin-top: 0%; margin-left: 59%; border-color: #89cff0; border-style: double solid;">
Try this:
<?php
include 'try_connect.php';
if (isset($_POST['login'])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$hsl = mysql_query("SELECT name, username, password, type FROM users WHERE username='$user' and password='$pass'");
$data = mysql_fetch_array($hsl);
$username = $data['username'];
$password = $data['password'];
$type = $data['type'];
$name = $data['name'];
if ($user==$username && $pass==$password) {
session_start();
$_SESSION['name']=$name;
if ($type =='admin') {
header("Location: try_admin.php");
}
elseif ($type =='user') {
header("Location:try_user.php");
}
}
}
?>
Use exit() after header(). exit() will terminate your script immediately.
if ($type =='admin') {
header('Location: try_admin.php');
exit();
}
elseif ($type =='user') {
header('Location:try_user.php');
exit();
}
Also make sure your header() function is called before any html output even before <html> tag

Fill table from input from mysql

I have an input, in which a code is entered and filled the table below with information from mysql optenida, the question is that I want every time a code is entered, the table all the data is added (without deleting the previous ). I got the idea to do with Ajax, but do not know where to start. So you see there is an easier way that I'm not seeing (finding on google). I do not like to add this data to a table, I would like it to be temporarily (until the table is confirmed, will be added to the db).
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table>
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
require ("conectar.php");
$_SESSION["codigo"] = $_POST["input_codigo"];
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
?>
</table>
</body>
</html>
Maybe something like this i write below.
Added jQuery and Ajax request to get the data and then add it to the table.
Changed the PHP a little so that the main HTML is not returned if it is and AJAX request.
Hope it works for you (i didnt test it).
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
$bAjaxRequest = false;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$bAjaxRequest = true;
}
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="post" id="frmQuery" name="frmQuery">
<input type="text" name="input_codigo" id="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table id="tblData" name="tblData">
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
} // end if(!$bAjaxRequest) {
// we are always going to return the TR's or ""
require ("conectar.php");
// ALWAYS, BUT ALWAYS VERIFY/VALIDATE USER INPUT!!!
$_SESSION["codigo"] = mysql_real_escape_string($_POST["input_codigo"]); // for example
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) { ?>
</table>
<script type="text/javascript">
function loadData(codigo) {
$.post( "index.php", { input_codigo: codigo }, function( data ) {
$("#tblData").append(data);
});
}
$(function() {
// jQuery POST are never cached, but if you change to GET you'll need this next line
//$.ajaxSetup ({ cache: false });
$("#frmQuery").submit(function(e) {
e.preventDefault();
loadData($("#input_codigo").val());
});
});
</script>
</body>
</html>
<?php
}
?>

login page wont log in

I am getting a problem where my login details wont let me log into my page :(
so my set up page is
<?php
$db = mysql_connect("$host", "$dblogin", "$dbpassword");
mysql_select_db("$dbname");
$res = mysql_query("SELECT * FROM userdb WHERE email='$email'");
$playerinfo = mysql_fetch_array($res);
$date2 = date("H:i");
function error($type)
{
if($type == "field")
{
echo '<body link="#FFFFFF" vlink="#FFFFFF" alink="#FFFFFF" bgcolor="#000000" text="#FFFFFF">';
echo '<p align=center><font color="red">You have left fields blank. Please relogin</font></center></p>';
}
elseif($type == "password")
{
echo '<p><center><font color="red">Incorrect password. Please relogin</font></center></p>';
}
}
echo '</body>';
?>
my login page is
<body link="#FFFFFF" vlink="#FFFFFF" alink="#FFFFFF" bgcolor="#000000" text="#FFFFFF">
<p align="center">
<img border="0" src=logo.jpg></img></p>
<p align="center">
<form action=check.php method=post>
<p align="center"><font size=1><b><font face="Tahoma" size="2">Login.</font></b><br><br>
<samp style="font-weight: normal; font-size: 7pt; font-family: tahoma"><font face="Tahoma" size="2"><b>Email -</fomt></b></font></samp><font face="Tahoma" size="2"><b>
<input type="text" name="email" size="20" style="border: 1px solid black">
</b></font></font><font face="Tahoma" size="2">
<br>
<samp style="font-weight: normal; font-size: 7pt; font-family: tahoma">
<b><font face="Tahoma" size="2">Pass -</font></b></samp><b><font size="1" face="Tahoma"><input type="password" name="password" size="20" style="border: 1px solid black"></font></b><br><input type="submit" value="Log In" style="border: 1px solid black">
<br>
</form>
</body>
and my check.php page is
<?
session_start();
include("setup.php");
if(!$email || !$password) {
error("field");
exit();
}
if($password == $info['password']) {
session_register("password");
session_register("email");
include("top.php");
echo "<p><b><center>Welcome</center></b></p>";
echo "<p><u><b>Members Area</b></u></p>";
echo "<p><center>- <b><a href=>Page</a></b> -</center></p>";
echo "<p><center>- <b><a href=logout.php>Log Out</a></b> -</center></p>";
include("bottom.php");
}
else
{
error("password");
}
?>
I always get a error of You have left fields blank. Please relogin from my index page so I cannot get my user to log in
where have I failed?
I think you have not even set your variables :D That is why it is saying "You have left fields blank"
session_start();
include("setup.php");
After this include
$email = $_POST["email"];
$password = $_POST["password"];
Besides this : Use prepared statements to avoid SQL Injection
The problem may be this:
$db = mysql_connect("$host", "$dblogin", "$dbpassword");
I think you meant:
$db = mysql_connect("{$host}", "{$dblogin}", "{$dbpassword}");
You cannot include variables into a string without the {}.
But even in that case, you need to define those varaibles before this line.
$host = "ipaddress";
Also, once you get beyond that, you are treating strings as booleans:
if(!$email || !$password)

Categories