How to get data from mysql to the select option in php - php

I have 2 tables: Students and Classes. In table Classes, I have a column "name" and in table Students I have a column "class" with input as select option. I want to get data from "name" to the select option. Anyone can help me?
This is my source code:
<?php
include "connect.php";
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sqlClass = "select * from classes where id = $id";
$result = $conn->query($sqlClass);
if ($result->num_rows > 0) {
$classes[] = $result->fetch_assoc();
} else{
die('class not found');
}
}
$sql = "select count(name) from classes";
$total = $conn->query($sql);
$totalClass = $total->fetch_assoc()['count(name)'];
?>
<div class="form-group">
<label for="">Class</label>
<select name="" id="input" class="form-control" required="required">
<?php
for ($i=1; $i <= $totalClass ; $i++) {
?>
<option value="<?=$i?>"><?php echo $classes['name']; ?></option>
<?php } ?>
</select>
</div>

Your select needs a name (if you don't name it you will never find it when you post the data) and you don't need the second query to get a count, just an iterator for each option:
<?php
include "connect.php";
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sqlClass = "select * from classes where id = $id";
$result = $conn->query($sqlClass);
if ($result->num_rows > 0) {
$classes[] = $result->fetch_assoc();
} else{
die('class not found');
}
}
?>
<div class="form-group">
<label for="">Class</label>
<select name="A_NAME_IS_REQUIRED" id="input" class="form-control" required="required">
<?php
$i = 1;
foreach($classes AS $class) {
?>
<option value="<?=$i?>"><?php echo $class['name']; ?</option>
<?php
$i++;
}
?>
</select>
</div>
In addition, you will want to check if $classes is an array. If it isn't there would be no sense in creating the drop-down.
SQL Injection Warning!
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

Related

Creating a search function

I have multiple fields in my search form and my query works for individual fields. what i'm trying to achieve is
1- query should work if search is based on 1 field
2- query should work if search is based on multiple fields entry
my form
<form class="sidebar-search jumbro-search container list-inline center-block" method="get" action="search.php">
<div class="form-group col-md-2">
<input list="location" name="location" class="form-control" placeholder="Location">
<datalist id="location">
<?php
$loc="select * from locations";
$results=mysqli_query($dbc,$loc);
while($row_loc=mysqli_fetch_array($results)){
echo '<option value='.$row_loc['region'].'>'.$row_loc['region'].'</option>';
}
?>
</datalist>
</div>
<div class="form-group col-md-2">
<select class="form-control" name="category">
<option selected>Category</option>
<?php
$cat="select * from property_type order by type_name asc";
$results=mysqli_query($dbc,$cat);
while($row_cat=mysqli_fetch_array($results)){
echo '<option value='.$row_cat['type_name'].'>'.$row_cat['type_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control" name="status">
<option selected>Status</option>
<?php
$status="select * from property_status order by status_name asc";
$results=mysqli_query($dbc,$status);
while($row_status=mysqli_fetch_array($results)){
echo '<option value='.$row_status['status_name'].'>'.$row_status['status_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" name="price-max" value="999999999999" class="form-control" placeholder="Max Price">
</div>
<div class="form-group col-md-2">
<button class="btn btn-primary form-control">Search</button>
</div>
and my php script looks like this
// getting user data from search form
$location=$_GET['location'];
$category=$_GET['category'];
$status=$_GET['status'];
//scripts
if($location!="location" && $category!="category" && $status!="status"){
$query="select * from properties where `property_type` like '%$category%' && `location` like '%$location%' && `status` like '%$status%' ";
}
$query="select * from properties where `property_type` like '%$category%' or `location` like '%$location%' or `status` like '%$status%'";
$result=mysqli_query($dbc,$query);
if(mysqli_query($dbc,$query)) {
$num_rows=mysqli_num_rows($result);
} else {
echo 'Query failed';
}
$num_rows=mysqli_num_rows($result);
if($num_rows!=0){
echo '<h3 class="page-header text-center">'.$num_rows.' Match Found</h3>';
while ($row=mysqli_fetch_array($result)) {
<?php
}//end while
}else{
echo '<h3 class="page-header text-center">No Match Found, try adjusting your search criteria.</h3>';
include 'functions/latest-sc.php';
}
Well, okay, I have several ideas about what you should change in your code.
I strongly recommend you to separate representative logic (html and echoing variables) from functionality like defining variables and handling database queries. It will help you a lot in future.
You can use default option in your selects with empty value
<option value="">Select none</option>
It will simplify your code in checks:
Instead of:
if($location!="location" && $category!="category" && $status!="status")
Can use:
if($location && $category && $status)
Read about escaping
On your main question - you can create query by concatenation. I give you example and you can replace it with 'OR' or 'AND' for your needs:
$sql = 'SELECT * FROM properties WHERE ';
$scopes = [];
foreach([$location,$category,$status] as $column => $condition) {
if ($condition) {
$scopes[] = $column.' LIKE \'%.$condition.'%\'';
}
}
$scopes = implode(' AND ',$scopes);
$sql .= $scopes.';';
// ...do what you need
There is a lot more advices for coding but maybe you just present it like dead-simple example, so I skip it.
OK I think what you are asking is a SELECT based on multiple columns in a table. Below is a script from my application that selects records from a table that checks for a hometeam and an away team:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "localdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT hometeam FROM stats WHERE hometeam = 'Man City' AND awayteam = 'Sunderland'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['hometeam'];
}
} else {
echo "0 results";
}
$conn->close();
?>
This should work:
$data = [
'property_type' => 'category_value', //$_GET['location']
'category' => 'location_value', //$_GET['category']
'status' => 'status_value' //$_GET['status']
];
$select = "";
$params = 0;
foreach($data as $k => $v){
if($params > 0){
$select .= " or ";
}
//add some better conditions
if(strlen($v) > 0){
$select .= "`$k` LIKE %$v%";
$params++;
}
}
$query = "select * from properties where " . $select;
print_r($query);

Throw select php variable into a form and convert it to a POST variable

I'm trying to use a drop down menu to load data from a select value. I want it passed into a php document in order to use the data that I need. What should I do? Thanks in advance.
This is my code for the select menu:
$sqlz = "SELECT * FROM content_temp1 WHERE user_uname='$uname'";
$resultz = mysql_query($sqlz);
$checkz = mysql_numrows($resultz);
$count = 0;
?>
<select name="ltemp">
<?php
while($count<$checkz){
$selectname=mysql_result($resultz,$count,"temp1_name");
?>
<option value="<?php echo "$selectname";?>"><?php echo $selectname;?></option>
<?php
$count++;
}
?>
</select>
<input type="submit" value="Load Template" class="ufbutton"><br></center>
</form>
and this is my php page
$uname = $_GET['username'];
$loadtemp = $_POST['ltemp'];
header("Location:editing1.php?username=$uname&tempname=$loadtemp");
it seems that you have use " inside " in this line :
<option value="<?php echo \"$selectname\";?>"><?php echo $selectname;?></option>
try this:
$sqlz = "SELECT * FROM content_temp1 WHERE user_uname='$uname'";
$resultz = mysql_query($sqlz);
$checkz = mysql_numrows($resultz);
$count = 0;
?>
<select name="ltemp">
<?php
while($count<$checkz){
$selectname=mysql_result($resultz,$count,"temp1_name");
?>
<option value="<?php echo \"$selectname\";?>"><?php echo $selectname;?></option>
<?php
$count++;
}
?>
</select>
Alternative :
$sqlz = "SELECT * FROM content_temp1 WHERE user_uname='$uname'";
$resultz = mysql_query($sqlz);
?>
<select name="ltemp">
<?php
while ($row = mysql_fetch_array($resultz, MYSQL_ASSOC)) {
$selectname=$row["temp1_name"];
?>
<option value="<?php echo \"$selectname\";?>"><?php echo $selectname;?></option>
<?php } ?>
</select>
Be careful this is ripe for sql injection without validating the input;
SQL Injection with GET

Populating dropdown with sql results

I have the following code to display a dropdown based on the sql query but nothing is displaying when i run the code.
<?php
require ("common.php");
$sql = "SELECT FullName FROM Users";
$query = $db->prepare($sql);
$query->execute();
$option = "";
while($rows = $query->fetchAll(PDO::FETCH_ASSOC)) {
$name = $rows["FullName"];
$option.="<option>".$name."</option>";
}
?>
<div class="aClass">
<p class="select">Name</p>
<select name="aName" id="aName">
<option value="0">Select UserName</option>
<?php echo $option?>
</select>
</div>
$option you added an s
<?php echo $option;?>
Replace while with
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $rows) {
...
}
while($rows = $query->fetchAll(PDO::FETCH_ASSOC)) will return the entire set of results which will not evaluate to true,leaving $name undefined,you want to iterate over the results.

Displaying query results after submitting a PHP form

I am currently working on a school project using php and mysql. I have created a form with three drop down boxes where users select types of data they are looking for. However, I am having a lot of trouble displaying the results after the form is submitted. Here is my current code:
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
I am almost certain my problem lies within my while statement. I get the titles of my table columns to show up (Year, Month, $gSelect), but I am not getting my query results to be displayed.
I have tried:
while ($row = $result->fetch_object())
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
Neither of these are working for me. I have looked at php.net for guidance. I am still confused with what to do. If anyone could help me, I would really appreciate it.
Always check your returns:
if( ! $result = $conn->query($query) ) {
die('Error: ' . $conn->error());
} else {
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
}
Also putting error_reporting(E_ALL); at the top of your script while you're developing it will help enormously as well.
You should really look into passing variables as parameters to your query instead of injecting them as variables directly into your query. This can lead to sql injection attacks.
Also, here's a quick example of how to write a query using PDO and mysql:
//Simple Query
$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
//Useful during development.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//mysql can have prepares depending on the version: http://stackoverflow.com/questions/10113562/pdo-mysql-use-pdoattr-emulate-prepares-or-not
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sth = $dbh->query("SELECT * FROM table");
var_dump($sth->fetchAll(PDO::FETCH_ASSOC));
//Now with pass params and a prepared statement:
$query = "SELECT * FROM table WHERE someCol = ?";
$sth = $dbh->prepare($query);
$sth->bindValue(1,"SomeValue");
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC));

Accessing Information from SQL While inside a form

I have a Query that looks something like this (I know its vulnerable to sql injection, its just a template):
$db = mysql_connect("host","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT *"
. " FROM Student" ;
$result = mysql_query($sql);
$students = mysql_fetch_assoc($result);
$numRows = mysql_num_rows($result);
Then I have this form:
<form name="form" id="form" method="post" action="page">
<select name="student" id="student">
<?
for ($i=0;$i<=$numRows;$i++){
echo "<option>" . $students['StudentID'] . "</option>";
}
?>
<option selected="selected">Please select a student</option>
</select>
This should print something like a drop down box with all the values from the table as items. However, I get a drop down box with 6 of the same items, in this case, I get 6 student Id's, but they are all the same ID. I have six students in the db, and I would like to display each of them as an option. What am I doing wrong?
TIA
Have a look at the examples of mysql_fetch_assoc. It will only return one record. In order to get all of them, you have to use it in a loop, e.g.:
$students = array();
while(($student = mysql_fetch_assoc($result))) {
$students[] = student;
}
and later:
<?php foreach($students as $student): ?>
<option><?php echo $student['StudentID']; ?></option>
<?php endforeach; ?>
or with a for loop (but it is not necessary if you don't need a counter):
<?php for($i = 0; $i < numRows; $i++): ?>
<option><?php echo $students[$i]['StudentID']; ?></option>
<?php endfor; ?>
(Note: I use the alternative syntax for control structures which imho is much more readable when mixing HTML and PHP)

Categories