I've looked online and most drop down tutorials are for ratings e.g. matching the drop down value with a rating. I need to execute a query which corresponds to a number in the dropdown and the results to display once a user clicks submit, I don't want to use javascript. In my HTML :
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
The php :
<?php
$Link = mysql_connect($Host, $User, $Password);
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='1'";
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='2'";
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='3'";
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='4'";
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='5'";
}
WHILE($board = mysql_fetch_array($result)):
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />
;
endwhile;
?>
Try it this way, assuming you're already connected and have selected DB and that you're using your entire code inside the same file, since you are using action=""; this denotes executing as "self".
You also are not executing mysql_query() which I have added below.
Be sure to change xxx below with your DB credentials and your_db to your database's name.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$Host = "xxx";
$User = "xxx";
$Password = "xxx";
$Link = mysql_connect($Host, $User, $Password);
$db_selected = mysql_select_db('your_db', $Link);
if (!$db_selected) {
die ('Can\'t use that DB : ' . mysql_error());
}
if(isset($_POST['Submit'])){
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='1'");
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='2'");
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='3'");
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='4'");
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='5'");
}
WHILE($board = mysql_fetch_array($query)){
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />';
}
} // brace for if(isset($_POST['Submit']))
?>
</div>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
Note:
This enctype="multipart/form-data" isn't required if it's not going to be used to upload files.
If im not mistaken this is what you want? you just need to loop through the row in the tables and fetch it.
<div class="form">
<?php
$Link = mysql_connect($Host, $User, $Password);
$Query = "select * from books where product = 'hannibal' AND book = '1'";
$result = mysql_query($Query);
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$username = $row['username'];
$date = $row['date'];
$comments = $row['comments'];
?>
<h1>Subject : <?php echo $subject;?>
Posted by <?php echo $username;?> on <?php echo $date;?></h1><br />
<?php echo $comments;?>'; <br />
<?php
}
?>
</div>
Related
I have select tag, and dropdown menu, I want to delete item, when it's selected, like, on change
Here is my code:
$db = mysqli_connect('localhost', 'root', 'root', 'php_wood');
$sql = "SELECT * FROM posts";
$post = $db->query($sql);
if(isset($_GET['postDelete'])){
$delete = $_GET['postDelete'];
$sql = "DELETE FROM posts WHERE id = `$delete`";
mysqli_query($db, $sql);
}
I don't know where is mistake, here is my form
<form action="delete.php" method="get">
<select id="" onchange="this.form.submit();" name="postDelete">
<?php
if($post->num_rows > 0){
while($row = $post->fetch_assoc()){
?>
<option value="<?php echo $row['id']?>"><?php echo $row['title']?></option>
<?php
}
}
?>
<option value="">
</option>
</select>
</form>
I am working on a project and I need to find a way to count the table rows when a user has selected a Group from the drop-down box. I have tried some ways in which I can show, but also I am not grasping how this concept would work. I am also using an SQL database which works perfectly, the rows is giving me a hard time though.
<!DOCTYPE html>
<html>
<body>
<form action="Web4.php" method="post">
<label form="return">Group: </label>
<select id="return" name="return">
<option value="G">All</option>
<option value="A">Group A</option>
<option value="B">Group B</option>
<option value="C">Group C</option>
<option value="D">Group D</option>
<option value="E">Group E</option>
</select>
<input type="submit">
</form>
<?php
$servername = "servername";
$username = "myusername";
$password = "mypassword";
$dbname = "mydatabasename";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection Failed: ". $conn->connect_error);
}
if(!isset($_POST["return"])) {$selval ="G";}
else {$selval = $_POST["return"];}
if($selval == "G"){
$scores = mysqli_query($conn, "select * from test_scores;");
}
elseif($selval == "A"){
$scores = mysqli_query($conn, "select * from test_scores WHERE group_id='A';");
}
elseif($selval == "B"){
$scores = mysqli_query($conn, "select * from test_scores WHERE group_id='B';");
}
elseif($selval == "C"){
$scores = mysqli_query($conn, "select * from test_scores WHERE group_id='C';");
}
elseif($selval == "D"){
$scores = mysqli_query($conn, "select * from test_scores WHERE group_id='D';");
}
else{
$scores = mysqli_query($conn, "select * from test_scores WHERE group_id='E';");
}
?>
<table border="1">
<tr><th>Record ID</th><th>Math Score</th><th>Reading Score</th><th>Writing Score</th></td></tr>
<?php
while($row = mysqli_fetch_array($scores)){
echo "<tr><td>".$row["group_id"]."</td><td>".$row["math"]."</td><td>".$row["reading"]."</td><td>".$row["writing"]."</td></tr>\n";
}
?>
</table>
</body>
</html>
I have a PHP form which saves user data to a MySQL database.
I want to show the user which information is held about them and display it in a form in order for them to update or edit the values.
I have a problem in getting the user's saved data from the database in a PHP loop and show that to user in order for them to update or edit it.
Below is the piece of code:
<?php
$id = $_GET['id'];
$conn = mysqli_connect('localhost', 'phpmyadmin', 'Test#2000', 'user');
$sql1 = "SELECT * FROM usr WHERE id='$id'";
$result = mysqli_query($conn, $sql1);
$row = mysqli_fetch_assoc($result);
?>
<fieldset><label>Birthday</label>
<select name="birthday">
<?php
for ($i = 1300; $i <= 1397; $i++) {
echo "<option >$i</option>";
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
I want to show into the form's Select input the birthday value that user selected originally, in order to edit or update by user.
The <select> children elements <option> does support a selected tag to indicate that it was the selected value, so by adding the selected tag like so <option value='1' selected> you can have that as the selected value.
You'll also want to probably add the $i value into your option element to ensure that the values are being submitted properly.
Mozilla documentation:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select
I have edited your code in this way.
<?php
$id = $_GET['id'];
$conn = mysqli_connect('localhost', 'phpmyadmin', 'Test#2000', 'user');
$sql1 = "SELECT * FROM usr WHERE id='$id'";
$result = mysqli_query($conn, $sql1);
$row = mysqli_fetch_assoc($result);
?>
<fieldset><label>Birthday</label>
<select name="birthday">
<?php for ($i = 1300; $i <= 1397; $i++) {
echo "<option" . (($i == $row['birthdayYear']) ? 'selected="true"' : '') . ">$i</option>";
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
Hope this helps, thanks.
A.) WITH PDO MODULE
It is best practice today to use prepared statements to avoid SQL injection. This is done through the PDO object.
Set for select the autocomplete="off" attribute, because Firefox apparently has a bug with the selected="selected" that needs this to be set.
See if it is the user's birthday, we can use intval to compare.
<?php
$id = $_GET['id'];
$host = 'localhost';
$username = 'phpmyadmin';
$password = 'Test#2000';
$db_name = 'user';
$conn = new PDO('mysql:host:=' . $host . '; dbname=' . $db_name, $username, $password);
$sql1 = "SELECT * FROM usr WHERE id = :id;";
$stmt = $conn->prepare($sql1);
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<fieldset><label>Birthday</label>
<select name="birthday" autocomplete="off">
<?php for ($i = 1300; $i <= 1397; $i++) {
if($i === intval($row['birthdayYear'])){
echo "<option selected='selected'>$i</option>";
} else {
echo "<option>$i</option>";
}
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
B.) Please at least try option A.), but if it doesn't work:
<?php
$id = $_GET['id'];
$conn = mysqli_connect('localhost', 'phpmyadmin', 'Test#2000', 'user');
$sql1 = "SELECT * FROM usr WHERE id='$id'";
$result = mysqli_query($conn, $sql1);
$row = mysqli_fetch_assoc($result);
?>
<fieldset><label>Birthday</label>
<select name="birthday" autocomplete="off">
<?php for ($i = 1300; $i <= 1397; $i++) {
if($i === intval($row['birthdayYear'])){
echo "<option selected='selected'>$i</option>";
} else {
echo "<option>$i</option>";
}
}
?>
</select>
<fieldset>
<button name="btn" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
</div>
</body>
</html>
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);
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);
?>