Problem passing selected options - POST method - php

I'm having problems with the passing of the selected options by the client (the select box is a multiple choice select box built with jquery). Basically, through the POST method, it's passing just the last option selected by the client, ignoring all the others.
<form action="inserimento_fraseP.php" method="post">
sigla Frase P <input type="text" name="siglaP" required/> <br />
significato: <input type="text" name="significatoSiglaP" required/> <br />
<br />
sigla Frase H: <select class="mul-select" multiple="true" name="siglaH"> <?php select('siglaH', 'FraseH'); ?> </select>
<input type="submit" value="inserisci"/>
</form>
<?php
function select($name, $tabella){
include 'connessione_db.php';
$sql = "SELECT DISTINCT $name FROM $tabella ORDER BY $name";
echo $sql;
$result = $conn->query($sql);
echo "<option></option>";
while($row = $result->fetch_assoc())
{
echo "<option name='$row[$name]' value = '$row[$name]' > $row[$name] </option>";
}
}
?>

PLEASE change the name=siglaH[]
<select class="mul-select" name="siglaH[]" multiple="multiple">
---
</select>
you can check the by
print_r(implode(',', $_POST['siglaH']));
And ya one more thing I would like to tell you in your database store this field as varchar
Please set select name = siglaH[] then only you will get multiple data

I edited the name of the select from "siglaH" to "siglaH[]" and in the .php file the action refers to I was able to handle the selected options as an array.

Related

How can I prevent the ID from showing in the datalist element?

I am trying to utilize the datalist element. Everything is working with 1 little hitch. The selectable list is showing 2 columns, both the street_id and street columns. I need the street_id that will be submitted but dont want the street_id to show in the datalist.
<?php
require 'connect_mysqli.php';
$sql = "SELECT * FROM streets";
$result = mysqli_query($con, $sql) or die ("Error " . mysqli_error($con));
?>
<form action="test.php" name="test" method = "post">
<datalist id="street" name="streets">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street']; ?></option>
<?php
}
?>
</datalist>
<input type="text" name="street_val" id="test" autocomplete="off" list="street">
<input type="submit" value="Submit">
</form>
<?php
mysqli_close($con);
//test the output value
echo $_POST['street_val'];//
?>
You have coded a select list - which has separate values for display and returned values. In the datalist, you only need value="" for options and then it will only return that value. Also better to keep the server code and display code separate: i.e. populate or build the array in the PHP with your query, then in the HTML only display it.

How to make search form where user has three columns to search.Using PHP AND SQL AND HTML

I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth

get selected value of a drop down which is populated with results from an SQL query

So I have a drop down populated with the names based on an SQL query. I want to be able to see which option the user selected before they pressed submit and use this as a variable on a separate php file. I assume I will need to use session variables? I'm a bit lost so any help would be appreciated. I have the following code so far:
<form name="ClientNameForm" id="ClientNameForm" action="ClientDetails.php">
<input type="text" name="ClientName" id="ClientName" placeholder="Type Service User's name here:" style="width: 200px"/><br/><br/>
<select name="Name_dropdown" id="name_dropdown" style="width: 200px" >
<?php
$ClientName_Query= "SELECT CONCAT(FName, ' ', SName) AS FullName FROM ClientDetails";
$ClientName_Result= mysql_query($ClientName_Query) or die (mysql_error());
while ($row= mysql_fetch_array($ClientName_Result)){
echo "<option> $row[FullName] </option>";
}
?>
</select><br/><br/>
<input type="submit" name="submit_btn" id="submit_btn" value="Submit"/>
</form>
In your ClientDetails.php file the value will be available using,
$name = $_POST['Name_dropdown'];
If you need to change a setting in the form document before submitting you can use jQuery. Something like
$('#name_dropdown').change(function(){
var option = $(this.options[this.selectedIndex]).val();
});

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

List option values fail to insert into the database

I've created a php form to insert values into a database.
One of my form options is a dynamic list populated with fields from another table.
I first created the form without the dynamic option, and all data inserted just fine (and still does).
Now I'm attempting to include the code below, and while it displays the option values properly, the value fails to insert. Any advice?
<?php
/*
* LIST ALL CATEGORIES
****************************************/
include('../dbconnection.php');
$query = 'SELECT category_id, category_name FROM ingredient_categories';
$result = mysql_query($query);
echo '<select>';
while ($ingredientCategoryOption = mysql_fetch_array($result)) {
echo '<option value="'.$ingredientCategoryOption[category_id].'">'.$ingredientCategoryOption[category_name].'</option>';
}
echo '</select>';
?>
I had created something similar yesterday. The $polls array is passed to the view in CodeIgniter in the $this->load->view('poll.php', $data['polls']), while you do it in the page itself. However, you can have the general idea.
<FORM id="formPoll" class="question" name="createpoll" action="<?php echo base_url()?>index.php/poll/selectOption/" method="POST">
<select name="poll_list">
<?php
foreach($polls as $poll){
echo "<option name='poll_table'>$poll->name</option>";
}
?>
</select>
<div id="input">
Poll name: <input type="text" name="name"></input>
Title: <input type="text" name="title"></input>
</div>
<div id="options">
Option: <input type="text" name="option"></input>
</div>
<input type="submit"></input>
</FORM>
Some ideas:
Check if $results is not empty before using it
Give your <select> form a name, as I showed above
Check if $ingredientCategoryOption is not null or is something returned.
Check your database connection

Categories