Updating SQL database from a dropdown using PHP script - php

I am just self-learning PHP and SQL. This question seems repetitive, but I cannot find exact solution for my problem.
I have a SQL database for inventory management of mobile phones. I have implemented PHP script to display the database contents in a table. I have to further enhance the script, so the user can change the status of the mobile phone such as Working or Not working. For this I have created another SQL database storing this info. I am able to display the details in a dropdown, but when I change from Working to Not working and select Submit button, no change is seen in the database and also in the web server.
<?php
$servername="localhost";
$username="root";
$password="XXXXX";
$dbname="inventory_db";
//Connection
$conn =mysqli_connect($servername,$username,$password);
$db_handle = $conn->select_db($dbname);
//Connection check
if($conn->connect_error)
{
die("Connection failed:" .$conn->connect_error);
}
else {
echo "connection setup";
}
if($db_handle)
{
$sql="SELECT asset_no,asset_name,current_holder,location,status FROM Phone_table ";
$sql_status="SELECT idstatus,status_name FROM status_table";
?>
<!DOCTYPE html>
<HTML>
<HEAD>
<STYLE>
.asset_table
{
width: 100%;
border :1px solid black;
}
td{
text-align: left;
padding: 15px;
border: 1px solid black;
}
th{
border: 1px solid black;
}
</STYLE>
</HEAD>
<BODY>
<form method="post">
<TABLE class="asset_table">
<TR>
<TH>Asset Number</TH>
<TH>Asset Name</TH>
<TH>Asset Holder</TH>
<TH>Location</TH>
<TH>Status</TH>
</TR>
<?php
$result=$conn->query($sql);
$count=mysqli_num_rows($result);
if($result->num_rows > 0)
{
while($row=$result->fetch_assoc())
{?>
<TR>
<TD> <?php echo $row['asset_no']; ?> </TD>
<TD> <?php echo $row['asset_name']; ?></TD>
<TD> <?php echo $row['current_holder']; ?></TD>
<TD> <?php echo $row['location']; ?></TD>
<TD><select>
<?php
<!-- *****This is where I am stuck*****-->
$result_status=$conn->query($sql_status);
if($result_status->num_rows > 0)
{
while($row_status=$result_status->fetch_assoc())
{ ?>
<option value =' <?php echo $row_status['idstatus']?> '>
<?php echo $row_status['status_name'];?> </option>
<?php $row['status']=$row_status['status_name'];
}} ?></select>
</TD>
</TR>
<?php
}}?>
<input type="submit">
</form>
<?php
if($submit)
{
for($i=0;$i<$count;$i++)
{
$sql="UPDATE Phone_table SET status='$status[$i]' WHERE asset_no='$asset_no[$i]'";
$result=$conn->query($sql);
}
}
?>
</TABLE>
</BODY>
</HTML>
<?php }
ob_end_flush(); ?>

One problem with the existing code is that there was no way to relate the submitted value for the asset status ( even if it had been given a name! ) to the particular record in the database. The update statement would require, usually, an ID in the where clause so that the releveant record can be updated as opposed to ALL records being updated equally. To that end, given the HTML structure and generaly approach ( no javascript & single form ) using a hidden input field for each row in the table to hold the record ID seems to make sense. When the form is submitted the value for the select menu and the id should be relatable - you will see by the demo below.
Because there is a single form with multiple records the select menu and the hidden input will need to be treatable as arrays - that is to say their names should be of the form name[]
Another thing to note perhaps is the use of variables directly within the sql. This practise leaves your code vulnerable to sql injection and whilst this may be on a closed system somewhere with trusted users etc you never know what might happen!
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
/* connect to the db */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'inventory_db';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* declare the sql statements for later use */
$sql=(object)array(
'phones' => 'select `asset_no`, `asset_name`, `current_holder`, `location`, `status` from `phone_table`',
'status' => 'select `idstatus`, `status_name` from `status_table`',
'update' => 'update `phone_table` set `status`=? where asset_no=?'
);
/* very basic utility function to generate select menu */
function createselect( $name, $data, $value ){
$html=array();
$html[]=sprintf( '<select name="%s">', $name );
foreach( $data as $id => $status ){
$selected = $id == $value ? ' selected=true' : '';
$html[]=sprintf('<option value="%s"%s>%s', $id, $selected, $status );
}
$html[]='</select>';
return implode( PHP_EOL, $html );
}
/* query database to get possible status values which are used to create the SELECT menus */
$status=array();
$results=$db->query( $sql->status );
if( $results ){
while( $rs=$results->fetch_object() )$status[ $rs->idstatus ]=$rs->status_name;
}
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* using `user supplied data` - use a prepared statement to be safe! */
$stmt=$db->prepare( $sql->update );
$stmt->bind_param( 'ii', $assetstatus, $assetid );
/* Perform the update */
foreach( $_POST['id'] as $i => $assetid ){
$assetstatus = $_POST['status'][ $i ];
$stmt->execute();
}
$stmt->close();
exit( header( 'Location: ?db=updated' ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Asses or Assets?</title>
<style>
body{font-family:verdana}
table{ width: 100%; border :1px solid black; }
td{ text-align: left; padding: 15px; border: 1px solid black;text-align:center; }
th{ border: 1px solid black; }
input,select{padding:1rem;width:100%}
</style>
</head>
<body>
<?php
/* get the phones... no user input so no need for prepared statement */
$results = $db->query( $sql->phones );
if( $results ){
?>
<form method='post'>
<table>
<thead>
<tr>
<th>Asset Number</th>
<th>Asset Name</th>
<th>Asset Holder</th>
<th>Location</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
while( $rs = $results->fetch_object() ){
printf(
"<tr>
<td>%s<input type='hidden' name='id[]' value='%d' /></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>",
$rs->asset_no,
$rs->asset_no,
$rs->asset_name,
$rs->current_holder,
$rs->location,
createselect( 'status[]', $status, $rs->status )
);
}
?>
</tbody>
<tfoot>
<tr>
<td colspan=5>
<input type='submit' />
</td>
</tr>
</tfoot>
</table>
</form>
<?php
}//close `if`
?>
</body>
</html>

In general the form creation/display and the acting upon the submitted form are two entirely unrelated HTTP requests.
You have to change a few things to get your script to work:
1. Add a hidden field for each asset no.:
<TD>
<input type="hidden" name="asset_no[]" value="<?php echo $row['asset_no']; ?>">
<?php echo $row['asset_no']; ?>
</TD>
2. Add name attribute to your select fields:
<TD><select name="asset_status[]">
3. Make your select fields preselect the current status and remove the whitespace in the value:
<option value ='<?php echo $row_status['idstatus'] ?>' <?= $row['status'] == $row_status['idstatus'] ? ' selected' : '' ?>>
4. Remove this statement, as it does nothing (you're not writing to the array you read from the database):
$row['status']=$row_status['status_name'];
5. Add a name property to your submit field:
<input type="submit" name="submit">
6. Read your submitted form from the superglobal array $_POST (see php.net):
if(isset($_POST['submit']))
{
for($i=0;$i<count($_POST['asset_no']);$i++)
{
$asset_status = mysqli_real_escape_string($conn, $_POST['asset_status'][$i]);
$asset_no = mysqli_real_escape_string($conn, $_POST['asset_no'][$i]);
$sql = "UPDATE Phone_table SET status='$asset_status' WHERE asset_no='$asset_no'";
$result = $conn->query($sql);
}
}

Related

Style is not being applied except for the first row from sql query in html code

I'm retrieving all the rows from sql database through a query, and i'm using a loop to get all the rows
I have a style.css file which i'm specifying a style for the , however, only the first row is receiving the style and the style is not being applied to the rest.
<!DOCTYPE html>
<html>
<link href="styles.css" rel="stylesheet">
<head>
<title>IIACSS search center</title>
</head>
<body>
<form method="post">
<label>Search</label>
<input type="text" name="search">
<input type="submit" name="submit">
</form>
<?php
$con = new PDO("mysql:host=localhost;dbname=data",'root','admin123');
if (isset($_POST["submit"])) {
$str = $_POST["search"];
$sth = $con->prepare("SELECT * FROM `questions` WHERE question LIKE '%$str%'");
$sth->setFetchMode(PDO:: FETCH_OBJ);
$sth -> execute();
?>
<table>
<tr>
<th>Project</th>
<th>Question</th>
<th>Sample</th>
</tr>
<?php
for ($a=0;$row = $sth->fetch();$a++) {
?>
<tr>
<td><?php echo $row->Proj_Name; ?></td>
<td><?php echo $row->Question;?></td>
<td><?php echo $row->sample;?></td>
<br><br>
</tr>
</table>
<?php
}
}
?>
body {
background-color: white;
}
h1 {
color: black;
}
td {
color: black;
font-family: sans-serif;
}
th {
color: blue;
font-family: sans-serif;
}
It is not a CSS problem, it is because you are closing your </table> in the loop, so it is ending your table after the first tr.
Just remove it from the loop:
<?php
$con = new PDO("mysql:host=localhost;dbname=data",'root','admin123');
if (isset($_POST["submit"])) {
$str = $_POST["search"];
$sth = $con->prepare("SELECT * FROM `questions` WHERE question LIKE '%$str%'");
$sth->setFetchMode(PDO:: FETCH_OBJ);
$sth -> execute();
?>
<table>
<tr>
<th>Project</th>
<th>Question</th>
<th>Sample</th>
</tr>
<?php
for ($a=0;$row = $sth->fetch();$a++) {
?>
<tr>
<td><?php echo $row->Proj_Name; ?></td>
<td><?php echo $row->Question;?></td>
<td><?php echo $row->sample;?></td>
<br><br>
</tr>
<?php
} ?>
</table>
<?php }
?>

PHP website search

I'm having trouble getting my php search project working properly, having followed a guide, I don't fully understand the guide/code. My search bar will allow me to search for jobs in the database, but currently it shows all jobs and filters the one you search.
Is it possible to display these jobs as links, where it will take you to another page and display the currently selected job.
Here is my current code:
<?php
require 'config.php';
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="submit" value="Search"><br><br>
<table>
<tr>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['budget'];?></td>
<td><?php echo $row['duedate'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Your problem is this line:
if(isset($_POST['search']))
There's no variable called "search" which will be submitted by your form, so its value will never be set, and this if block will never be entered. I suspect you've confused the "name" attribute which determines the variable's name in the POST array, with its value ("Search", in the case of your button). Try
if(isset($_POST['submit']))
instead.
See also my comments above about your security problems and aim to fix those a.s.a.p.

How to display error message when nothing matches with the database?

This is my code. But I have a problem.
if ($kundevor!="" or $kundenach!="")
{
if ($kundevor=="")
{
$kundezusatz=" WHERE Nachname LIKE '$kundenach%'";
}
else if ($kundenach=="")
{
$kundezusatz=" WHERE Vorname LIKE '$kundevor%'";
}
else
{
$kundezusatz=" WHERE (Vorname LIKE '$kundevor%') OR (Nachname LIKE '$kundenach%')";
}
$sql = $dbh->prepare ("SELECT Nachname, Vorname FROM tblkunden $kundezusatz ");
$sql->execute() or die("SQL Fehler in: ".$sql->queryString." <br /> ".$sql->errorInfo()[2]);
echo "<table>";
echo '<p class="abfrage2">Abfrage 3:</p>';
echo"<tr><th>Nachname</th><th>Vorname</th></tr>";
while($ds = $sql->fetch())
{
echo "<tr><td>$ds[Nachname]</td><td>$ds[Vorname]</td></tr>";
}
}
If someone for example types a letter into my form which is neither like the "Vorname" (= first name) nor like the "Nachname" (= last name) it displays nothing. But I want to have a message like "Sorry, but none of your letters match with the Names in the database".
How can you achieve that in this code?
A remark: Your statement preparation is wrongly applied and looses its purpose: to avoid sql injection. No values should be directly passed into the sql statement. Instead, parameter markers (named or not) should be defined in the statement - as placeholders. For each of these markers the corresponding value must be passed either by calling the bindValue method, or the bindParam method, or by defining it as an element value in an array passed directly as argument to the PDOStatement::execute method.
Some suggestions:
You might also want to read this and this articles on how to apply error/exception handling and this article on applying prepared statements.
Avoid creating html code from PHP. Separate the php code from the html code.
Instead of mixing db fetching code with html code (like you did with while($ds = $sql->fetch()){...}), you should fetch all db data into an array (in the php code part) and iterate through it further (in the html code part).
Below is a code version in which I implement a solution to your task/question. I used my own naming/coding conventions (inclusive for the db table) though - so, as I would apply them in my own project.
Since you didn't specified which library you are using (PDO or mysqli) and because only PDO has the PDOStatement::errorInfo method, I deducted that you are using the PDO library. Therefore, my code uses PDO.
kunden.php
<?php
require 'connection.php';
if (isset($_POST['submit'])) {
$nachname = isset($_POST['nachname']) ? $_POST['nachname'] : '';
$vorname = isset($_POST['vorname']) ? $_POST['vorname'] : '';
if (empty($nachname) && empty($vorname)) {
$errors[] = 'Please provide either the first name, or the last name, or both.';
}
if (!isset($errors)) {
// Array used for creating the WHERE conditions in the sql statement.
$whereConditions = [];
/*
* Used for injecting the proper values for the named parameter markers found
* in the sql statement. It is passed as argument to the PDOStatement::execute method.
*/
$inputParameters = [];
if (!empty($nachname)) {
$whereConditions[] = 'nachname LIKE :nachname';
$inputParameters[] = '%' . $nachname . '%';
}
if (!empty($vorname)) {
$whereConditions[] = 'vorname LIKE :vorname';
$inputParameters[] = '%' . $vorname . '%';
}
$sql = sprintf(
'SELECT kunde_id, nachname, vorname FROM kunden WHERE %s'
, implode(' OR ', $whereConditions)
);
$statement = $connection->prepare($sql);
$statement->execute($inputParameters);
$kunden = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!$kunden) {
$errors[] = 'No clients found for your request.';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nachname').focus();
});
</script>
<style type="text/css">
body {
padding: 30px;
}
label {
/*display: block;*/
font-weight: 400;
}
input[type="text"] {
display: block;
margin-bottom: 20px;
}
button {
display: block;
padding: 7px 10px;
background-color: #8daf15;
color: #fff;
border: none;
}
.messages {
margin-bottom: 20px;
}
.messages .error {
color: #c00;
}
.kunden-list {
margin-top: 20px;
border-collapse: separate;
}
.kunden-list thead th {
padding: 10px;
background-color: #ccc;
}
.kunden-list tbody td {
padding: 10px;
}
</style>
</head>
<body>
<div class="messages">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
?>
<div class="error">
<?php echo $error; ?>
</div>
<?php
}
}
?>
</div>
<div class="form-container">
<form action="" method="post">
<label for="nachname">Nachname:</label>
<input type="text" id="nachname" name="nachname" value="<?php echo isset($nachname) ? $nachname : ''; ?>">
<label for="vorname">Vorname:</label>
<input type="text" id="vorname" name="vorname" value="<?php echo isset($vorname) ? $vorname : ''; ?>">
<button type="submit" name="submit" value="submit">
Senden
</button>
</form>
</div>
<?php
if (isset($kunden) && $kunden) {
?>
<table class="kunden-list">
<thead>
<tr>
<th>ID</th>
<th>Nachname</th>
<th>Vorname</th>
</tr>
</thead>
<tbody>
<?php
foreach ($kunden as $kunde) {
$kundeId = $kunde['kunde_id'];
$nachname = $kunde['nachname'];
$vorname = $kunde['vorname'];
?>
<tr>
<td><?php echo $kundeId; ?></td>
<td><?php echo $nachname; ?></td>
<td><?php echo $vorname; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
connection.php
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'yourDb');
define('USERNAME', 'yourUser');
define('PASSWORD', 'yourPassword');
define('CHARSET', 'utf8');
/*
* Create a PDO instance as db connection to db.
*
* #link http://php.net/manual/en/class.pdo.php
* #link http://php.net/manual/en/pdo.constants.php
* #link http://php.net/manual/en/pdo.error-handling.php
* #link http://php.net/manual/en/pdo.connections.php
*/
$connection = new PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
, USERNAME
, PASSWORD
, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
Create table syntax
CREATE TABLE `kunden` (
`kunde_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nachname` varchar(100) DEFAULT NULL,
`vorname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`kunde_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Count the rows (results) you fetch form the database.
If the count is zero then display the "no results found" message.
If there are results then take care of displaying the table header before you output the first row.
$count = 0; // This keeps track of the rows fetched
while($ds = $sql->fetch())
{
// Before the first row let's put the table header
if( $count === 0 )
{
echo "<table>";
echo '<p class="abfrage2">Abfrage 3:</p>';
echo"<tr><th>Nachname</th><th>Vorname</th></tr>";
}
// Output the row
echo "<tr><td>$ds[Nachname]</td><td>$ds[Vorname]</td></tr>";
// Update the row count
$count++;
}
// No rows/results? display the message
// Otherwise close the table
if( $count === 0 )
{
// Display "no matches" message ex:
echo "<div class='some-class'>Sorry, but none of your letters match with the Names in the database</div>";
}
else
{
echo "</table>";
}
Note that your code is unsafe as prone to sql injection.
Use Prepared Statements to inject user data into the query.
When you take user input and put it into a query after a LIKE statement then % wildcards must be escaped in the input string. See this question an the accepted answer.
Finally you should trim() $kundevor and $kundenach before using them; make sure to close the <table> html at some point, I put the code after the while loop. You have some fixes to take care of...

PHP if-else condition not working

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.

How to sort rows of HTML table that are called from MySQL

I know it's such a basic thing, but a Google search hasn't shown me how to re-sort the rows after clicking the th links.
I've got this:
<table border="1">
<tr>
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
</tr>
<?php
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['description'] ?></td>
<td><?php echo $row['recorded_date'] ?></td>
<td><?php echo $row['added_date'] ?></td>
</tr>
<br />
<?php
}
mysql_close();
?>
</table>
I need to be able to click type and sort alphabetically, and click on either Recorded Date or Added Date and sort by date. I see that I need to have the MySQL queries do this, but do I set them up as conditionals with a href tags?
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
That's actually pretty easy, here's a possible approach:
<table>
<tr>
<th>
Type:
</th>
<th>
Description:
</th>
<th>
Recorded Date:
</th>
<th>
Added Date:
</th>
</tr>
</table>
<?php
$orderBy = array('type', 'description', 'recorded_date', 'added_date');
$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
$query = 'SELECT * FROM aTable ORDER BY '.$order;
// retrieve and show the data :)
?>
That'll do the trick! :)
A SIMPLE TABLE SORT PHP CODE:
(the simple table for several values processing and sorting, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
source: php sortable table
//this is a php file
<html>
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
<script type="text/javascript">
function working(str)
{
if (str=="")
{
document.getElementById("tump").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tump").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsort.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body bgcolor="pink">
<form method="post">
<select name="sortitems" onchange="working(this.value)">
<option value="">Select</option>
<option value="Id">Id</option>
<option value="Name">Name</option>
<option value="Email">Email</option>
<option value="Password">Password</option>
</select>
<?php
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine");
echo "<center><br><br><br><br><table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table></center>";?>
</form>
<br>
<div id="tump"></div>
</body>
</html>
------------------------------------------------------------------------
that is another php file
<html>
<body bgcolor="pink">
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
</head>
<?php
$q=$_GET['q'];
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine order by $q");
echo "<table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table>";?>
</body>
</html>
that will sort the table using ajax
This is the most simple solution that use:
// Use this as first line upon load of page
$sort = $_GET['s'];
// Then simply sort according to that variable
$sql="SELECT * FROM tracks ORDER BY $sort";
echo '<tr>';
echo '<td>Title<td>';
echo '<td>Album<td>';
echo '<td>Artist<td>';
echo '<td>Count<td>';
echo '</tr>';
It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.
In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)
Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.
You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.

Categories