I need help regarding my PHP drop down list. I've created a Database call state. I'm trying to populate a state drop down on an html page using php connecting to mysql. Here is my code for the html page:
<form action="CreateUser.php" method="POST">
<label type='text'>State:</label>
<select name='state'>
<option value='0'>--Choose a State--</option>
<?php
$dbTable='states'
$QueryResult=msql_query('Select * from "$dbTable"');
while($Row = mysql_fetch_assoc($QueryResult))
{
?>
<option value="<?php echo $Row['StateID']; ?>">
<?php echo {$Row['StateName']}; ?>
</option>
<?php } ?>
</select>
<input id='movebutton' type = "Submit" name="submit" value="submit"/>
</form>
And here is my PHP code for the dbconnection:
$DBName = "business";
$DBConnect = #mysql_connect("localhost", "root", "");
if($DBConnect === FALSE)
{
echo "<p>Unable to connect to the database server.</p>" . "<p>Error code " . mysql_errno() . ": " . mysql_error() . "</p>";
}
else
{
$DB = mysql_select_db($DBName, $DBConnect);
if(!$DB)
{
echo "<p>Unable to connect to the database server.</p>" . "<p>Error code " . mysql_errno() . ": " . mysql_error() . "</p>";
mysql_close($DBConnect);
$DBConnect = FALSE;
}
}
Can someone tell me what I'm doing wrong? I've checked on this forum and also on YouTube regarding PHP dropdown. I'm new to php and still learning.
The query is invalid. It should be as follows:
$QueryResult=msql_query("Select * from `$dbTable`");
Update your query like $QueryResult=msql_query("Select * from '$dbTable'"); and also
Remove Curly braces inside option, or replace this code
<option value="<?php echo $Row['StateID']; ?>">
<?php echo $Row['StateName']; ?>
</option>
Related
I have populated dropdown list from the sql result in php and now i am trying to get the selected value to a php variable in the same page , but it is not working. Can you help. Below is the code.
<?php
$mid="mario";
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
echo "<select name='list'>";
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<option value='" . $row['col_of_fac'] . "'>" . $row['col_of_fac'] . "
</option>";
}
echo "</select>";
$varsel = $_POST['list'];
echo "hai";
echo $varsel;
?>
$varsel = $_POST['list']; is not working.
you should
1- use a form
2- send the variables with method "POST" to the same file php
<?php
// display the errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
<?php
// when the form submitted
if(!empty($_POST['list'])){
echo $_POST['list'];
}
?>
<?php
// connection test
$conn=mysqli_connect("localhost","user","pass","db"); //replace the (user, pass, db) with your parameters
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//if your connection succeded
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<select name="list">
<?php while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)): ?>
<option value="<?= $row['col_of_fac']; ?>"><?= $row['col_of_fac']; ?></option>
<?php endwhile; ?>
</select>
<input type="submit" value="valider">
</form>
if you want to print the value selected and not without form
then you have to use jquery
<?php
// display the errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
<?php
// when the form submitted
if(!empty($_POST['list'])){
echo $_POST['list'];
}
?>
<?php
// connection test
$conn=mysqli_connect("localhost","user","pass","db"); //replace the (user, pass, db) with your parameters
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//if your connection succeded
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
?>
<select name="list">
<?php while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)): ?>
<option value="<?= $row['col_of_fac']; ?>"><?= $row['col_of_fac']; ?></option>
<?php endwhile; ?>
</select>
<p id="value-selected"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
$("select[name=list]").on("change", function () {
var valueSelected = $(this).val();
$("#value-selected").html(valueSelected);
});
});
</script>
$varsel = $_POST['list']; is not working. : it will work only when the form is submitted by the post method ,
(with current code select box is printed and you are fetching post without submitting the form)
The logic should be like
In Form Select box is made using your below code and user select and click on submit:
<?php
$mid="mario";
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
echo "<select name='list'>";
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<option value='" . $row['col_of_fac'] . "'>" . $row['col_of_fac'] . "
</option>";
}
echo "</select>";
?>
After form submitted below code should execute and in Network console , in page headers you can see if the required data is transferred to the requested page
I'm using a form to input new projects into my database. One of the fields is Lead Writer. I want to add a drop down menu to that field that will display the names of the lead writers from my database that the user can then select to populate that field. I've managed to get the drop down to appear in the field, but my code isn't generating any names. I tried setting up a function that would call those results, but it's obviously not working. The form worked well prior to my changes, so it's not an issue connecting to the database. Any help would be greatly appreciated.
function query(){
$myNames = "SElECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($result = mysqli_fetch_array($myNames)){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
Lead Writer: <select name="dropdown">
<?php query() ?>
</select>
<br><br>
Date Received: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
Edited Code:
<html>
<head>
</head>
<body>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
</form>
<?php
$connection->close();
?>
</body>
</html>
2nd Edit:
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($connection){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $connection->query($myNames)) {die($mysqliconnection->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}?>
<?php
$connection->close();
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
</form>
</body>
</html>
You have a variable scope issue - http://php.net/manual/en/language.variables.scope.php. $mysqli is undefined in your function query(). You need to pass it as a param. Also, you were trying to do mysqli_fetch_array() on the query string, instead of the mysqli result. I have updated it to the OO ->fetch_array().
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($record = $result->fetch_array()){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
You will also need to pass it in your call
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
You can add some debugging to find out why it is not printing
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
per your edit - https://stackoverflow.com/posts/34257335/revisions
Your mysqli connection is $connection
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
so not sure why you are trying to use $mysqli
$mysqli->query($myNames)
as $connection != $mysqli.
As you are doing the query in a function, you don't need to rename all instances of $mysqli to $connection, as you can just change to
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
Why this code is not update information?
HTML Form:
<form>
<lable> ID# :</lable>
<input id= "ID" name= "ID" type= "text">
<p>
<label>Select field to Edit</label>
<select name="change">
<option value=""></option>
<option value="fname">First Name</option>
<option value="lname">Last Name</option>
<option value="email">Email</option>
<option value="city">City</option>
<option value="zip">Zip</option>
</select>
<lable> Enter the value to be replaced </label>
<input id = "replace" name = "replace" type = "text">
</p>
<input name="submit" type="submit" value="Submit">
PHP Code for updating information from database:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$conn = mysql_connect($servername,$username,$password);
if(!$conn)
{
die('Error!' . mysqli_error());
}
$sql = 'SELECT * FROM users';
mysql_select_db('mitsdatabase');
$retval = mysql_query($sql, $conn);
if(! $retval)
{
die('Could not get data:' . mysql_error());
}
echo "<table width='300' cellpadding='5' border='1'>";
echo "<tr> <td>ID#</td> <td>FirstName</td> <td>LastName</td> <td> Email </td> <td> City </td> <td> State </td> <td> Zip </td> </tr>";
while($row = mysql_fetch_array($retval,MYSQL_ASSOC))
{
echo "<tr> <td>{$row['ID']}</td> . <td>{$row['fname']}</td> . <td>{$row['lname']}</td> . <td>{$row['email']}</td> . <td>{$row['city']}</td> . <td>{$row['state']} </td>. <td>{$row['zip']}</td>";
}
echo "</table>";
$db_id = $_POST['ID'];
$db_select = $_POST['change'];
$db_replace= $_POST['replace'];
echo " Do you want to edit any entry?";
if(!_POST['submit'])
{
echo " ";
}
else{
mysqli_query("UPDATE users SET db_select='$db_replace' WHERE ID = $db_id ");
}
mysql_close($conn);
?>
I want to update informate selected from select field but somehow it is not doing any thing. Can someone help me what is wrong with this code.
Is your PHP on the same page as your HTML? If not, you are not directing to your php code within the <form> element in your HTML.
For example, if your PHP file was called 'myphpcode.php' (and in the same folder as your HTML code) then you could direct to it using the following:
<form method="post" action="myphpcode.php">
If you want to post to the same page just change <form> to <form method="post" action="#"> and get variables in php like this $nameofvar = $_POST['nameofinputfield'] . Each input field should have the name tag.
Also try to change your mysql connect to this :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
and after you finished the query
$conn->close();
and the query to insert
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and you can modify this $sql string to update or delete
I have drop downs built by a PHP function pulling from MySQL tables. The drop downs work fine but the selected option isn't POSTing. I suspect the problem is with how the HTML select tag is created in PHP but I can't seem to find a way to correct it. I've searched around but nothing seems to work.
Here is the PHP function to build the drop down:
function contact_list(){
//Connection info
$dbhost = 'localhost';
$db = 'database';
$dbuser = 'user';
$dbpass = 'password';
//Define connection
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $db);
//Check connection
if (mysqli_connect_errno()) {
echo " ERROR " . mysqli_connect_error() . " ERROR ";
}
//Define search strings for drop down
$contact_list = "SELECT * FROM CONTACT_LIST";
//Execute search of primary_contact table
if (!mysqli_query($con,$contact_list)) {
die('' . mysqli_error($con));
}
//Return primary_contact results as string
$contact_result = $con->query($contact_list);
//Build drop down
echo "<select name='Primary_Contact'>";
//Loop through results
foreach ($contact_result as $row)
{
echo "<option value='' >" .htmlspecialchars($row['Primary_Contact']). "</option>";
}
echo "</select><p></p>";
}
Here is a sample of the HTML. The Description text box is fine so I don't think the problem is with the form tags.
<form action="mod_output_test.php" method="POST">
<u>Description</u>: <p></p>
<input type="text" name="Description" size="48" value="<?=$Description;?>"> <p></p>
<!-- Primary Contact -->
<?php echo "<u>Primary Contact</u>:<p></p>Current value: <b> " . $Primary_Contact . "</b>  New value: ";?>
<?php contact_list() ?>
<p></p>
<input type="submit">
</form>
Change
echo "<option value='' >" .htmlspecialchars($row['Primary_Contact']). "</option>";
to
echo "<option value='".$row['Id']."'>" .htmlspecialchars($row['Primary_Contact']). "</option>";
And I am guessing your dropdows is between a form tag.
in the top of the action file type this and tell us what you get
<?php
print_r($_REQUEST);
exit;
?>
echo "<option value='' >" .htmlspecialchars($row['Primary_Contact']). "</option>";
When you post like that, option value is empty. Add the id of the contact.
As they said, we see no <form> tag, we "assume" you add it before that piece. But the answer to "is not posting" is because value from <option> is empty.
Long time listener, first time caller. I'm having trouble with pulling a column called "Rep_IP" from a mysql table called "roster", turning it into an array, and then using that array to populate a dropdown in html. I've tried several suggestions listed here as well as other places and I'm not having any luck. The page shows up just fine but the dropdown has no options to select. I figured I would see if one of you could tell me what I am doing wrong here.
<html>
<body>
<form action="insert.php" method="post">
<p>Rep ID:</p>
<?php
$con = mysql_connect("localhost", "root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("rep_stats", $con);
$query = "SELECT Rep_ID FROM roster";
$result = mysql_query($query) or die ("no query");
$result_array = array();
echo "$query"
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
?>
<select name="Rep_ID">
<?php
foreach($result_array as $rep)
{
echo "<option value=" . $rep['Rep_ID'] . ">" . $rep['Rep_ID'] . "</option>";
}
?>
</select>
Issues Handled: <input type="number" name="IssuesHandled">
Hours Worked: <input type="number" step="any" name="HoursWorked">
<input type="submit">
</form>
</body>
</html>
As you can see, the drop down is part of a form that is used to create an entry in a new table as well. I don't know if that makes a difference but I figured I would point it out.
Try this.
<select name="Rep_ID">
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
?>
</select>
Try this:
<?php
function select_list(){
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link)
{
echo ('Could not connect');
}
ELSE {
$query = "SELECT Rep_ID FROM roster";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
}
mysqli_close($link);
}
$begin_form =
<<< EODBEGINFORM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Insert data </title></head>
<body>
<form action="insert.php" method="post" name="form1">
<p>Rep ID:</p>
<select name="reps" form="form1">
EODBEGINFORM;
$end_form =
<<< EODENDFORM
</select><br>
Issues Handled: <input type="text" size="12" name="IssuesHandled"><br>
Hours Worked: <input type="text" size="12" name="HoursWorked"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
EODENDFORM;
echo $begin_form;
echo select_list();
echo $end_form;
?>
You will notice that I have used MYSQLI_ istead of MYSQL_ the reason is that this better for new code, see the comments above.
I debugged your code and ran I to a lot of problems.:-( The main problem was:
echo "$query" Your forgot the semicolon at the end of the line.
Good luck with you project.