PHP mySQL select via html select - php

I'm trying to do a select from a table based on the post value of an HTML select box. I'm getting no results at all, I'm echoing out the post value no problem. The statement works on it's own but won't when I use the select form to populate it. This is just my test I will be adding other options to the dropdown box.
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1=Militaria";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
?>
Here is the html form I'm using, can anyone tell me where I'm going wrong, should I do it a different way etc, I'm new to php? Thanks!!
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="Militaria">Militaria</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>

mysql_fetch_array() should receive resorce as a parameter. Try mysql_fetch_array($sql).

Quote around 'Militaria' and mysql_fetch_array($sql)
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1='Militaria'";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
$sql = mysql_query($sql);
while ($row = mysql_fetch_array($sql)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
}
?>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="Militaria">Militaria</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>

You have two mistakes in your php code.
1st : quote around Militaria. The query should be, $query = "SELECT * FROM listings WHERE category1='Militaria'";
2nd : mysql_fetch_array accepts executed query's result as parameter. It should be, $row = mysql_fetch_array($sql)
Final code:
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1 = 'Militaria'";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($sql)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
?>

Related

edit select option values

I am trying to edit my form. I want to get selected value selected in selection list.
I have created function to store values in database, and it works. Below is html code I use and function below to insert values in database.
// insert values in database
<label>Dobavljač</label>
<select class="form-control" name="dobavljac" required>
<?php dobavljac() ?>
</select>
function dobavljac(){
$sql=mysqli_query($link, "SELECT * FROM `partneri` WHERE `Dobavljac`='1'
order by `PartnerId` asc ");
echo '<option value="">Izaberi dobavljača</option>';
while($record = mysqli_fetch_array($sql)) {
echo '<option value= "' .$record['PartnerId']. '">' . $record['PartnerNaziv'] . ' </option>';
}
}
// edit values
First I retrieve information from database
$id=$_GET['id'];
$sql = "SELECT * FROM materijali where Id=$id ";
$q = $conn->query($sql);
$r = $q ->fetch();
if ($r) {
$dobavljac=$r['Dobavljac'];
I want to get selected value in box
<label>Dobavljač</label>
<select class="form-control" name="dobavljac" value="<?php echo $dobavljac; ?>">
<?php dobavljac() ?>
</select>
Probably I am not doing it the right way, any advice would be appreciated
Try this
<label>Dobavljač</label>
<select class="form-control" name="dobavljac" value="<?php echo $dobavljac; selected?>">
<option value=<?php echo $dobavljac?> selected>
<?php dobavljac() ?>
</option>
</select>
Try this...
$id=$_GET['id'];
$sql = "SELECT * FROM materijali where Id=$id ";
$q = mysql_query($query);
echo "<select name="dobavljac" class="form-control">";
while (($row = mysql_fetch_row($q)) != null)
{
echo "<option value = '{$row['Dobavljac']}'>";
echo $row['Dobavljac'];
echo "</option>";
}
echo "</select>";

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));

Can't display data from my database

I am trying to allow users to select restrictions from my database by using 3 drop down boxes. I have set them up and I have connected to my database. However, once the user hits the submit button, I can't get data to be displayed in a table. Here is my 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 can't get the data to be displayed in a table at all. I have tried multiple ways, but I am still getting errors. To ensure that I am connected to my database, I used var_dump($row) to make sure, and that worked okay. So that is not the problem. Does anyone have any idea what is wrong with my code?
When you retrieve the data from your result set you're fetching it as an object:
while ($row = $result->fetch_object()){
But when you come to display it, you refer to it as an array:
echo "<tr><td>";
echo $row['Year']; // array syntax.
You should be using object syntax:
echo "<tr><td>";
echo $row->Year; // object syntax.
If you check your error logs you should see a lot of messages to this effect.

dropdown list based on checkbox

i have few checkboxes named as HR,visitor,gaurd now i want to get which ever chckbox is selected according to it names of the employee belonging to that team whether HR or Guard or visitor to be shown in dropdown list
<select name=cmbname id="cmbname" width='50%'>
ALL
`
$objDB->SetQuery($sql);
$res = $objDB->GetQueryReference();
if(!$res)
exit("Error in SQL : $sql");
if($objDB->GetNumRows($res) > 0)
{
while($row = mysql_fetch_row($res))
{
print("
<option value='{$row[0]}'>{$row[0]}</option>");
}
}
mysql_free_result($res);
?>'
Himani ,
Try this. Hope it will be useful to you. Instead of text-area you can use drop-down.
Try this way gives you solution
<script type="text/javascript">
//javascript
function clicked_checkbox()
{
document.form.submit();
}
</script>
<?php
$hr = isset($_REQUEST['HR'])?$_REQUEST['HR']:false;
$guest = isset($_REQUEST['guest'])?$_REQUEST['guest']:false;
$visiter = isset($_REQUEST['visiter'])?$_REQUEST['visiter']:false;
//Prepare query with retrieved value and put value in Dropdown
$sql = 'select * from table ';
if($hr) { $sql .= "where user = '$hr'" };
if($guest) { $sql .= "where user = '$guest'" };
if($visiter) { $sql .= "where user = '$hr'" };
$objDB->SetQuery($sql);
$res = $objDB->GetQueryReference();
if(!$res)
exit("Error in SQL : $sql");
if($objDB->GetNumRows($res) > 0)
{
while($row = mysql_fetch_row($res))
{
print("<option value='{$row[0]}'>{$row[0]}</option>");
}
}
mysql_free_result($res);
?>
//on change of checkbox we'll call above function and set data to dropdown
<form name='form' method='get' action='#'>
<input type="checkbox" id="checkbox_HR" name="HR" value="true" <?php if($hr) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
<input type="checkbox" id="checkbox_guest" name="guest" value="true" <?php if($guest) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
<input type="checkbox" id="checkbox_user" name="visiter" value="true" <?php if($visiter) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
</form>
like this you can achieve :)

insert selected option into table

I have this code and I'm trying to put the selected state in a subcat table.
So far it returns an empty value. I'm not sure if this is clear or not, but all I want is: select a state from the select option and submit it. I want to get the selected state name into my table subcat.
enter <?php
include("connect.php");
$state = $row['states']; //Select name
if (isset($_POST[submit])){
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form> here
Thanks
Change $state = $row['states'] to $state = $_POST['states']
<?php
include("connect.php");
if (isset($_POST[submit]))
{
$state = $_POST['states']; //Select name
$query = "INSERT INTO subcat (sub_name) VALUES ('$state')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo "<select name='states'>
<option value=''>Select a state</option>";
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='$row[id]'>$row[name]</option>"; // if you want to
//get the name into table, then use like this
//echo "<option value='$row[name]'>$row[name]</option>"; or
//echo "<option>$row[name]</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="Continue" />
</form>
Try this:
enter <?php
include("connect.php");
if (isset($_POST[submit])){
$state = $_POST['states'];
$query = "INSERT INTO subcat (sub_name) VALUES ('".mysql_real_escape_string($state)."')";
mysql_query($query) or die(mysql_error());
}
?>
<form action="" method="post" name="form">
<?php
$sql = mysql_query("SELECT * FROM state");
echo '<select name="states" id="states">
<option value="">Select a state</option>';
while ($row = mysql_fetch_assoc($sql)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
<input type="submit" name="submit" value="Continue" />
</form> here
Dont forget to use mysql_real_escape_string to prevent SQL injections. I have replaced $state = $row['states']; with $state = $_POST['states'];
I dont know where u got $row from...
The above will insert the states name into the database.

Categories