Sort by using drop down variable from MySQL - php

I'm new to PHP, and I have a simple table from a MySQL database. What I want to do is sort the table using the selected value from the drop down box, with the data from that row in the database.
Here is my code (selected is what I need for the drop down box):
$orderby = $_GET['orderby'];
if ($orderby == 'selected') {
$orderby_query = "WHERE timeStamp LIKE 'selected'";}
else {
$orderby_query = "";
}
$con = mysql_connect("xxxx","xxxx","xxxx");
$db = mysql_select_db("xxxx",$con);
$get = mysql_query("SELECT DISTINCT(timeStamp) FROM deliverys ORDER BY timeStamp DESC");
$timeStamp = '';
while($row = mysql_fetch_assoc($get))
{
$timeStamp .= '<option value ="'.$row['timeStamp'].'">'.$row['timeStamp'].'</option>';
}
<table width="100%" border="1">
<tr style="font-weight:bold;" valign="top" height="30px" bgcolor="#999999">
<td><form name="sorter0" action="index.php" method="get">
<label title="date">Date</label><br />
<select name="orderby" OnChange="document.sorter0.submit();"><br /><br />
<option>Sort by Date</option>
<option value=''>--?--</option><?php echo $timeStamp; ?></option>
</select>
</form></td>
I don't know if I'm adding the data to the drop down box correctly because, if I click, the site reloads and I can see it say:
/index.php?orderby=05-09-2015
If I use a "fixed" value like yes or no it works.

Related

Update the value from table in textbox BUT not updated the value in db?

I have listed all the data(Item, Category, Job, Hole(Hole is evaluating marks)) and I display the Hole(mark) in textbox filed.
I want to update the Hole(marks) after user change.
I list all the data using php
<?php
try{
$con = new PDO("mysql:host=localhost;dbname=gcmes", "root", "");
$sql = $con->query("SELECT * FROM details");
echo"<table class='info' align='center'>";
echo"<tr><td width='10'><b>No</b></td>
<td width='30'><b>Category</b></td>
<td width='50'><b>Job</b></td>
<td width='40'><b>Evaluate</b></td><tr>";
foreach($sql as $row) {
$Item = $row["Item"];
$Category = $row["Category"];
$Job = $row["Job"];
$Evaluate = $row["Hole 1"];
echo'
<tr>
<td>' . $Item . '</td>
<td>' . $Category . '</td>
<td>' . $Job . '</td>
<td><input type="input" name="Evaluate" id="Evaluate" value="' . $Evaluate . '">
</td>
</tr>
';
}
echo"</table></form>";
if(isset($_POST['Update_btn'])){
$Evaluate = $_POST["Hole 1"];
if(empty(Evaluate)){
echo "<script type='text/javascript'>alert('Please fill in the required fields to update!')</script>";
}
else{
$insert=$con->prepare("UPDATE details SET Evaluate=:Hole 1 WHERE Item=:Item");
$insert->bindParam(':Hole1',$Evaluate);
$insert->bindParam(":Item",$Item);
$insert->execute();
echo "<script type='text/javascript'>alert('Successful Updated ! ');
window.location.href = 'Hole 1.php';
</script>";
}//else
}//if add button
}//try
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
?>
The html code i just use to display button
<form id="form1" name="Hole 1" method="post" action="Hole 1.php">
<input name="Update_btn" type="image" id="Update_btn" onmouseover="this.src='UpdateO.png'" onmouseout="this.src='UpdateD.png'" value="submit" src="UpdateD.png" alt="submit Button" align="right">
</form>
The problem is will alert message successful updated BUT the value not update in my db. Why? what is the problem?
this is my interface
i want update the marks in textbox filed
I need to change the hole as a selection give the user choose which hole that need to update only, i set the hole have a drop-down menu list. How to dectect which hole?
i just add the code after <td>{$rowData['Frequency']}</td> (dn Fer answer)
<td><select name="hole">
<option value="Hole1">1</option>
<option value="Hole2">2</option>
<option value="Hole3">3</option>
<option value="Hole4">4</option>
<option value="Hole5">5</option>
<option value="Hole6">6</option>
<option value="Hole7">7</option>
<option value="Hole8">8</option>
<option value="Hole9">9</option>
<option value="Hole10">10</option>
<option value="Hole11">11</option>
<option value="Hole12">12</option>
<option value="Hole13">13</option>
<option value="Hole14">14</option>
<option value="Hole15">15</option>
<option value="Hole16">16</option>
<option value="Hole17">17</option>
<option value="Hole18">18</option>
</select>
Keep the following in mind:
I don't have the same environment as yours, so it might not work one
on one.
Spaces in database fieldNames and arrayKeys, etc. are discouraged. I
prefer to use lowerCamelCase, check if dB fieldNames match the code
below!
Read the comments I've placed in the code.
I didn't take psr coding, value validation or safety (sql injection), etc. in consideration. The code is to guide you, you should take these things in consideration yourself.
Hopefully getting you closer to your goals...
Update: The values of the Evaluate field of each row is now validated to be an integer in the range from 1 to 5.
<?php
//Initialize variables
$result = '';
$doUpdate = isset($_POST['updateButton_x']);
//Because button type is 'image', we get parameters buttonName_x and buttonName_y
//from the browsers POST request when the form is sent.
if ($doUpdate) {
//Update button pressed.
//Initialize variables
$stmtSetParams = $stmtInParams = array();
$validationOptions = array('options' => array('min_range' => 1, 'max_range' => 5));
//Define statement and parameters (Assuming dB field 'item' is the primary key).
$set = '`hole1` = CASE `item` ';
foreach ($_POST['evaluate'] as $item => $hole1) {
//Get input value of each table row
if (filter_var($hole1, FILTER_VALIDATE_INT, $validationOptions) !== false) {
//Field is not blank
$set .= 'WHEN ? THEN ? ';
$stmtSetParams[] = $stmtInParams[] = $item;
$stmtSetParams[] = $hole1;
} else {
//Field is not an integer from 1 to 5
$result .= "Field \'Evaluate\' of item \'$item\' with a value of \'$hole1\' is not from 1 to 5 and skipped while saving!\\n";
}
}
$set .= 'END';
//Define query placeholders
$placeHolders = implode(', ', array_fill(0, count($stmtInParams), '?'));
$query = <<<SQL
UPDATE `details` SET $set WHERE `item` IN ($placeHolders)
SQL;
}
//Query the dB.
try {
$dbh = new PDO('mysql:host=localhost;dbname=gcmes', 'root');
if ($doUpdate) {
//Update requested. Prepare and execute update query
$stmt = $dbh->prepare($query);
$stmt->execute(array_merge($stmtSetParams, $stmtInParams));
$result .= 'Update Completed!';
}
//Query for en fetch (updated) table data
$stmt = $dbh->query("SELECT * FROM `details`");
$tableData = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
//A PDO exception is raised
$result = 'Error: ' . addslashes($e->getMessage());
}
//Alert results of database operations
if ($result != '') {
echo "<script>alert('$result')</script>";
}
?>
<form id="form1" name="chooseFormNameIfNeeded" method="post" action="test.php">
<!-- attribute align is deprecated, define and use a class instead -->
<table class="info align-center">
<tr>
<!-- use th instead of td for table header -->
<!-- using <b> tag is discouraged -->
<th width="10"><b>No</b></th>
<th width="30"><b>Category</b></th>
<th width="50"><b>Job</b></th>
<th width="40"><b>Evaluate</b></th>
</tr>
<?php
foreach ($tableData as $rowData) {
//Print a table row for each of the fetched records
echo <<<HTML
<tr>
<td>{$rowData['item']}</td>
<td>{$rowData['category']}</td>
<td>{$rowData['job']}</td>
<td>
<!-- Assuming dB field 'item' is the primary key. -->
<input type="number" name="evaluate[{$rowData['item']}]" id="Evaluate" value="{$rowData['hole1']}"
min=1 max=5
>
</td>
</tr>
HTML;
}
?>
</table>
<!-- Attribute align is deprecated, define and use a class instead -->
<!-- Value attribute should not be specified -->
<input name="updateButton" type="image" id="Update_btn" src="http://via.placeholder.com/100x50/0000FF?text=Update"
alt="submit Button" class="align-right"
onmouseover="this.src='http://via.placeholder.com/100x50/00FF00?text=Update'"
onmouseout="this.src='http://via.placeholder.com/100x50/0000FF?text=Update'"
>
</form>

Trying to use PHP to send two variables to SQL query

I'm sorry for such a basic question but I'm a bit stumped. I've been trying to build a basic website for a database I created that will graph the data. There are two variable lists that the user selects from and the data from this then is supposed to generate the requested information. However, I'm completely lost as to how to get the data selected from the list to appear in the results page. It will search under the 'country' variable, but not goods. I know that I'm probably doing something stupid, but I'm not sure what it is.
The code I'm using for the dropdown menus on the forms is as follows:
<form id="Country" name="Country" method="get" form action="/database/results_page.php"><table border="1">
<tr>
<td width="68">Name</td>
<td width="48"><span id="sprytextfield4">
<select name="selcountry" id="selcountry" title="<?php echo $row_rsCountrydropdown['']; ?>">
<?php
do {
?>
<option value="<?php echo $row_rsCountrydropdown['country']?>" <?php if($varcountry_rsexportsearch == $row_rsCountrydropdown['country']){echo 'selected';}?>><?php echo $row_rsCountrydropdown['country']?></option>
<?php
} while ($row_rsCountrydropdown = mysql_fetch_assoc($rsCountrydropdown));
$rows = mysql_num_rows($rsCountrydropdown);
if($rows > 0) {
mysql_data_seek($rsCountrydropdown, 0);
$row_rsCountrydropdown = mysql_fetch_assoc($rsCountrydropdown);
}
?>
</select>
<select name="selgoods" id="selgoods" title="<?php echo $row_rsGoodsdropdown['']; ?>">
<?php
do {
?>
<option value="<?php echo $row_rsGoodsdropdown['name']?>" <?php if($vargoods_rsexportsearch == $row_rsGoodsdropdown['name']){echo 'selected';}?>><?php echo $row_rsGoodsdropdown['name']?></option>
<?php
} while ($row_rsGoodsdropdown = mysql_fetch_assoc($rsGoodsdropdown));
$rows = mysql_num_rows($rsGoodsdropdown);
if($rows > 0) {
mysql_data_seek($rsGoodsdropdown, 0);
$row_rsGoodsdropdown = mysql_fetch_assoc($rsGoodsdropdown);
}
?>
</select>
</tr>
</table>
<input type="submit" name="submit" id="submit" value="Submit" onChange="row_rsCountrydropdown.submit()" />
</form>
and my SQL for the results page is as follows:
mysql_select_db($database_cork_normalised, $cork_normalised);
$query_query = "SELECT exports.trade_year, country_id.country, goods.name, exports.Cork FROM country_id, goods, exports WHERE country_id.country_id='varcountry' and goods.goods_id='vargoods'";
$query = mysql_query($query_query, $cork_normalised) or die(mysql_error());
$row_query = mysql_fetch_assoc($query);
$maxRows_query = 10;
$pageNum_query = 0;
if (isset($_GET['pageNum_query'])) {
$pageNum_query = $_GET['pageNum_query'];
}
$startRow_query = $pageNum_query * $maxRows_query;
$vargoods_query = "-1";
if (isset($_POST['selgoods'])) {
$vargoods_query = $_POST['selgoods'];
}
$varcountry_query = "-1";
if (isset($_POST['selcountry'])) {
$varcountry_query = $_POST['selcountry'];
}
If anyone could help I'd be really grateful, this is my first foray into PHP and I'm a bit lost in it.

Drop down, results table not showing Mysql php

Trying to get the results from the Mysql to show up on the web page.
The process is that the user would select a make of a car and then it will show just that make in a table.
I've been trying different things but I cant seem to get it to show the results. As soon as I get rid of the WHERE statement in the sql query it shows all the cars/makes. I think the problem is in the sql statement or the if.
This is what I've got so far.
<HTML >
<head>
<title>Inventory</title>
</head>
<body>
<form method="get" action="TaskC.php">
Please select a make:
<select name = "make" >
<option value = "All">All</option>
<option value = "Toyota">Toyota</option>
<option value = "Holden">Holden</option>
<option value = "Ford">Ford</option>
<option value = "Nissan">Nissan</option>
</select> <br/>
<br/>
<input type="submit" value="Search" name="Search" />
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Make</th>
<th>Model</th>
<th>Price</th>
<th>Quantity</th>
<tr>
</form>
<?php
//error_reporting (E_ALL ^ E_NOTICE);
$dbConnect = mysqli_connect('xxxxxxxxx', 'xxxxxxxxx','xxxxxxxx')
or die("<p>The database server is not available.</p>");
$dbSelect = mysqli_select_db( $dbConnect,'xxxxxxxx_db' )
or die("<p>The database is not available.</p>");
$make = $_GET['make'];
$sqli = "SELECT * FROM inventory WHERE make = '" .$make. "'";
$result = mysqli_query($dbConnect,$sqli);
if (isset($_GET['make']) )
{
while ($inventory = mysqli_fetch_assoc($result) )
{
echo "<tr>";
echo "<td>".$inventory['make']."</td>";
echo "<td>".$inventory['model']."</td>";
echo "<td>".$inventory['price']."</td>";
echo "<td>".$inventory['quantity']."</td>";
echo "</tr>";
}
}
mysqli_close($dbConnect);
?>
</body>
</HTML>
Hope you can help.
Thanks
There is an error in the query. It should be -
$sqli = "SELECT * FROM inventory WHERE make = '" .$make. "'";
Edit
if (isset($_GET['make']) ){
$make = $_GET['make'];
$sqli = "SELECT * FROM inventory WHERE make = '" .$make. "'";
$result = mysqli_query($dbConnect,$sqli);
while ($inventory = mysqli_fetch_assoc($result) )
{
echo "<tr>";
echo "<td>".$inventory['make']."</td>";
echo "<td>".$inventory['model']."</td>";
echo "<td>".$inventory['price']."</td>";
echo "<td>".$inventory['quantity']."</td>";
echo "</tr>";
}
}

php - Can't delete input in table using sql statement

I don't know what I have done to this but I had the form working and now it has stopped. My problems are with the bottom if statement where I am trying to delete the user. As I said it was working properly and now it has stopped. I just can't figure out what the issue is? And yes I do backup but clearly should do it more!
function HMdisplayrooms() {
global $wpdb;
echo '<html><body><h1>Display Rooms</h1>';
echo '<p>Order room view by: <p>
<form name = "view_HM_rooms" method="post" action="">
<select name="roomsView" size = "1">
<option value = "room_id">Room ID</option>
<option value = "room_type">Room Type</option>
</select></br>
<input type="submit" name="action">
</form></body></html>';
echo '<table border="1" style="width:1000px" cellspacing ="0"><tr><td><b>Room ID</b></td><td><b>Room Type</b></td><td><b>Options</b></td></tr>';
if(isset($_POST['action'])) {
$roomType = $_POST['roomsView'];
$query = "SELECT * FROM hm_room ORDER BY $roomType ASC";
$rooms = $wpdb->get_results($query);
foreach ($rooms as $room) {
$roomID = ($room->room_id);
echo '<tr><td>'.format_to_post($room->room_id).'</td><td>'.format_to_post($room->room_type).'</td><td><form name = "HotelManiaRoomDeletion" method="post" action="">
<input type="submit" name="action2" value="Delete Room"></form></td></tr>';
if(isset($_POST['action2'])){
$results = $wpdb->query("DELETE FROM hm_room WHERE room_id='".$roomID."'");
$msg = "Room deleted";
return $msg;
}
}
}
}
Use the code like this,
function HMdisplayrooms() {
global $wpdb;
echo '<html><body><h1>Display Rooms</h1>';
echo '<p>Order room view by: <p>
<form name = "view_HM_rooms" method="post" action="">
<select name="roomsView" size = "1">
<option value = "room_id">Room ID</option>
<option value = "room_type">Room Type</option>
</select></br>
<input type="submit" name="action">
</form></body></html>';
echo '<table border="1" style="width:1000px" cellspacing ="0"><tr><td><b>Room ID</b></td><td><b>Room Type</b></td><td><b>Options</b></td></tr>';
if(isset($_POST['action'])) {
$roomType = $_POST['roomsView'];
$query = "SELECT * FROM hm_room ORDER BY $roomType ASC";
$rooms = $wpdb->get_results($query);
foreach ($rooms as $room) {
$roomID = ($room->room_id);
echo '<tr><td>'.format_to_post($room->room_id).'</td><td>'.format_to_post($room->room_type).'</td><td><form name = "HotelManiaRoomDeletion" method="post" action="">
<input type="hidden" name="DelRooMId" value="'.$roomID.'">
<input type="submit" name="action2" value="Delete Room"></form></td></tr>';
}
}
if(isset($_POST['action2'])){
$roomID = $_POST['DelRooMId']; // sanitize the input
$results = $wpdb->query("DELETE FROM hm_room WHERE room_id='".$roomID."'");
$msg = "Room deleted";
return $msg;
}
}
I have pulled the DELETE block outside of your code. It may help you. The problem with your code is $_POST['action'] will be null at the time of DELETE operation , so the code never executes, that may be the error
Note - Make sure to get the $roomID when you are using the below structure

Cant get my user database to sort.

I have a user database which I want the admin to be able view users. I want the admin to be able to sort the users by different fields. (E.g first name or surname).
My problem:
Is that it wont sort. Im trying to do it using a drop down box and a submit button. I have have tried the Sql in phpMyAdmin to make sure the statement is correct which it is. I have also added a or die to make sure its not a mysql error. Im getting no errors its just not sorting. I have also tried echoing out the drop down to make sure the right value is being added to the variable.
code:
HTML drop down
<form action="View_users.php" enctype="multipart/form-data" name="sort" id="sort" method="post" align="right">
<label>
<select name="sortdropdown" id="sortdropdown">
<option value="<?php echo $sortby; ?>"><?php echo $sortby; ?></option>
<option value="name">First Name</option>
<option value="surname">Surname</option>
<option value="email">Email</option>
<option value="signupdate">Date</option>
</select>
</label>
<label>
<input type="submit" name="button" id="button" value="Sort" />
</label>
</form>
logic:
$sortby = "";
if (!isset($_POST['sortdropdown'])) {
$sortby = "surnname";
}else{
$sortby = mysql_real_escape_string($_POST['sortdropdown']);
}
// This block grabs the whole list for viewing
$product_list = "";
$counter = 0;
$sql = mysql_query("SELECT * FROM users ORDER BY '$sortby' ASC") or die(mysql_error());
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$counter++;
$id = $row["id"];
$email = $row["email"];
$name = $row["name"];
$surname = $row["surname"];
$lastlogin = $row["lastlogin"];
$signupdate = $row["signupdate"];
if (is_float($counter/2)) {$class = "#CCCCCC"; }
else {$class = "white";}
$product_list .= '<tr bgcolor="'.$class.'">
<td>'.$surname.'</td>
<td>'.$name.'</td>
<td>'.$email .'</td>
<td>View More</td></tr>';
}
} else {
$product_list = "There are no users in the system yet";
}
Thanks
The comments are correct, you should be using back ticks `$sortby` instead of '$sortby'
The reason is - single quotes are used to wrap values in MySQL, which is not what you want. You're passing the name of a table column, so you use back ticks because they are used to wrap table column names.

Categories