I am trying to search my SQL database with a simple search form and then return the data to the screen.
For example, the user can select a year, then all the row results from the table display all of the information for that entry. Here is my form:
<form class="" method="POST" action="availability.php" enctype="multipart/form-data">
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<input class="btn btn-blue-grey" type="submit" value="submit">Search
<i class="fas fa-search ml-1"></i>
</input>
</form>
And here is my PHP
if(isset($_POST['submit'])) {
$year = $_POST['year'];
var_dump($year);
var_dump($_POST);
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll(); }
and my HTML
<ul>
<?php foreach($data as $stmt) { ?>
<li><?php echo $stmt['cruise'];?></li>
<li><?php echo $stmt['year'];?></li>
<?php } ?>
</ul>
At the minute, the form submits, but I get nothing populating the list.. Any help would be appreciated.
You can try to use this query :
$year = $_POST['year'];
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll();
$stmt->bindParam(':year',$year,PDO::PARAM_STR); <-- does this need to be PARAM_INT ?
also have you var_dump'ed $year = $_POST['year']; to make sure you are getting a value?
You could turn on error_reporting and see if you get any useful errors
you must change a few thing,
first, edit the select tag to:
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
There is a condition that seems it is wrong.
so, change your html code to
if($_POST) {
$year = $_POST['year'];
$stmt = $pdo->prepare("SELECT * FROM availability WHERE year = :year");
$stmt->execute(array("%$year%"));
// fetching rows into array
$data = $stmt->fetchAll();}
Related
I have basic question about storing $variable data and later use in html script, anyone who can help me? Right now, the variable $gset is not stored.
<?php
// Update Strictness value
if(isset($_POST['strictness'])){
$gset = $_POST['strictness'];
$strictnessUpdate = "UPDATE users SET strictness = '$gset' WHERE user_id = 1";
mysqli_query($conn, $strictnessUpdate);
echo "strictness value updated";
}
?>
<form method="POST" class="form-align" action="">
<h5 class="my-6">Current Strictness :</h5> <?php echo $gset; ?><br>
<select name="strictness" required>
<option value=""></option>
<option value="15">15</option>
<option value="31">31</option>
</select>
<input type="submit" name="substrict" value="CHANGE">
</form>
<?php
$_grabStrictness ="SELECT strictness FROM users WHERE id = 1";
$gs_query = mysqli_query($conn, $_grabStrictness);
$gs_result = mysqli_fetch_array($gs_query);
if ($gs_result > 0) {
while ($result = mysqli_fetch_array($gs_query)) {
$gset = $result['strictness'];
}
}
if(isset($_POST['strictness'])){
$gset = $_POST['strictness'];
$strictnessUpdate = "UPDATE users SET strictness = '$gset' WHERE user_id = 1";
mysqli_query($conn, $strictnessUpdate);
echo "strictness value updated";
}
?>
<form method="POST" class="form-align" action="setStrictness(<?php $conn ?>)">
<h5 class="my-6">Current Strictness :</h5> <?php echo $gset; ?><br>
<select name="strictness" required>
<option value=""></option>
<option value="15">15</option>
<option value="31">31</option>
</select>
<input type="submit" name="substrict" value="CHANGE">
</form>
In my form, I generate the select options from my MySQL data table. But when I submit the form without any value, it returns to a blank page and does not show any validation error. When I select a value and submit the form, it inserts the value to MySQL table. No MySQL or PHP error is thrown. I am assuming the problem is the query for the select option is not running. But if it is the problem, what should be the good practice to avoid this problem?
My form is:
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$ad_di = "";
$ad_di_err = "";
if (empty(trim($_POST["ad_di"]))) {
$ad_di_err = "District cannot be empty.";
} else {
$ad_di = trim($_POST["ad_di"]);
}
if (empty($ad_di_err)) {
$sql = "INSERT INTO address (ad_di) VALUES (?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("i", $p_ad_di);
$p_ad_di = $ad_di;
if ($stmt->execute()) {
$id = $mysqli->insert_id;
header("location: add.php?id=$id&update=success");
}
$stmt->close();
}
}
}
?>
<form id="acEdit" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="contact-form">
<div class="row">
<div class="col-3">
<div class="form-group">
<label>District</label>
<select name='ad_di' id='ad_di' class='custom-select'>
<option value=''>Select one ...</option>
<?php
$qDistrict = "SELECT * FROM districts order by name ASC";
echo "<select name='ad_di' id='ad_di' class='custom-select'><option value=''>Select one ...</option>";
foreach ($mysqli->query($qDistrict) as $rowDistrict) {
echo "<option value={$rowDistrict['id']}>{$rowDistrict['name']}</option>";
}
echo "</select>";
?>
</select>
<span class="invalid-feedback"><?php echo $ad_di_err; ?></span>
</div>
</div>
</div>
</form>
The above query for select options returns as following when the page is loaded first,
<select name="ad_di" id="ad_di" class="custom-select">
<option value="">Select one ...</option>
<option value="28">Dist A</option>
<option value="11">Dist B</option>
<option value="35">Dist C</option>
<option value="33">Dist D</option>
</select>
But when the validation error occurs, the returning page doesn't have any options, just returns
<select name="ad_di" id="ad_di" class="custom-select">
<option value="">Select one ...</option>
</select>
Below is the code where i created a drop down list, i am able to retrieve data from MySQL but i have to repeat the option step for every field, how can I setup a code for the drop down so i can just shorten to call it once in selection list, like in a for loop..also how do i create a error message to display if there is no selection, and if i select a data from the list it stores in the database
<form action="sign.php" method="post">
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<label for="manager">manager</label>
<select name = "manager">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<label for="senior">Senior</label>
<select name = "Senior">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<input type="submit" name="register" value=" Click to Add"></button>
</form>
Use array and run query once to set options in array.
<?php
$optionArray = array();
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$optionArray[] = '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
<form action="sign.php" method="post">
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?php
foreach($optionArray as $row)
{
echo $row;
}
?>
</select>
how can I setup a code for the drop down so i can just shorten to call it once in selection list, like in a for loop.
Just create a loop. though it should be foreach, not for.
First collect your data,
$people = $pdo->query('Select name from people order by name')->fetchAll(PDO::FETCH_COLUMN);
$sections = [
'employee_name' => 'Employee name',
'manager' => 'Manager',
'senior' => 'Senior',
];
and then loop it over
<form action="sign.php" method="post">
<?php foreach ($sections as $label => $caption): ?>
<label for="<?=$label?>"><?=$caption?></label>
<select name = "<?=$label?>">
<option value=""> -----------Select----------- </option>
<?php foreach ($people as $name): ?>
<option><?=$name?></option>
<?php endforeach ?>
</select>
<?php endforeach ?>
<input type="submit" name="register" value=" Click to Add"></button>
</form>
Instead of repeating this every time you can create a method which performs the same task.
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?=loadOptions('name','people');?> <!--shortcut way to echo in php-->
</select>
<?php
function loadOptions($field,$table){
$stmt = $pdo->prepare('Select '.$field.' from '.$table);
$stmt->execute();
$options='';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$options .= '<option>'.$row['name'].'</option>';
}
return $options;
}
?>
I have a select box connect to database for countries, it works but trying to keep the selected data in the form clears itself out. I have tried adding a selected but gives error
<div class="form-group">
<label>Country</label>
<?php
$sql = "SELECT * FROM countries ";
$result = query($sql);
?>
<select class="form-control input-lg box" id="country" name="country">
<option value="">Select a country</option>
<?php
$i = 0;
while (($row = mysqli_fetch_assoc($result)) != false) {
?>
<option value="<?=$row["country_id"];?>"><?=$row["country_name"];?></option>
<?php
$i ++;
}
?>
</select>
</div>
Assign the return value of a ternary operator to the variable $selected and add it to the option tag
<?php
$selected = ($_POST['country'] == $row["country_id"])?"selected":"";
?>
<option value="<?=$row["country_id"];?>" <?=$selected ?>>
<?=$row["country_name"];?>
</option>
With this way, I get results from database and "print" them. But I don't know how I will update those results when I press the submit button!!! I just need an idea or something for the next step. Thank you in advance!!!
Here is an example of my code...
<?php // DATABASE QUERY
$query="SELECT countdown_module, hometeam_position
FROM jos_gm_nextmatch
WHERE id = 1";
$result=mysql_query($query);
// DATABASE VARIABLES
$countdown_module = mysql_result($result,$i,"countdown_module");
$hometeam_position = mysql_result($result,$i,"hometeam_position"); ?>
<form action="***.php" method="post" name="form">
<input name="countdown_module" value="<?php echo $countdown_module ?>" type="text" />
<select name="hometeam_position">
<option value="<?php echo $hometeam_position ?>"><?php echo $hometeam_position ?></option>
<option disabled="disabled" value="...">...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">3</option>
<option value="5">5</option>
<input name="submit" type="submit" value="UPDATE" />
</form>
You would use the form action to redirect to a script where you do the update. On this script you can access the the forms input elements by using the $_POST array. As for how to do update queries, an example could be:
$query="UPDATE mytable
SET title = '".$title."', name = '".$name."', date = '".$date."'
WHERE id = ".$id;
$result=mysql_query($query);
UPDATE:
An example of the script could be:
$hometeam_position = $_POST['hometeam_position']; //access the selected option when submitting
$countdown_module = $_POST['countdown_module']; //access the text input
$query = "UPDATE jos_gm_nextmatch SET countdown_module = '".$countdown_module."', hometeam_position = '".$hometeam_position."' WHERE id = 1";
$result=mysql_query($query);
You could before or after selecting the fields from the database simply increment them
...
if (isset($_POST['submit'])) {
$stmt = "UPDATE jos_gm_nextmatch
SET countdown_module = " . $_POST['countdown_module'] .
" , hometeam_position =" . $_POST['hometeam_position'] .
" WHERE id=1";
mysql_query($stmt);
}
mysql_close();