Sort from database tables by multiple checkbox php - php

I have a question about display data from the database alphabetically.
I have 2 ckeckboxes and if the nr.1 is checked, it must display data alphabetically from table "companyName" but if chechbox nr.2 is checked, it must display data alphabetically from table "stade".
I am very new to coding, so I will be happy if there was someone who could explain or show me exactly how it should look.
Here is the checkboxes:
<fieldset>
<dl">
<dt><label for="sleep">Sortering:</label></dt>
<dd>
<input type="checkbox" name="" value="Alfabetisk A-Z"/>
<label for="alfabetiskA-z" class="opt">Alfabetisk A-Z</label>
<input type="checkbox" name="" value="Alfabetisk Stade"/>
<label for="alfabetiskStade" class="opt">Alfabetisk Stade</label>
</dd>
</dl>
</fieldset>
Here is where I show my data fra the database:
echo '
<table class="tableUser">
<tr class="topColor">
<td>Stade</td>
<td>Firmanavn</td>
<td>Navn</td>
<td>Telefon nr.</td>
<td>E-mail adresse</td>
</tr>';
$class0 = "trColor0";
$class1 = "trColor1";
$query = mysqli_query($conn,"SELECT * FROM creatUser ORDER BY companyName ASC");
while( $result = mysqli_fetch_array($query)) {
$id = $result['id'];
$class = "trColor". $i%2;
echo '
<tr class="'.$class.'">
<td VALIGN=TOP>'.$result['locationNumber'].'</td>
<td VALIGN=TOP>'.$result['companyName'].'</td>
<td VALIGN=TOP>'.$result['fName'] . ' ' . $result['lName'].'</td>
<td VALIGN=TOP>'.$result['phone'].'</td>
<td VALIGN=TOP>'.$result['eMail'].'</td>
</tr>';
$i++;
}

You have to give names to your checkboxes, so you can get what the user selected:
<input type="checkbox" name="sort" value="Alfabetisk A-Z"/>
<label for="alfabetiskA-z" class="opt">Alfabetisk A-Z</label>
<input type="checkbox" name="sort" value="Alfabetisk Stade"/>
<label for="alfabetiskStade" class="opt">Alfabetisk Stade</label>
Then in your PHP, you do:
if (!isset($_POST['sort']) || $_POST['sort'] == 'Alfabetisk A-Z') {
$order = 'companyName'
} else {
$order = 'stade';
}
$sql = "SELECT * FROM creatUser ORDER BY $order ASC";
$query = mysqli_query($conn, $sql) or die (mysqli_error($conn));

Related

building an evaluation form php

I'm trying to create an evaluation form for students, all questions are stored in db. I'm retrieving them from db any trying to store the answers for each question on db again. all answers should be selected from radio buttons as the following:
<?php
$sql = "SELECT Q_body, Q_ID FROM s_evaluation_questions WHERE Ev_ID='1'";
$result = $conn->query($sql);
?>
<?php
if ($result->num_rows > 0)
{
?>
<form action="AnswerS.php" method="POST">
<table align="right" id="keywords" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th colspan="4"> </th>
<th>Question</th>
</tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc())
{ $answer="s".$row["Q_ID"];
?>
<tr>
<td>
<input type="hidden" name="Q_ID" value="<?php echo $row["Q_ID"]; ?>" >
<input type="radio" name=<?php echo $answer?> value="Bad" >Bad
<input type="radio" name=<?php echo $answer?> value="Good"> Good
<input type="radio" name=<?php echo $answer?> value="VeryGood"> Very Good
<input type="radio" name=<?php echo $answer?> value="Excellent"> Excellent</td>
<td align="right"> <?php echo $row["Q_body"]?></td>
</tr>
<?php } ?>
</tbody>
</table></br></br></br></br></br></br></br>
<input type="submit" value="Send" />
</form>
<?php
?></div>
<?php
} else
{echo "not allowed";}
And on the AnswerS.php page I suppose to store the answers on db as the following:
$UID='1';
$answer=$_POST['answer'];
$Q_ID= $_POST['Q_ID'];
$sql = "INSERT INTO s_evaluation_answers(Q_ID, A_body, UID) VALUES($Q_ID, $answer, $UID) ";
$result = $conn->query($sql);
if ($result === TRUE) {
echo "done" ;
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
but unfortunately it doesn't work!, I tried to trace the value of Q_ID and it gives only the last question id not all questions.
how can I store the selected value from the radio button for each question and store it as the answer for this question? (note: all questions are brought from db)
thanks
If you see your source html you will find that you have many fields with name Q_ID:
<input type="hidden" name="Q_ID" value="one id" >
<input type="hidden" name="Q_ID" value="another id" >
<input type="hidden" name="Q_ID" value="some more id" >
So browser sends you the last value of Q_ID - in above case it is some more id.
To avoid this - use [] notation in name attribute:
<input type="hidden" name="Q_ID[]" value="one id" >
<input type="hidden" name="Q_ID[]" value="another id" >
<input type="hidden" name="Q_ID[]" value="some more id" >
After that, outputting $_POST['Q_ID'] will give you an array. You can iterate over it with foreach and gather other info you need. Something like (simplified):
foreach ($_POST['Q_ID'] as $q) {
// answer will be stored in a `s . $q` value of POST
$answer = $_POST['s' . $q];
$sql = "INSERT INTO s_evaluation_answers(Q_ID, A_body, UID) VALUES($q, $answer, $UID) ";
$result = $conn->query($sql);
}

Can't edit data in the database and cant fetch name with id?

I am trying to edit data into the database I don't know why I cant do. I have tried something till now. maybe someone can have a look please. I am trying to built a update where i can change name, surname blah blah blah, but i cant config even just for a name first..
Home file
Managament System
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
include_once('coneksioni.php');
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
$res = mysql_query("SELECT * FROM tblperson");
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($res)) {
?>
<tr>
<td><?=$row['personid']?></td>
<td><?=$row['personname']?></td>
<td><?=$row['personsurname']?></td>
<td><?=$row['persondepartment']?></td>
<td><?=$row['personboard']?></td>
<td><?=$row['martinumber']?></td>
<td><?=$row['personregdate']?></td>
<td>
edit |
del
</td>
</tr>
<?php
}
?>
</body>
</html>
and edit20.php
<?php
include_once('coneksioni.php');
if( isset($_GET['edit']) )
{
$personid = $_GET['edit'];
$res= mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row= mysql_fetch_array($res);
}
if( isset($_POST['personname']) )
{
$personname = $_POST['personname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname='$personname' WHERE personid='$personid'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
Name: <input type="text" name="personname" value="<?php echo $row[1]; ?>"><br />
<input type="hidden" name="personid" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>
and in the database primary key in my table is personid name field personname (not Primary key).
Please use Prepared Statement for reduce the risk of SQL Injection
check the coneksioni.php
$conn = new mysqli(HOST, USER, PASS, DBNAME);
the edit.php
require_once ('coneksioni.php');
$edit_person = $conn->prepare("
UPDATE tblperson SET
personname = ? WHERE personid = ?
");
$edit_person->bind_param(
"si",
$personname, $personid
);
if(isset($_POST['personname']) && isset($_POST['personid']) ) {
$personname = $_POST['personname'];
$personid = $_POST['personid'];
if (!$edit_person->execute()) {
// action if failed
} else {
// action if success
}
$edit_person->close();
}
the form.html
<form action="edit.php" method="POST">
Name: <input type="text" name="personname" value="<?php echo $row[1]; ?>"><br />
<input type="hidden" name="personid" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>
Cheers

Dynamic insertion of data into database

I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}

how to display two row of database value in textfield when user select one value from drop down list

When a user select the name using drop down list,the stock and price text field should automatically be filled.But it wont.
This is the code
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
echo '<option value="'.$row['price'].' && '.$row['price'].'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price" id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<tr>
<td>
<p>Stock</p>
</td>
<td>
<p align="center">:<input type="text" name="stock" id="stock"value="<?php echo ('stock'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
var input = document.getElementById('price');
var input = document.getElementById('stock');
select.onchange = function(){
input.value = select.value;
}
</script>
i hope u guys can help.i've spent a week just to figured out the code.
Try this below code, below are some notes
Avoid using the Keywords like "name" in select box
Price and Stock Input element attribute are does not have spaced properly.
Avoid using Mysql_connect and start use PDO / MySQLi
Avoid presentational tags and start use css to acheive it like "text-align:center"
Currently its working as you expected without Ajax and its a quick workaround, I have added the value in a comma separated the both value by split function.
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
// echo '<option value="'.$row['price'].' && '.$row['price'].'">'.$row['name'].'</option>';
$option_value = $row['price'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price" id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<tr>
<td>
<p>Stock</p>
</td>
<td>
<p align="center">:<input type="text" name="stock" id="stock"value="<?php echo ('stock'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
//var input = document.getElementById('price');
//var input = document.getElementById('stock');
var price = document.getElementById('price');
var stock = document.getElementById('stock');
select.onchange = function(){
// input.value = select.value;
var price_stock = select.value.split(',');
price.value = price_stock[0];
stock.value = price_stock[1];
}
</script>
How about this.......
Main File
<?php
$medOptions = "";
mysql_connect( "localhost", "root", "");
mysql_select_db( "arie");
$sql = mysql_query( "SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) !=0 ) {
while($row = mysql_fetch_assoc($sql)) {
$medOptions .= '<option value="' . $row['id'] . '">' . $row['name'] . '</option>\n';
}
}
?>
<form>
<table>
<tr>
<td class="label" width="55%">Medicine name</td>
<td width="45%">
<select name="med" id="med">
<option disabled="true" selected="true">--- Choose Medicine ---</option>
<?=$medOptions;?>
</select>
</td>
</tr>
<tr>
<td class="label">Price</td>
<td><input type="text" id="price" readonly="true" /></td>
</tr>
<tr>
<td class="label">Stock</td>
<td><input type="text" id="stock" readonly="true" /></td>
</tr>
</table>
CSS
table {
margin: 0 auto;
}
td {
text-align:center;
}
.label {
font-weight:bold;
}
Javascript
var select = document.getElementById('med');
// INSERT AJAX ROUTINE TO RETRIEVE PRICE AND STOCK LEVEL
var medPrice = document.getElementById('price');
var medStock = document.getElementById('stock');
select.onchange = function () {
medPrice.value = response.price;
medStock.value = response.stock;
};

Records not getting inserted in ascending order

I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);

Categories