php dropdown selection Inserts only the first word in the table - php

<center><?php
include "config.php"; // Database connection using PDO
//$sql="SELECT name,id FROM student";
$sql="SELECT Product_Name, id FROM stockcount";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
?>
<select id = 'ProductName' name='productName' onchange="" >Product_Name </option>"
<?php
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[Product_Name]>$row[Product_Name
]</option>";
/* Option values are added by looping through the array */
}
?>
</select>
</center><p></P>
This code shows all the product names from the stockcount table.
<?PHP
include ('config.php');
$date = $_POST['date'];
$productname = $_POST['productName'];
$cartons = $_POST['cartons'];
$send_to = $_POST['send_To'];
$sql = "INSERT INTO storerequest (Date, Product_Name, Cartons, Send_To) VALUES ('$date','$productname', '$cartons', '$send_to')";
if ($conn->query($sql)===TRUE) {
header("Location:orderrequest.php");
}
else {
echo "Error is " .$sql."<br>". $conn->error;
}
$conn->close();
?>
This adds the selection from the dropdown to the storerequest table.
Now the problem is if i select an option named "Motor Car" from the down. It inserts in the storerequest table as "Motor" only. When i changed the product name to "Motor-Car" then it inserts as "Motor-Car". It basically stores only the 1st word. Please experts help me solve this problem

You forgot the " signs for the value:
echo '<option value="'.$row[Product_Name].'">'.$row[Product_Name].'</option>"';

need to change echo statement.
Change From
echo "<option value=$row[Product_Name]>$row[Product_Name]</option>";
To
echo "<option value='$row[Product_Name]'>$row[Product_Name]</option>";

Your problem is that you are not wrapping the value of your value attribute in either single or double quotes.
i.e. value=$row[Product_Name]
echo "<option value=$row[Product_Name]>$row[Product_Name]</option>";
You dont have to wrap the attributes value in quotes, BUT YOU DO if the value has a space in it like Motor Car
So you must do
echo "<option value='$row[Product_Name]'>$row[Product_Name]</option>";
Or
echo '<option value="' . $row['Product_Name'] . '">' . $row['Product_Name'] . '</option>';

Yes, or if you need the double quotes for html just escape them :
`echo "$row[Product_Name]";

Related

Select Option inside value with php

I have a trouble about select option value choosing with PHP
Multiple select box is showing for state and city. Jquery loads as ajax method for database. And I need to reach "option value" inside value. I will show the problem inside below codes.
<?php
function load_country() {
include 'includes/db.php';
$sql = "SELECT * FROM ilce ORDER BY name";
mysqli_set_charset($con, "UTF8");
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)) {
$output .= '<option name="' . $row['name'] .'" value="' .
$row["ilce_id"].'">' . $row["name"]. '</option>';
}
return $output;
}
?>
<select class="form-control" name="state" id="state">
<option>Choose State</option>
<?php
echo load_country();
?>
</select>
<?php
$state = mysqli_real_escape_string($con, $_POST['state']);
echo $state;
?>
<option value="5">New York</option>
$state is showing for me Example : "id" => 5
Thus, I want to reach "New York", inside value.
Please help me
Thanks
The text content of an <option> element is not posted to the server, only its value.
If you're inserting the selected state into a database (like in a user table), you might just insert the numeric state ID and join the two tables when you need to display the information.
Alternatively, you can fetch an array of all states indexed by their IDs and then reference that array:
while ($row = mysqli_fetch_array($result)) {
$allStates[$row['ilce_id']] = $row['name'];
}
$stateId = $_POST['state'];
$thisState = $allStates[$stateId];
echo $thisState;
Or just fetch the one row that you need by its ID, depending on what you need.
A less desirable solution is to set the <option> value to the row's name rather than its ID:
$output .= '<option value="' . $row["name"] . '">' . $row["name"] . '</option>';
But that seems to defeat the purpose of using a relational database.
Also see Get Text From Tag Using PHP.

Retain Value of Select Tag after Submit - PHP

I'm trying to add subject to a teacher's workload. I have a validation before inserting the user input to my workload table, mostly for detecting schedule conflict.
Now, what I want is to retain the selected value of the user and display it again after the validation fails. So that the user doesn't have to select the subject name, class name, and class adviser again.
I've attached my code for the class adviser selection.
<?php
$link = mysqli_connect("localhost", "root", "", "smis");
$sql = "SELECT * FROM teacherData";
$result = mysqli_query($link,$sql);
echo "<select id='modalINPUT' name='teacherID' required>";
echo"<option value=''>Select Adviser</option>";
while ($row = mysqli_fetch_array($result))
{
echo "<option value='".$row['teacherID']."'>".$row['Fname'] ." ". $row['Mname'] ." " .$row['Lname'] . "</option>";
}
echo "</select>";
?>
/*
Once validation fails, is there a way where I can display the selected value?
Like display the name of the teacher.
*/
Yes, you can use:
$teacherID = !empty($_POST['teacherID']) ? $_POST['teacherID'] : '';
right before your sql query
Then to display selected value on select box, you can check if posted id matches with current id and print out selected parameter for the according option field:
echo '<option value="'.$row['teacherID'].'"'.($teacherID == $row['teacherID'] ? ' selected="selected"' : '').'>'.htmlspecialchars($row['Fname']) .' '. htmlspecialchars($row['Mname']) .' ' .htmlspecialchars($row['Lname']) . '</option>';
EDIT: Take a look on my edited answer - use single quotes for better performance (so PHP doesnt have to scan your double quoted string for vars), and ALWAYS process your information, which you get from DB with htmlspecialchars, so you don't mess up your html, when something improper is saved into DB
EDIT: Also do not select all data from MYSQL table, unless you need to. To gain performance, select only fields you need in your query:
$sql = 'SELECT teacherID, Fname, Mname, Lname FROM teacherData';
You could compare the posted value against the id of the current row. And add selected attribute if the values are the same.
// create $selected variable to get "selected" or "":
$selected = isset($_POST['teacherID']) && $_POST['teacherID'] == $row['teacherID']
? 'selected' : '' ;
// add $selected to the <option> tag:
echo "<option value='".$row['teacherID']."' $selected>"
. $row['Fname'] ." ". $row['Mname'] ." " .$row['Lname']
. "</option>";

Dropdown box in php getting partial values from mysqli database

When I am trying to list all the employee names from the database to assign a job for a particular person in the dropdown box. The Output value only show the initial or the First name of Employee. The other names of the employee (Last names) are not posted in the php.
Actually the names after first spaces are missing.
Here is my code...
<pre>
<tr>
<td><label>Assigning To</label></td><td><label>:</label></td>
<td>
<?php
$result = mysqli_query($conn, "SELECT * FROM userdetails WHERE UserGroup='DigitizationArtist' || UserGroup='DigitizationArtistQC' || UserGroup='GraphicArtist' || UserGroup='GraphicArtistQC')");
echo "<select name='ArtistName' value=''>";
echo "<option value=''></option>";
while($r = mysqli_fetch_array($result))
{
echo "<option value=" .$r['Name'] .">".$r['Name']. "</option>";
}
echo "</select>";
?>
</td>
</tr>
<pre>
This is the getting value php code...
$ArtistName = mysqli_real_escape_string($conn, $_POST['ArtistName']);
I am getting the out for "S Gowri Shankar" is "S"
I am getting the out for "Selva Kumar" is "Selva"
Please advise. What is wrong in these coding? Else the php always ignore the space after text in checkbox values.
You value attributes has missing closing quotes:
echo "<option value=" .$r['Name'] .">".$r['Name']. "</option>";
Should be:
echo "<option value='" .$r['Name'] ."'>".$r['Name']. "</option>";
^ ^
And also use htmlspecialchars for those values with quotations so that they wont mess up the closing on the attributes:
$ArtistName = mysqli_real_escape_string($conn, $_POST['ArtistName']);
$ArtistName = htmlspecialchars($ArtistName, ENT_QUOTES);

dynamically populate mysql array into drop down menu

I have a database that I want to get data out onto a website. It contains states listed by name and id. Counties listed by id, namne , and state that contains thems ID and then clubs that exist , with a reference to the county id's that they exist in and columns for their actual data.
What I've got :
A drop down menu that populates itself with state id and name.
What I'd like to accomplish:
On selection of state , let's say ny , take it's id and use this in gathering another mysql array for the county drop down. I'd like it to dynamically occur on selection of state , maybe even giving a count of results next to the drop down.
$resstate = mysql_query("SELECT * FROM state ORDER by longstate;") or die("Note: " . mysql_error());
State:
<select name="State" size=1>
<?
while( $rs = mysql_fetch_array( $resstate ) ) {
echo "<option value=" .$rs['id'] . ">" . $rs['longstate'] . "</option>";
}
echo "</select>";
?>
I know I could use a JavaScript onChange="this.form.submit()" on the first drop down, but it's my understanding that I'd then be making a new page at that point and don't know if I could keep the functionality of the state drop down, say if you accidentally chose new Hampshire when you wanted New York.
here's an example of the current array filling the drop down :
http://snowmobileamerica.com/countytest.php
----EDIT---
Using Dagons Advice , I looked into Ajax.
I made a php file that's supposed to query the database based on a reference to getcounty.php?q=
The file is created as follows :
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
mysql_select_db("snowusa_clubs", $cn);
$sql="SELECT * FROM county WHERE state_id = '".$q."' ORDER by name";
$result = mysql_query($sql);
echo "<select name="County" size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value=" .$rc['id'] . ">" . $rc['name'] . "</option>";
}
echo "</select>";
mysql_close($cn);
?>
If i try to run it manually http://www.snowmobileamerica.com/getcounty.php?q=33 I get a 500 internal server error...
Any ideas where I went wrong?
try adding an id to the element, then make an ajax call to a handler with jquery:
$("#State").change(function() {
$.post("path/to/request handler/" , { "State" : $(this).val() },
function(data){
if (data == "OK"){
//add some elements here
} else {
//handle an error here
}
});
});
not able to comment yet.
but for the second question try:
<?php
$q=$_GET["q"];
$cn=mysql_connect("localhost","user","password") or die("Note: " . mysql_error());
echo "Conn ok<br>";
mysql_select_db("snowusa_clubs", $cn);
echo " Database opened<br>";
$sql="SELECT * FROM county WHERE state_id = '$q' ORDER by name";
$result = mysql_query($sql);
echo " Database queried <br>";
echo "<select name='County' size=1>";
while($rc = mysql_fetch_array($result))
{
echo "<option value='" .$rc['id'] . "'>" . $rc['name'] . "</option>";//added single quotes in the value
}
echo "</select> ";
mysql_close($cn);
?>

PHP Dropdown of all records from database + select current set record

I have a PHP dropdown of a list of groupnames (together with id, so it can be updated). In this FORM page you can change the groupname specified for an item by choosing possibilities from the dropdown coming out from the database. My code below works, but there must be a better way, because I get the first field as the currently set, and then all the possibilities, so I get this record twice.
Example:
- Keyboard (Currently set)
- Speakers (Possible to choose, straight from DBS)
- Midi Controllers (Possible to choose, straight from DBS)
- Keyboard (Possible to choose, straight from DBS)
- Drum set (Possible to choose, straight from DBS)
As you see I get the currently set record again.
My code:
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
There are 2 ways to achieve what you're looking for:
1) To show the selected item at the top of the dropdown
echo "<select name='itemgroupid'>";
// CHOOSE CURRENT SET RECORD AS SELECTED ITEM
echo "<option value='" . $itemgroupid . "'>";
$selected="
SELECT item.itemid, itemgroup.itemgroupname, itemgroup.itemgroupid
FROM item, itemgroup
WHERE item.itemid=$itemid";
$selectedresult=mysql_query($query) or die("query fout " . mysql_error() );
while($record=mysql_fetch_array($selectedresult) ) {
echo "" . $itemgroupname . "</option>";
}
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup WHERE item.itemid != $itemid";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
2) Show the selected item in it natural place
echo "<select name='itemgroupid'>";
// QUERY TO SHOW ALL POSSIBLE CHOOSABLE RECORDS FROM DATABASE
$itemgroupquery="SELECT itemgroupname,itemgroupid FROM itemgroup";
$itemgroupqueryresult = mysql_query ($itemgroupquery);
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option value=$nt[itemgroupid]";
if( $itemid == $nt['itemgroupid'] ) echo ' selected="selected"';
echo ">$nt[itemgroupname]</option>";
}
echo "</select>";
HTH
OK
In your code.
rather than output your selected value at the top, do it the proper way :)
Select your current item (make a note of the itemgroupid for example)
then in your output
while($nt=mysql_fetch_array($itemgroupqueryresult)){
echo "<option ";
if ($savedid==$nt[itemgroupid]) echo "selected ";
echo "$nt[itemgroupid]>$nt[itemgroupname]</option>";
}
echo "</select>";
This will produce with $savedid=1
<option value=0>group 0</option>
<option selected value=1>group 1</option>
<option value=2>group 2</option>
Add the default selected record to a empty array first like
toDisplay = array('selected_record');
Then, get the data from the database using your sql and append it to this array.
Later run a array_unique on it and finally using a loop create the html output string, in the same way you are doing it now.

Categories