populate html table with php from mySQL based on user input - php

I'm trying to populate an html table from my SQL query based on a user's selections. I'm able to populate the first column however, my variable column "select_datapoint" is blank. Is there any reason this won't work?
<form>
<select name="select_datapoint">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
<option value="test5">test5</option>
</select>
<select name="minput">
<option value="ME">ME</option>
<option value="CT">CT</option>
<option value="AZ">AZ</option>
<option value="DE">DE</option>
<option value="MT">MT</option>
</select>
<input type="submit" name="Submit">
</form>
<br></br>
<?php
print date("g:i a.", time());
?>
<br></br>
<!--use PHP to connect to sql database-->
<?php
$servername = "sql206.phpnet.us";
$username = "pn_14163829";
$password = "714405c";
$dbname = "pn_14163829_mexico";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$zurich = $_GET["minput"];
$montreal = $_GET["select_datapoint"];
$sql = "SELECT test1,'$montreal' AS testX FROM test WHERE test1='$zurich'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table class=\"v\">";
echo "<th>test1</th><th>$montreal</th>";
while($row = $result->fetch_assoc()) {
echo "<tr>"."<td>".$row["test1"]."</td>"."<td>".$row['testX']."</td>"."</tr>";
}
} else {
echo "0 results";
echo "<br></br></table>";
}
$conn->close();
?>

$sql = "SELECT test1,'$montreal' AS testX FROM test WHERE test1='$zurich'";
Mark's answer is correct, but not for the reason he gives.
He says that the above will treat '$montreal' as a string literal. Normally that is correct, but because it's embedded in a double quoted string, it will actually be interpolated correctly.
What's actually happening is that you're generating a string along the lines of:
SELECT test1,'fieldname' AS testX FROM test WHERE test1='$zurich'
The 'fieldname' is incorrect - it's a column name. Single quotes in an SQL query are for values, so MySQL isn't interpreting this as you expect. If you want to use quotes for a column (or table) name, you need to use backticks:
$sql = "SELECT test1,`$montreal` AS testX FROM test WHERE test1='$zurich'";
Will work. Though as you noticed, you can get the same effect by omitting any quotes.

This is invalid PHP Code:
'$montreal'
Single quotes will not process variables inside of them. Change it to double quotes:
$row["$montreal"]
Or, better yet, remove the quotes all together:
$row[$montreal]
Read more here:
What is the difference between single-quoted and double-quoted strings in PHP?

Related

How can I populate a 3rd column result on intersections of 1st and 2nd columns all from the same table that are selected by the user on dropdown?

I have a column vehicle_name and I would like 2 dropdown lists of my 2 other columns namely, vehicle_type and vehicle_color.
When these 2 dropdown values are selected and submitted, I would like their intersection to print out the values from vehicle_name. So far my code only generates a dropdown list for vehicle_type, I would need another dropdown for vehicle_colour. Which on submissions populates the intersected values for the vehicle_name. How can I achieve this?
<!DOCTYPE html>
<html>
<body>
<?php
echo "<br>";
echo "<br>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$db = new mysqli($servername, $username, $password, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<br>
<div class="label">Select vehicle type:</div>
<select name="payment_method">
<option value = "">---Select---</option>
<?php
$queryusers = "SELECT DISTINCT vehicle_type FROM orders";
$db = mysqli_query($db, $queryusers);
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['vehicle_type']."}'>".$d['vehicle_type']."</option>";
}
?>
</select>
<br>
<div class="label_for_time">Select color:</div>
<select name="vehicle_color">
<option value = "">---Select---</option>
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
</select>
<br>
<br>
<button class="go-btn" type="submit">Go</button>
</body>
</html>
As I don't see any AJAX / client-side code in your above example I assume that this is a pure backend-side filtering you are performing. Your code is currently missing parts of the required elements we would need but let's try to figure this out together:
1. Form around your inputs
Add a <form method="POST" target="path-to-your-script.php"> where "path-to-your-script.php" has to be changed to your PHP file name or rewritten URL path. This has to be around the <select> boxes.
You may also use PHP_SELF to set this automatically, this should work in most cases. I used html_entities($var) to avoid any code injections via manipulated URL.
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
2. Check for POST'ed variable 'vehicle_type'
In your form, check if a search for available colors has been performed:
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
// check if the form variable 'vehicle_type' is available; if so, filter entries.
if (isset($_POST['vehicle_type'])) {
$vType= filter_var($_POST['vehicle_type'], FILTER_SANITIZE_STRING);
$query_for_colors .= ' WHERE vehicle_type = \''.$vType.'\'';
}
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
Edit:
As pointed out by one user in the comment, filter_var($var, FILTER_SANITIZE_STRING) won't be enough to avoid potential SQL injections. This was just a recommendation and was not part of the question at all. If you have to work with user data, do more than using filter_var(), instead use either prepared statements or properly escape the user data. There are many tutorials like this one out there that will guide you to safe queries.

UPDATING information into MySQL Database but department remains the same for each employee

I am trying to update my DB for the employees table. When I run and test, every user is coming up as working in Accounting even if they work in another department. Is there something I am missing? I am not receiving any errors either. Any help is greatly appreciated.
PHP/HTML
<?php
//ERROR CHECKING CODE
mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once("dbconnect.php");
$id = (isset($_REQUEST['id']) ? $_REQUEST['id'] : '');
$sql = "SELECT * FROM employees WHERE empid= '" . $id . "';";
$result = mysqli_query($connect, $sql) or die(mysql_error);
$row = mysqli_fetch_array($result, MYSQL_ASSOC) or die (mysql_error());
?>
PHP/HTML
<p>Department</br>
<select name="department">
<option <?php if($row['department']==1) {print('selected');}?>value="1">Accounting</option>
<option <?php if($row['department']==2) {print('selected');} ?>value='2'>Legal</option>
<option <?php if($row['department']==3) {print('selected');} ?>value='3'>Information Technology</option>
<option <?php if($row['department']==4) {print('selected');} ?>value='4'>Human Resources</option>
</select>
Without seeing the code in action it's hard to say, but at first glance there's this problem: In each option tag you're not leaving any space between the closing PHP tag (?>) and the value property, so when if $row['department'] matches the correspondent value, the PHP statement will print "selected" but with no space, the HTML will look like this (say $row['department'] equals 2):
<option selectedvalue='2'>Legal</option>
which obviously won't select that option. Try adding a space after each closing PHP tag, or print "seleted ", with a space in the end.

get dropdown data on another dropdown change

I have a drop down menu having column names same as they are in database table. I have inserted every column name in option tag of dropdown menu. These columns have number of rows in database.
After that, I have another drop down menu. I want to show all the data rows of the selected column in the previous drop down menu.
E.g. I have column names as a,b,c,d in the first drop down and every column has data in database table. So, If I select A in first drop down; It shows all the data rows of A in next drop down. Here is the code:
<select name="first">
<option selected="true" disabled="disabled">Select an Option</option>
<option value="select_all">Select All</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">c</option>
</select>
<?php
if(isset($_POST['first'])){
$first=$_POST['first'];
}
?>
<select name="firstres" id="firstres"><option style="display:none;" selected; value="">---Select an option---</option><?php
#mysql_connect('localhost', 'root', '');
#mysql_select_db('db');
$first=$_POST['first'];
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db' AND TABLE_NAME = 'tbl' AND COLUMN_NAME LIKE '" . $_POST["first"] . "'";
$result = #mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value=' " . $row['first'] ."'>" . $row['first'] ."</option>";
}
?>
</select>
The problem is; I am not getting column rows in second drop down menu.
You need to use Ajax for this issue, here my code maybe you can use on your projects.
View Code
<select id="category">
<option value="1">Category</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select id="sub_category">
<option>Chose Category</option>
</select>
Ajax Code
$(document).ready(function(){
$('#category').on('change',function(){
var category_id = $(this).val();
if(category_id){
$.ajax({
type:'POST',
url:'sub_category.php',
data: {
category_id : category_id
},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option>Pilih Sub category Kelas</option>');
}
});
});
sub_category.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category_id = $_POST['category_id'];
$sql = "SELECT id,sub_category FROM category where category_id = $category_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row["id"]."'>".$row["sub_category"]."</option>";
}
} else {
echo "<option>Empty Sub Category</option>";
}
$conn->close();
?>
First of all, I do recommend to stay in php for the whole code.
-> Make things easier for the future...
Example:
$output = <<< EOD
<option>Select an Option</option>
etc.
EOD;
echo $output;
Second, did you run through the code step by step?
what is the output for $first and $_POST['first']; ?
Are they correct?
Is the SQL statement correct?
Table and column names....
Third, I understand, that you want select from the first dropdown and than the output from the database should appear.
This won't work in that way. HTML is stateless. This means everything which has been send to client is no longer available for the server.
So you need to use some code to resend this information: For example JSON (AJAX) or via HTML (which is not so nice). Look here:
https://www.w3schools.com/js/js_ajax_intro.asp

dropdown box has extra blank spaces/vaues

I am grabbing some values from my database and putting them in a dropdown select box. For some reason, there is a blank value after each option, which is weird as my database doesn't contain any blank fields.
<select id="school" name="school_name">
<option value=0> Choose</option>
<?php
$con = mysqli_connect("localhost", "root", "****") or die("error".mysqli_error());
mysqli_select_db($con, "newprojectdb") or die("error in database".mysqli_error());
$sql="SELECT school_id, school_name FROM schools";
$result=mysqli_query($con, $sql);
while($row= mysqli_fetch_array($result)){
$school_name=$row["school_name"];
echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
}
mysqli_close ($con);
?>
</select>
The reason why you are getting a blank space between each value is because of the last <OPTION> which the closing / was missing and should have been closed like this </OPTION>
I also noticed you escaped the single quotes for
echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
^^ ^^ ^ missing the / slash
which would not have echo'ed the value in HTML source but the variable itself $school_name
Sidenote: Variables are not parsed properly when set inside single quotes which is what you were doing in escaping the single quotes.
Example:
<OPTION VALUE='$school_name'>
Change it to:
echo '<OPTION VALUE="'.$school_name.'">'.$school_name.'</OPTION>';
and it will work.
You can also do it this way: (escaping the double quotes for VALUE instead).
echo "<OPTION VALUE=\"$school_name\">".$school_name."</OPTION>";
Footnotes
For cleaner and more readable HTML, use a concatenated . "\n" at the end like this:
echo "<OPTION VALUE=\"$school_name\">".$school_name."</OPTION>" . "\n";
which will produce something like:
<OPTION VALUE="St-Alexander">St-Alexander</OPTION>
<OPTION VALUE="St-Peter">St-Peter</OPTION>
<OPTION VALUE="St-John">St-John</OPTION>
instead of
<OPTION VALUE="St-Alexander">St-Alexander</OPTION><OPTION VALUE="St-Peter">St-Peter</OPTION><OPTION VALUE="St-John">St-John</OPTION>
Pleae find changes you need. Thanks
CHANGE
echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
TO
echo "<option value=\"$school_name\"> $school_name </option>";

Implement data using query

I want to create a php page that contains a html drop down list of people's names (as the option
text) and then their age (as the value). Below is my form for you to see (almost what I mean) which I hard coded:
<form>
<select name="nameOption">
<option value="">Select your name:</option>
<option value="45">Mary Smith</option>
<option value="16">Lily Roe</option>
<option value="32">Elliot Perkins</option>
</select>
<p><input type="submit" name="submit" value="Submit"/>
<input type="reset" value="Reset" />
</form>
What I want to do (or been trying to do) is to create the drop down list by running a SQL query to obtain the data (the people's name and age) from my database (unlike what I written above) and then when I click on one of the options, only their value or age should appear. So basically, I need to implement the data from the database into a drop down list
Now it's here where I am stuck. I am familiar with writing SQL statements for tables but I seem to get puzzled when I try to create a SQL statement for a drop down list in a php tag.
How would I write it? Like:
$sql = "SELECT name, age FROM person WHERE name = ". $person. ";
or
$nameOption = $_POST['nameOption'];
print_r ($nameOption);
with selecting a database:
$conn = mysql_connect("localhost", " ", " ");
mysql_select_db(" ", $conn)
I know it may seem like a dull answer but I need help. How would I implement SQL query to a drop down list? I would love your help.
As you have to enclose string in quotes, change your query to
$sql = "SELECT name, age FROM person WHERE name = '$person'";
and for showing dropdown dynamically you can do like
$query=mysql_query($sql);
echo '<select name="nameOption">
<option value="">Select your name:</option>';
while($result=mysql_fetch_array($query))
{
echo '<option value="'.$result['age'].'">'.$result['name'].'</option>';
}
echo '</select>';
You should do like that
<select name="nameOption">
<?php
$query = mysql_query($sql);
while( $row = mysql_fetch_array($query) ) {
echo '<option value="'.$row['age'].'">"'.$row['name'].'"</option>';
}
?>
</select>
You need to get the full list of people from the database first, then iterate through that outputting each option tag for each row:
$cnx = new Mysqli('localhost', 'username', 'password', 'database_name');
$people = $cnx->query("SELECT name, age FROM person");
echo '<select name="nameOption">';
while($person = $people->fetch_assoc())
{
echo '<option value="' . $person['age'] . '">' . $person['name'] . '</option>';
}
echo '</select>';

Categories