Select input filled with SQL from database - php

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.

Related

Want to fetch data from database based on dropdown list selection using php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}

Data dropdown not loaded with mysql

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>';
}

My PHP Search Function isn't Outputting Data

So I am trying to create a way of searching my website. I've created a search bar on my index page. You can find this page here: http://seersvillage.com/v1.2/
My search form looks like this:
<form method="post" action="search.php">
<input type="text" name="search" class="search" value="Skeleton" onFocus="this.value=''">
</form>
and I have a functions.php file attatched and this page is also connected to my mysql database. I have content available to be read / searched for all ready.
Here is my search function on functions.php:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
}
}
And the only thing on my search.php (excluding your usual html layout) is as follows:
<?php
include('includes/functions.php');
if(!isset($_POST['search'])) {
header("Location:index.php");
}
?>
and further down in the tags.
<?php print("$output");?>
Now I am pretty new to PHP and MySQL. However I am getting no error on my error.log file, making troubleshooting a little hard for a first timer. Any suggestions? I'm sure it's a very simple mistake, probably just misspelt something, but I just can't see it.
it seems that your php.ini file is set to not display errors. Add these lines of code at the beginning of your code and retry:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Your doSearch function does not return anything.
return $output;
But $output is only declared within the function. So you'll need to use
print(doSearch());
Either that or declare $output as a global variable, but we don't want to do that :)
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
//make sure your function returns $output
return $output;
}
Make sure your function returns the output and then echo out the function:
<?php echo doSearch(); ?>
This is because of how PHP variables are scoped.
...then of course we need to add in all the standard provisos ... don't use the mysql_ library it's almost as dead as a Norwegian Blue. If you use mysqli or PDO you can bind the parameters/values to a prepared statement and not only will that improve efficiency but it'll ensure your input is properly sanitised (far better than that odd ad-hoc preg_replace you're using).
You don't want to kill your script (die) when the query fails - that's just a bit weird, handle the error properly.
There are far better ways to do searches in SQL such as FULLTEXT searches.. or if you can, perhaps implement Apache Solr rather than trying to roll your own.

PDO issue with displaying appropriate data

To begin with, I'm having this small PDO snippet of code which gets me all available databases on the server and another function for the tables:
I need whenever I select and submit an option from the db list to display its corresponding tables in the select menu below. I managed to display the databases with a foreach but I kinda miss the point why this doesn't work.
Thanks in advance for any answers/solutions :)
see below for a revision to your code in order to achieve what you're looking for.
<form method='post' action="<?php $_SERVER['PHP_SELF']; ?>">
<?php
define('PDO_USER', 'root');
define('PDO_PASS', '');
function getDatabases(PDO $pdo) {
$stmt = $pdo->query('SHOW DATABASES');
$result = $stmt->fetchAll();
$dbs = array();
foreach($result as $row) {
$dbs[] = $row['Database'];
}
return $dbs;
}
$pdo = new PDO('mysql:host=localhost', PDO_USER, PDO_PASS);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$databases = getDatabases($pdo);
// Table code
$selectedDB = (!empty($_POST['database'])) ? $_POST['database'] : null;
function getTables(PDO $pdo, $databaseName) {
if(!in_array($databaseName, getDatabases($pdo))) {
return array();
}
$stmt = $pdo->query('SHOW TABLES FROM '.$databaseName);
$result = $stmt->fetchAll();
$tables = array();
foreach($result as $row) {
$tables[] = $row['Tables_in_'.$databaseName];
}
return $tables;
}
$tables = array();
if(!empty($selectedDB)) {
$tables = getTables($pdo, $selectedDB);
}
?>
Database:
<select name='database'>
<?php foreach($databases as $row): ?>
<option value="<?php echo $row; ?>"><?php echo $row; ?></option>
<?php endforeach; ?>
</select> 
<input type='submit' name='formSubmit' value='Submit'></form>
UPDATE
<select name='formTable1'>
<?php foreach($tables as $tbName): ?>
<option value='<?php echo $tbName; ?>'><?php echo $tbName; ?></option>
<?php endforeach; ?>
</select>
A couple of notes:
You need to include the "action" attribute in the form tag in order to give the form a target URL for submission.
In your original select you had 2 name attributes
(name='formDatabases[]' name='database'). You should only have one
name per form element, which is what is determined to be used as the
key in the $_POST array for that particular field.
You should only use "name='var[]'" format in the HTML, if you expect
that particular POST item to be an array in PHP. Otherwise you can
just use "name='var'"
This may be out of the scope of your original question, but you may
want to consider separating your database business logic into a separate
class, to keep your HTML clean. For now at least, I updated the code to have
the logic at the top of the file so that in can be extracted into a
class more easily in the future. This avoids the perilous path into PHP Spaghetti string code!

Reading mysql with php and displaying result in dropdown menu

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>

Categories