function query(){
$leverancierVar = mysql_query("SELECT * FROM leverancier");
while($record = mysql_fetch_array($leverancierVar)){
echo '<option value="' . $record['leverancier'] .'">' . $record['leverancier'] . '</option>';
}
}
this is my code to store all data in database in function
<select id="leverancier" name="leverancier" style="width: 30%">
<?php query() ?>
</select>
this is the line of code i am using in the form to load data
[Database screenshot][1]
When I click the form dropdown button, there is no data displayed.
I am trying to solve the issue for a few hours, maybe someone with a clear look can see the mistake I made.
Edit:
I managed to get the data from the database, and displayed in a the dropdown, however the text is not displayed in the dropdown. You can however choose a value, and the correct value will be saved in the database. Here is a picture of the problem
And here's the code I used:
<?php
$mysqli = new mysqli("localhost", "root", "", "voorraad");
$result = $mysqli->query("SELECT leverancier from leverancier");
echo "<select id='leverancier' name='leverancier' style='width: 30%', color='black'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['leverancier'] ."'></option>";
}
echo "</select>";
?>
I imagine you're not connected to the database, probably worth looking over the connection page in the PHP manual
In the manual you will probably notice some warnings about the mysql_* extension. That is because it is deprecated and removed in version 7 and above. What does that mean for you? Essentially you shouldn't be using the mysql_* extension in your code.
You should instead use mysqli or PDO
If you were going to use PDO you would connect like so:
$dsn = 'mysql:dbname=<DATABASENAME>;host=<HOSTADDRESS>';
$user = ''; // Database User
$password = ''; // Database Password.
try {
$connection = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// Connection failed, you may want to do something here
}
And then do your query like so:
$statement = $connection->prepare('SELECT * FROM leverancier');
$statement->execute(); // Run the query.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo '<option value="' . $record['leverancier'] .'">' . $record['leverancier'] . '</option>';
}
Related
Basically, I'm trying to organize my code cleaner. I have a bunch of SQL queries which I am storing in a file called Queries.PHP. Example:
//Queries.php
//Connects to Database
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
function hi3() {
$query = "SELECT AVG(NULLIF(`~`, 0)) FROM `~` WHERE `~` BETWEEN '~' AND '~';";
$result = mysql_query($query) or die ( $result.mysql_error());
$row = mysql_fetch_array($result);
echo "~";
}
Then, on a separate page, I have code that is building HTML table headers and a separate function building the contents:
include Queries.php;
function BuildHTMLTableHeaders {
echo HTML table headers;
BuildHTMLTableBody();
echo </table>;
}
function BuildHTMLBody {
echo <tr>;
echo <td>;
hi3();
echo </td>;
echo </tr>;
...
}
Now, here's my problem: when I call hi3(), the rest of the table doesn't build. Why?
Your logic in BuildHTMLBody is flawed. You're only ever going to echo out 1 table row/cell because you're not looping through the results you get from your function.
function hi3() {
$query = "SELECT AVG(NULLIF(`~`, 0)) FROM `~` WHERE `~` BETWEEN '~' AND '~';";
$result = mysql_query($query) or die ( $result.mysql_error());
return $result;
}
function BuildHTMLBody {
$rows = hi3();
while($row = mysql_fetch_array($rows)) {
echo '<tr>';
echo '<td>' . $row['data'] . '</td>';
echo '</tr>';
}
}
Notice I return the results of hi3() and assign the results to a variable in BuildHTMLBody() and loop through them.
I haven't tested this, so I'm not sure if there are any syntax errors. Also, I would suggest using mysqli_. mysql_ is deprecated.
I have a table with 2 columns and i am looking to output only one of these columns into a drop down selector list with a button at the bottom. I am using PDO to connect to the database, This code is working but it is only giving me an array of all of the details of each row.
<?php
/* Execute a prepared statement by binding PHP variables */
$username = "mydb";
$password = "mydb";
$member = $_SESSION['SESS_MEMBER_ID'];
try {
$dbh = new PDO('mysql:host=;dbname=mydb', $username, $password);
$sth = $dbh->prepare('SELECT list_name FROM lists WHERE member_id = :member_id ');
$sth->execute(array('member_id' => $member));
$result = $sth->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
This is the working code so far, how to i change the output from an array to a selector drop down list with buttons? even a scrolling box list would do?
You are just trying to display a query result in a drop down box.
This is only html depending on some variables.
Instead of displaying results like this :
foreach($result as $row) {
print_r($row);
}
you should display an HTML tag with PHP like this :
print '<select id="your_list">';
foreach ($result as $row) {
print '<option value="'.$row['list_name'].'">'.$row['list_name'].'</option>';
}
print '</select>';
print '<input type="submit" value="Submit">';
If you want be able to submit this form and get the value, you have to surround it with a form tag with right options.
You access the element in the array by column name e.g. $row['list_name']
Something like:
<select name='x'>
<?php
foreach($result as $row) {
echo "<option value='".$row['list_name']."'>".$row['list_name']."</option>";
}
?>
</select>
i'm farly new to php and are trying to make a php script where it's suppose to connect to a mysql db and get the vaule id, then show as an option in a drop down menu.
This is the code I have so far (got help from a friend):
$username = "root";
$password = "";
$hostname = "localhost";
$database = "customers";
$id = "";
mysql_connect("$hostname", "$username", "$password") or die (mysql_error()) or die (mysql_error());
mysql_select_db("$database") or die (mysql_error());
$result = mysql_query("SELECT id FROM users WHERE id='$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$valuestring = $row['id'];
print_r($result);
echo "<option value='$valuestring'>". $valuestring ."</option>";
mysql_close();
}
print_r($id);
But when I use this code the option is returned empty :/
I have also tried to do print_r($result); and that give me Resource id #4, so I guess that works.
If anyone could help me solve this I would be one happy guy :D
the $id value in your code is empty, are you avare of that ?
and can you print the query before sending it to mysql ?
use :
"$query = "select id from table where id = '$id'";
mysql_query($query);
echo $query;
Perhaps if you showed us what output you did get it would help.
the option is returned empty
If the output includes HTML generated inside the loop then that means the query returned at least 1 row. But the only way that echo "<option value='$valuestring'>" would produce an empty string is if $valuestring was an empty string. It's populated from "SELECT id FROM users WHERE id='$id'" implying that you must have a row in your database where id is null or an empty string and $id in your php code is null/empty string - indeed that is the case ($id = "";).
NTW the mysql_close(); should be outside the loop.
Let's simplify this code:
<select name="user" id="user" width="200px" style="width: 200px">
<option value="">Select State</option>
<?php
$query_uf = "SELECT id FROM users WHERE id="'.$id.'";
$result = mysql_query($query_uf,$bd);
while ($users =mysql_fetch_assoc($result)) {
echo "<option value='".$uf['id']."'>".$uf['user']."</option>"; }
?>
</select>
Obs: It's better you use mysqli_query and connect. And, in your code it's missing the connection in mysql_query.
I've previously needed to retrieve a list of albums from a table using a similar method, maybe try this function. Create your form and call the function within the and tags leading this to work. This should list your id(s) where specified in the query.
functions.php (or wherever you'd like to put the function):
function stateList() {
$username = "username";
$password = "password";
$host = "localhost";
$dbname = "dbname";
$id = RETRIEVE VALUE HERE;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "
SELECT
id,
FROM users
WHERE
id = $id // YOU MAY WANT TO REMOVE WHERE - $ID AS STATED ABOVE, DOESN'T MAKE SENSE.
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$valuestring = $row['id'];
$rows = $stmt->fetchAll();
foreach($rows as $row):
print "<option value='" . $valuestring . "'>" . $valuestring . "</option>";
endforeach;
}
?>
Selection page:
<? include 'functions.php' ?> <!-- This will allow you to call the function. -->
<form action="example.php" method="post" enctype="multipart/form-data">
<select name="album">
<? stateList(); ?> <!-- Calls the function and retrieves all options -->
</select>
<input type="submit" name="submit" value="Submit">
</form>
I am trying to populate a drop-down list via PHP embedded in HTML.
Here is what I have so far:
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
#mysql_connect($host, $username, $password) or die("Unable to connect to database");
#mysql_select_db($database) or die("Unable to select database");
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysql_query($query);
while($row = mysql_fetch_array($ListOptions))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>"
}
?>
</select>
I know I am recieving the expected results because if I echo $row['ChapterName']; , the current values I have in the database are listed in the proper order, so why is it when I echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>" my list receives nothing at all?
You are missing a semi-colon at the end of your echo statement
while($row = mysql_fetch_array($ListOptions)) {
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
Note: Start using mysqli_() functions as mysql_() are no more maintained by PHP team..
try using this
<?php
$form='';
$link = odbc_connect ('databasename', 'username', 'password');
if (!$link)
{
die('Could not connect: ' . odbc_error());
}
echo 'Connected successfully .<br>';
//Query the database
$sql = "SELECT * FROM Chapters ORDER BY Id ";
$result = odbc_exec($link,$sql);
$selectbox='<select id=combox name=Chapters >';
while($bin =odbc_fetch_array($result))
{
$selectbox.= "<option value=\"$bin[Chapters]\">$bin[FChapters]</option>";
}
odbc_close($link);
$selectbox.='</select>';
echo "Select Name".$selectbox;
?>
this code is working perfectly for me
Ok... so I solved my own question in a way.
What I discovered was that my php was being commented out via <--! -->. I merely changed the file extension to .php as opposed to .html. The drop-down list worked immediately and was populated with the proper values.
But this raises another question... how can I get inline PHP to work? My site is hosted with MyDomain. Is there a setting I am missing somewhere?
try to use this
<select>
while($row = mysql_fetch_array($ListOptions))
{
$id=$row['Id'];
$cname=$row['ChapterName'];
echo "<option value='$id'>$cname</option>";
}
?></select>
I have correct them just look at once,
<?php
$username = "xxxxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxxxxxxx";
$host = "xxxxxxxx.mydomainwebhost.com";
$dbc=#mysqli_connect($host, $username, $password,$database) or die("Unable to connect to database");
?>
<select name="ChapterList" id="ChapterList" style="width:120px;">
<?php
$query = "SELECT * FROM Chapters ORDER BY Id";
$ListOptions = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($ListOptions,MYSQLI_ASSOC))
{
echo "<option value='".$row['Id']."'>".$row['ChapterName']."</option>";
}
?>
</select>
I want to fill a drop down with information I am getting from MySQL database.
I make a query and want to use the while loop to echo out the input field.
What I have right now:
I see a single option selection for the drop down with no data in it.
What I want:
Information in the option selection.
<dt><label for="image">Bild</label></dt>
<select id="image" name="ak_image" value="<?php echo $ak_image; ?>">
<?php
$result = mysql_query("SELECT bi_pfad, bi_name FROM tbl_bilder ");
$options = "";
while ($row = mysql_fetch_array($result)) {
$bi_name = $row["bi_name"];
$bi_pfad = $row["bi_pfad"];
$options .= "<option value=\"$bi_pfad\">".$bi_name."</option>\n";
}
echo $options;
echo "</select>\n";
?>
Since you've verified through phpmyadmin that there is data, that leads to a couple follow-up questions:
Are you successfully executing any other queries on this page? If not, then the most likely culprit is an unsuccessful connection to the db.
Are you running mysql_connect() before this snippet?
You may also want to refactor this a bit to make sure the query function knows of the appropriate connection and also introduce some error trapping.
<?
// Somewhere towards the beginning of this page/view.
$db_connection = mysql_connect( $host, $user, $password );
?>
<dt><label for="image">Bild</label></dt>
<select id="image" name="ak_image" value="<?php echo $ak_image; ?>">
<?php
// Affirmatively pass the connection to the query. Also, check for errors.
$result = mysql_query("SELECT bi_pfad, bi_name FROM tbl_bilder ", $db_connection);
if( $result )
{
$options = "";
while ($row = mysql_fetch_array($result)) {
$bi_name = $row["bi_name"];
$bi_pfad = $row["bi_pfad"];
$options .= "<option value=\"$bi_pfad\">".$bi_name."</option>\n";
}
echo $options;
}
else
{
// Perform error trapping here.
}
echo "</select>\n";
?>
Also, if your version of PHP is new enough to support them, it's probably a good idea for you to switch libraries. At the very minimum I would switch to mysqli or something that allows for parameterized query setups.