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);
Related
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!
I am making an addition using php and I want to update the output to a column from my database.
This is what I have:
$api = "https://blockchain.info/ticker";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
$rate = $data["USD"]["sell"];
$symbol = $data["USD"]["symbol"];
$query = $db->query("SELECT * FROM bit_buysell WHERE status='1' ORDER BY id");
if($query->num_rows>0) {
while($row = $query->fetch_assoc()) {
echo ''.$row[name].' '.$row[currency].''.$row[price].'';
}
}
echo "<br><center> <b>1 BTC = " . $rate . $symbol . "</b></center></div>";
?></li>
<?php
$query = $db->query("SELECT * FROM bit_buysell WHERE id='1' ORDER BY id");
if($query->num_rows>0) {
while($row = $query->fetch_assoc()) {
echo ''.$row[prce].'';
$first_number = $rate ;
$second_number = $row[price];
$sum_totalbuy = $first_number * $second_number;
print ($sum_totalbuy);
}
}
I have been able to successfully add the the bitcoin price ticker and my custom value which returns the result I want in the print ($sum_totalbuy);
I want to therefore update my database by changing a table which automatically reference the $sum_totalbuy
Here is what i have done -
mysql_query("UPDATE bit_rates SET id='38' WHERE rate_from='$sum_totalsell'");
it didn't work and I have this too which I don't know how to go about it
Here is the code that manually update it via my dashboard, because I have to enter rate from and rate to:
<div class="card-body">
<form action="" method="POST">
<div class="form-group">
<label>List with exchange rates</label>
<select class="form-control" name="rid">
<?php
$query = $db->query("SELECT * FROM bit_rates ORDER BY id");
if($query->num_rows>0) {
while($row = $query->fetch_assoc()) {
echo '<option value="'.$row[id].'">'.gatewayinfo($row[gateway_from],"name").' '.gatewayinfo($row[gateway_from],"currency").' ('.$row[rate_from].' '.gatewayinfo($row[gateway_from],"currency").') = '.gatewayinfo($row[gateway_to],"name").' '.gatewayinfo($row[gateway_to],"currency").' ('.$row[rate_to].' '.gatewayinfo($row[gateway_to],"currency").')</option>';
}
} else {
echo '<option>No gateways</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>New exchange rate</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Rate from</span>
<input type="text" class="form-control" name="rate_from" placeholder="1" aria-describedby="basic-addon1">
<span class="input-group-addon" id="basic-addon1">= Rate to</span>
<input type="text" class="form-control" name="rate_to" placeholder="0.95" aria-describedby="basic-addon1">
</div>
</div>
<button type="submit" class="btn btn-primary" name="btn_update_rate"><i class="fa fa-check"></i> Update</button>
</form>
Please help me fix it.$sum_totalbuy
I need to store the print ($sum_totalbuy); to be updated in rate_from I will handle rate_to $sum_totalbuy
i have finally gotten it to work and this is what i did.
I had to do a total reconnect to my database then did the query update.
<?php
$server = "host";
$user = "user";
$pass = "pass";
$db = "db";
// Create connection
$conn = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Could not connect: " . mysqli_connect_error());
}
$sql = "UPDATE bit_rates SET rate_from='$sum_totalsell' WHERE id=38";
if (mysqli_query($conn, $sql)) {
echo "Sell Rate Update successful.";
}
$sql = "UPDATE bit_rates SET rate_to='$sum_totalbuy' WHERE id=37";
if (mysqli_query($conn, $sql)) {
echo "Buy Rate Update successful.";
}
else {
echo "Could not update: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
That directly updates the table in my sql
Thanks everyone for the time
i found the help here https://www.bitdegree.org/learn/mysql-update-syntax/
Hi :) I have a form that contains select lists and search button to show result from the database in a table. The first option of all my select lists are "ALL" (This is not from the database! Basically it supposes to bring all data from the database when user clicks Search without selecting any specific option). The current code works fine if I select real options (not the first option "ALL"). My question is: How to bring all the data if the user selects "ALL" in one select list, or in all select lists?
<!-- Search Components -->
<div class="row">
<form action="search.php" method="POST" name="" class="text-center">
<!-- Username -->
<div class="form-group col-sm-6 col-md-4">
<?php
include("dbc.php");
$qq = "SELECT DISTINCT username FROM users ORDER BY username";
$rr = mysqli_query($dbc,$qq);
while ($row = mysqli_fetch_array($rr)){
$username_array[] = $row['username'];
}
echo '<select class="form-control border-input" name="username">';
echo '<option value="all">ALL</option>';
foreach($username_array as $user){
$selected = '';
if($_POST['username'] == $user) {
$selected = 'selected="selected"';
}
echo '<option value="'.$user.'"'.$selected.'>'.$user.'</option>';
}
echo '</select>';
?>
</div>
<!-- Hospital Sections -->
<div class="form-group col-sm-6 col-md-4">
<?php
include("dbc.php");
$qqq = "SELECT DISTINCT section_name FROM hospital_sections ORDER BY section_name";
$rrr = mysqli_query($dbc,$qqq);
while ($row = mysqli_fetch_array($rrr)){
$sections_array[] = $row['section_name'];
}
echo '<select class="form-control border-input" name="section_name">';
echo '<option value="all">ALL</option>';
foreach($sections_array as $sec){
$selected = '';
if($_POST['section_name'] == $sec) {
$selected = 'selected="selected"';
}
echo '<option value="'.$sec.'"'.$selected.'>'.$sec.'</option>';
}
echo '</select>';
?>
</div>
<!-- Room Number -->
<!-- Qeblah Status -->
<div class="form-group col-sm-6 col-md-4">
<select class="form-control border-input" name="qeblah_status">
<option <?php if($_POST['qeblah_status'] == "ALL") echo 'selected="selected"'; ?> value="all">ALL</option>
<option <?php if($_POST['qeblah_status'] == "yes") echo 'selected="selected"'; ?> value="yes">Yes</option>
<option <?php if($_POST['qeblah_status'] == "no") echo 'selected="selected"'; ?> value="no">No</option>
</select>
</div>
<!-- Prayer Painting -->
<div class="form-group col-sm-6 col-md-4">
<select class="form-control border-input" name="prayer_painting">
<option <?php if($_POST['prayer_painting'] == "ALL") echo 'selected="selected"'; ?> value="all">ALL</option>
<option <?php if($_POST['prayer_painting'] == "yes") echo 'selected="selected"'; ?> value="yes">Yes</option>
<option <?php if($_POST['prayer_painting'] == "no") echo 'selected="selected"'; ?> value="no">No</option>
</select>
</div>
<!-- Fatwah -->
<div class="form-group col-sm-6 col-md-4">
<select class="form-control border-input" name="fatwa_status">
<option <?php if($_POST['fatwa_status'] == "ALL") echo 'selected="selected"'; ?> value="all">ALL</option>
<option <?php if($_POST['fatwa_status'] == "yes") echo 'selected="selected"'; ?> value="yes">Yes</option>
<option <?php if($_POST['fatwa_status'] == "no") echo 'selected="selected"'; ?> value="no">No</option>
</select>
</div>
<!-- Search Button -->
<div class="form-group col-sm-6 col-md-4">
<button type="submit" class="form-control btn btn-success btn-fill btn-wd" name="submit" value="Search"><i class="ti-search"></i> Search </button>
</div>
</form>
</div> <!-- .row Ends -->
<!-- Search Components Ends -->
<hr>
<!-- Search Results -->
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$section_name = $_POST['section_name'];
$qeblah_status = $_POST['qeblah_status'];
$prayer_painting = $_POST['prayer_painting'];
$fatwa_status = $_POST['fatwa_status'];
?>
<!-- The Table -->
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="content table-responsive table-full-width">
<table class="table table-striped table-bordered" style="border-style: hidden;">
<thead>
<th>Username</th>
<th>Section Name</th>
<th>Room Number</th>
<th>Qeblah</th>
<th>Prayer Painting</th>
<th>Fatwah</th>
<th>Condition</th>
</thead>
<tbody>
<?php
$selected_username = "";
if($username != 'All'){
$selected_username = "username = '$username'";
}
$selected_section_name = "";
if($section_name != 'All'){
$selected_section_name = "section_name = '$section_name'";
}
$selected_qeblah_status = "";
if($qeblah_status != 'All'){
$selected_qeblah_status = "qeblah_status = '$qeblah_status'";
}
$selected_prayer_painting = "";
if($prayer_painting != 'All'){
$selected_prayer_painting = "prayer_painting = '$prayer_painting'";
}
$selected_fatwa_status = "";
if($fatwa_status != 'All'){
$selected_fatwa_status = "fatwa_status = '$fatwa_status'";
}
include("dbc.php");
$q = "SELECT * FROM reports WHERE $selected_username AND $selected_section_name AND $selected_qeblah_status AND $selected_prayer_painting AND $selected_fatwa_status";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r)){
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['section_name']."</td>";
echo "<td>".$row['room_number']."</td>";
echo "<td>".$row['qeblah_status']."</td>";
echo "<td>".$row['prayer_painting']."</td>";
echo "<td>".$row['fatwa_status']."</td>";
echo "<td>".$row['report_status']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div> <!-- .content Ends -->
</div> <!-- .card Ends -->
</div> <!-- .col-md-12 Ends -->
</div> <!-- .row Ends -->
}
<!-- Search Results Ends -->
</div> <!-- .container-fluid Ends -->
</div> <!-- .content Ends -->
Instead of suggesting solutions, I had a go at the code myself. I modified the page a bit to make it work without a database. The important part is the bottom section.
I took out the table formatting, what I concentrated on is to build the query dynamicly based on the users's choice. To understand:
when a user selects ALL, there is nothing to filter on, so it is not even mentioned in the $query.
If a user selects ALL for all the fields, there is no need for a WHERE clause in the query ($query remains empty).
In a user selects more than one field to be other than ALL, each WHERE item must be separated by "AND". So we must add "AND" in the $query.
So the code I produced and tested is this (the bottom section, I did not change the rest):
<div class="content table-responsive table-full-width">
<?php
$where = "";
$query = "";
if($username != 'all'){
$query = "username = '$username'";
$where = "WHERE ";
}
if($section_name != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "section_name = '$section_name'";
$where = "WHERE ";
}
if($qeblah_status != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "qeblah_status = '$qeblah_status'";
$where = "WHERE ";
}
if($prayer_painting != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "prayer_painting = '$prayer_painting'";
$where = "WHERE ";
}
if($fatwa_status != 'all'){
if (strlen($query) != 0)
{
$query = $query . " AND ";
}
$query = $query . "fatwa_status = '$fatwa_status'";
$where = "WHERE ";
}
$q = "SELECT * FROM reports $where $query";
echo "<h1>$q</h1>\n";
?>
</div>
So your query changes dynamically. You can then run it and display the output.
Hope this helps!
The way I understand your question, you want to modify your $q query for items that are selected as "ALL".
The query limits the number of returned values in the WHERE part of it. So if a user selects ALL, just remove that part of query.
I will do for the username part, you can use the same concept for the rest:
$username_part = "";
if ($username != 'ALL')
{
$username_part = "username = '$username' AND";
}
$q = "SELECT * FROM reports WHERE $username_part section_name = '$section_name' AND qeblah_status = '$qeblah_status' AND prayer_painting = '$prayer_painting' AND fatwa_status = '$fatwa_status'";
This way, if a user selects ALL, you do not specify a WHERE condition on it. You just take it all. If a user selects one value, it adds a condition in the WHERE, based on the user's selection.
Managing the results of such queries is left to you :-)
Obviously, if the username is named "ALL", you have a problem :-)
This is my first post in this forum, despite being a devoted follower for years now.
I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form.
Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries.
It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances.
Now the thing got a little tricky.
I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number.
No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions.
This is my PHP code: `
<?php
$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['settore'];
$posts[2] = $_POST['ubicazione'];
$posts[3] = $_POST['numero'];
$posts[4] = $_POST['lotto'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$settore = $row['settore'];
$ubicazione = $row['ubicazione'];
$numero = $row['numero'];
$lotto = $row ['lotto'];
}
}else{
echo 'Lotto non presente in archivio';
}
}else{
echo 'Error';
}
}
// Insert
if(isset($_POST['insert']))
{
$data = getPosts();
$insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
try{
$insert_Result = mysqli_query($connect, $insert_Query);
if($insert_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resInsert = "1 nuovo dato inserito correttamente!";
}else{
$resInsert = "Nessun dato inserito";
}
}
} catch (Exception $ex) {
echo 'Errore '.$ex->getMessage();
}
}
// Edit
if(isset($_POST['update']))
{
$data = getPosts();
$update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
try{
$update_Result = mysqli_query($connect, $update_Query);
if($update_Result)
{
if(mysqli_affected_rows($connect) > 0)
{
$resAgg = "1 dato aggiornato correttamente!";
}else{
$resAgg = "Nessun dato aggiornato!";
}
}
} catch (Exception $ex) {
echo 'Error Update '.$ex->getMessage();
}
} ?>
`
HTML:
<form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">
<div class="form-group has-error" style="padding-top:30px">
<label class="col-xs-3 control-label" for="state-normal">ID</label>
<div class="col-lg-3">
<input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Settore</label>
<div class="col-md-6">
<input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
<div class="col-md-6">
<input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>"> </div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="state-normal">Numero</label>
<div class="col-md-6">
<input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>"> </div>
</div>
<div class="form-group has-success">
<label class="col-md-3 control-label" for="state-normal">Lotto</label>
<div class="col-md-6">
<input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>"> </div>
</div>
<div style="padding-top:16px">
<!-- Insert-->
<button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
<!-- Update-->
<button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
<a> </a>
<!-- Search-->
<button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
</div>
</form>
While the lot number was unique everything worked like a charm.
Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data.
I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work.
A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion.
Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto):
<?php if (isset($_POST['submitted'])){
include ('../mysql_connect.php'); // connessione al database
$category = 'lotto';
$criteria = $_POST['criteria'];
$query = "SELECT * FROM mappa WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idTab = $row['id'];
echo "<option>
$idTab </option>";
}
} // FINE if ?>
</select>
Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function.
Every help would really be appreciated! Thank you in advance for your answers.
You said that lotto is unique. So how come you are able to insert multiple rows with the same lotto?
Remove the unique constraint from the lotto column.
Try the following:
$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;
$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array
$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
echo "ID: " . $id_numbers_separated_array[$i];
echo "<br>";
}
Also try to run the query in your database management system to see the results.
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>