Issue with Populating dropdown from MySQL database - php

hi using following php code I am trying to populate a dropbox from mysql database:
enter code here
<?php
$mysqli = new mysqli('localhost', 'root', '', 'testdb');
if (mysqli_connect_errno())
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM language';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p> Select a language
<select id="selectLanguage">
<option value="">select</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value='<?php echo $row[0]; ?>'><?php echo $row[1]; ?></option>
<?php
}
?>
</select>
</p>
<p id="result"></p>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
I am not getting any error but the dropbox populated by this message instead of cell values stored in database:
(!) Notice : Undefined offset:0 in C:\wamp\test\index.ph on line 40 Call Stack#TimeMemoryFunctionLocation 10.0009684656{main}()...\index.php:0'>
can you please let me know why this is happening?

You problem is here:
<option value='<?php echo $row[0]; ?>'><?php echo $row[1]; ?></option>
you fetch the data using an associated array. not an index array.
while($row = $result->fetch_assoc())
You get that error message because index "1" does not exist.

Related

confused in echo mysql result inside echo

after sign in and redirect to next page, i check the user with $_SESSION.
Then if username valid, i want to show dropdown list which the list is get from database. I am confuse how to echo.
<?php
session_start(); //Start the session
if(!isset($_SESSION['pic']))
{
header('Location:index.php?p=signin');
}
else {
echo '<div class="form-group">
<label for="symcat" class="control-label">Symptom Category</label>
<select id="symcat" name="symcat" class="selectlist form-control">
<option value=""></option>
$sql='SELECT category FROM sym_category';
if ($sql) {
$res=mysqli_query($dbc,$sql) or die(_ERROR26.': '.mysqli_connect_error());
}
while ($dat = mysqli_fetch_array($res, MYSQLI_NUM)) {
echo '\t<option value="'.$dat[0].'">'.$dat[0].'</option>\n';
}
mysqli_free_result($res);
</select>
</div> <!-- /form-group -->';
}
?>
This would probably be better:
<?php
session_start(); //Start the session
if(!isset($_SESSION['pic']))
{
header('Location:index.php?p=signin');
}
else {
$sql = 'SELECT category FROM sym_category';
if ($sql) {
$res = mysqli_query($dbc,$sql) or die(_ERROR26.': '.mysqli_connect_error());
}
?>
<div class="form-group">
<label for="symcat" class="control-label">Symptom Category</label>
<select id="symcat" name="symcat" class="selectlist form-control">
<option value=""></option>
<?php if (isset($res)): ?>
<?php while ($dat = mysqli_fetch_array($res, MYSQLI_NUM)): ?>
<option value="<?php echo $dat[0] ?>"><?php echo $dat[0] ?></option>
<?php endwhile ?>
<?php mysqli_free_result($res); ?>
<?php endif ?>
</select>
</div> <!-- /form-group -->
<?php } ?>
Honestly I still don't think this is a very nice way. If possible, please use view files.
I think it's reasonable to say that you shouldn't use an echo within another echo. Echo is used to print something to your screen, so it shouldn't be necessary to use an echo within that same echo.
Check out this sample code. Maybe it'll help you.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch the option list details from DB
$optionList = array();
$sql = "SELECT category FROM sym_category";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$optionList[] = $row['category']
}
} else {
echo "0 results";
}
// Create the dropdown list
echo "<div class='form-group'>";
echo '<label for="symcat" class="control-label">Symptom Category</label>';
echo '<select id="symcat" name="symcat" class="selectlist form-control">';
echo '<option value=""></option>';
foreach ($optionList as $key => $value)
{
echo "<option value='$value'>$value</option>";
}
echo '</select>';
echo '</label>';
echo "</div>"
As Akintunde & SheperOfFire said the nice and tidy way is like :
<?php
session_start(); //Start the session
if(!isset($_SESSION['pic']))
{
header('Location:index.php?p=signin');
}
else {
header('Location:index.php?p=forminputcar');
}
?>
Because, inside of forminputcar has php tag and echo also. Or you can also put above script at the top of forminputcar page. So, if session match we stay on current page.
<?php
session_start();
if(isset($_SESSION['pic']))
{
header('charset=UTF-8');
}
else {
header('Location:index.php?p=signin');
}
?>

Output data from database with PHP into dropdown box

I have a form designed with bootstrap style and I want to retrieve data from a database into a drop-down list. I tried this code, but I get a list with no text.
<div class="form-group"><label class="col-sm-2 control-label">Location</label>
<div class="col-sm-8"><select class="form-control m-b" name=Location>
<?php
$mysqli = new mysqli( 'localhost', 'cshrnaf_user2', '=cXlIBsdMkdr', 'cshrnaf_mis_db' );
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM adhoc";
$result = mysqli_query($mysqli,$query);
while($rows = mysqli_fetch_assoc($result))
{
echo "<option value=" . $rows['Aim'] . "></option>";
echo "<option value='{".$d['Aim']."}'>".$d['Aim']."</option>";
}
?>
$d is never mentioned before you try to echo it, so what is it's content?
echo "<option value=" . $rows['Aim'] . "></option>"; has two issues: firstly, the value is not encased in quotes, and secondly, there is no content in the tag, so no text will output.
Try changing your while to:
while($rows = mysqli_fetch_assoc($result)){
echo "<option value='{$rows['Aim']}'>{$rows['Aim']}</option>";
}
As long as $rows['Aim'] contains the content you wish to output, this should work.
// cat is array fetch from database
<select name="cat" id="cat_id" style="width:170px" value="<?php echo $_POST['cat']; ?>">
<option value="0"></option>
<?php
foreach ($cat as $row) {
?>
<option value="<?php echo $row->tag_cat_id ?>" ><?php echo $row->tag_cat_name ?></option>
<?php }
?>
</select>
</select>
You should select database in your file.Above you only connect to your localhost.And you should use variable name $rows for all fetch values
if (!mysqli_select_db("mydbname")) {
echo "Unable to select database: " . mysqli_error();
exit;
}

PHP option value based on database table

My problem now:
once I echo the value from the database its woking good. but when I submit the form I got an empty value of the selected option.
Can any one help. I tried to used {} in he value code but it did not work.
What I want :
Set the the value of the selected option as it is on the database to insert it into another table.
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="" selected>--select-- </option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['centerName'].'">'.$row['centerName'].'</option>';
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
Try this
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="0" selected>--select--</option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$name = $row['centerName'];
echo "<option value='$name'> $name </option>";
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
</select>
You will have to "expand" your select query to include the ID of the row, and then instead of $row['centerName'] use $row['id'] (or what your ID column is named) in the value argument of the option element, and not the 'centerName'. If I understood correctly what you want, this should be it.
Edit: And do switch to mysqli_, mysql_ has been deprecated.
try to write like this:
echo '<option value="',$row["centerName"],'">',$row["centerName"],'</option>';
Warning:
Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead.
Solution
I recreated your issue and enhanced your code using mysqli extensions, and it's working fine. Take a look at the following code,
<?php
if(isset($_POST['submit'])){
// display submitted option
echo $_POST['CenterTO'];
}
?>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbName = "stackoverflow";
// Open a new connection to the MySQL server
$connection = new mysqli($host, $username, $password, $dbName);
// Check connection
if($connection->connect_errno){
// error
die('Connect Error: ' . $connection->connect_error);
}
// Execute query
$result_set = $connection->query("SELECT centerName FROM jeCenter");
?>
<form action="form_page.php" method="POST">
<select name="CenterTO">
<option value="" selected>--select-- </option>
<?php
// Check if number of rows is greater than zero or not
if($result_set->num_rows > 0){
// Loop through each record
while($row = $result_set->fetch_assoc()){
?>
<option value="<?php echo $row['centerName']; ?>"><?php echo $row['centerName']; ?></option>
<?php
}
}else{
?>
<option value="none">No data</option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
// Close connection
$connection->close();
?>

How to insert data in a dropdown list

We managed to get the drop down list menu however, we are having difficulties getting the data from sql. So far, this is what we got.
<select>
<option id="">--Select jobscope--</option>
<?php
$con=mysqli_connect("host","user","password","database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$getIT = mysqli_query("SELECT job_title FROM `job_details`");
while($viewIT = mysqli_fetch_array($getIT)) {
}
?>
<option id="<?php echo $viewIT['job_title']?>"<?php echo $viewIT['job_title']?></option>
</select>
Shouldn't be like this ? with tag inside WHILE LOOP
while($viewIT = mysql_fetch_array($getIT)) {
<option id="<?php echo $viewIT['job_title']?>"<?php echo $viewIT['job_title']?></option>
}
$query = "SELECT * FROM test_groups_tb WHERE user_id='$userid'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
$dd .= "<option value='{$row['group_id']}'>{$row['group_name']}</option>";
}
Try this,
<option value="">--select--</option>
<?php
while($rec = mysql_fetch_assoc($result)) {
?>
<option value="<?=$rec['job_title']?>"><?=$rec['job_title']?></option>
<?php }
}?>
</select>
I am not from php background. Try this.
<?php
$query = "SELECT job_title FROM job_details";
$result = $mysqli->query( $query );
echo '<select id="domain_account" name="domain_account" class="txtBox">';
echo '<option value="">-select-</option>';
while ($row = $result->fetch_assoc()){
?>
<option value="<?php echo $row['job_title']; ?>"><?php echo $row['job_title']; ?></option>
<?php
}
echo "</select>";
?>
Better use PDO or MYSQLi . MYSQL* is depriciated
U need to use that <option id="<?php echo $viewIT['job_title']?>"<?php echo $viewIT['job_title']?></option> line b/w while loop
$getIT = mysql_query("SELECT job_title FROM `job_details`");
while($viewIT = mysql_fetch_array($getIT)) {?>
<option id="<?php echo $viewIT['job_title']?>"<?php echo $viewIT['job_title']?></option>
<?hp }?>

PHP: Dropdown options from database

I am a newbie in php. I am trying to write code for displaying dropdown select from database(my_db).
I've attached the code here:
<?php
// Create connection
$con=mysqli_connect("localhost",$dbuname,$dbpwd,"my_db") or die("Couldn't connect!!!". mysqli_error());
mysqli_select_db($con,"my_db");
$result = mysqli_query($con,"Select country from Country");
$rowcount = mysqli_num_rows($result);
//echo $rowcount;
if($rowcount) {
$select = '<select name="select">';
//echo $select;
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
//printf ("%s \n",$row["country"]);
//echo "<br>";
$select.='<option value="'.$row['country'].'">'.$rs['country'].'</option>';
//echo $select;
}
$select .= "</select>";
echo $select;
}
?>
I refer this link for writing this code.
But, I didn't get the output. The dropdown box would be blank.
What did I make as wrong?
Please give more idea to improve my code.
Thank you in Advance!!!
put php code inside html tag.
<select id="selectbox" name="selectbox">
<?php
//here your query
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {?>
<option value="<?php echo $row['country'];?>"><?php echo $rs['country'];?></option>
<?php }?>
</select>
echo '<select name="select">';
while($row=mysqli_fetch_array($result)) {
echo '<option value="'.$row['country'].'">'.$row['country'].'</option>';
}
echo '</select>';
it worked for me.
//db connection
mysql_connect("localhost","user","password");
mysql_select_db("database");
//query
$sql=mysql_query("SELECT id,name FROM table");
if(mysql_num_rows($sql)){
$select= '<select name="select">';
while($rs=mysql_fetch_array($sql)){
$select.='<option value="'.$rs['id'].'">'.$rs['name'].'</option>';
}
}
$select.='</select>';
echo $select;

Categories