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!
Related
I've been using mysql and it did what I want, but as my project is getting larger, I decided to opt for mysqli.
I looked at the tutorial at enter link description here which was really straight forward up until the point where I want to display some data
stored procedure (connect.php)
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $con;
// Try and connect to the database, if a connection has not been established yet
if(!isset($con)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('config.ini');
$con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if( $con === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $con;
}
function db_query($query) {
// Connect to the database
$con = db_connect();
// Query the database
$result = mysqli_query( $con,$query);
return $result;
}
function db_error() {
$con = db_connect();
return mysqli_error($con);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_quote($value) {
$con = db_connect();
return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>
php/html
<div class="grid_4">
<div class="left-1">
<h2 class="top-1 p3">Find a property</h2>
<form id="form-1" method="post" class="form-1 bot-1" action="prop_result.php">
<div class="select-1">
<label>Select Area</label>
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}else
{
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}}
?>
</select>
</div>
What I don't understand is how to use the stored procedure in a while loop so it will output the data in the fields ID and Area so my select box and any other input can be properly populated based on the query
current
I've tried different ways :
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
<?php
$rows = db_select("SELECT area_id from property");
if($rows === false) {
$error = db_error();
}
{
echo "<option value='".$rows['id']."'>".$rows[$col4]."</option>";
}
?>
None of these output any data. Echoing $rows gives no data. I don't know what the logic is for using the stored procedure to display the output.
Any help would be appreciated, if any other information is required to assist in resolving this issue, please let me know.
Awesome to hear that the data is returning. Try this out for size...
foreach($rows as $key => $value){
foreach($value as $k => $v){
if($k == 'id'){
$newID = $v;
}
if($k == 'type'){
$newType = $v
}
}
echo "<option value='".$newID."'>".$newType."</option>";
}
with this you should be able to make it work for you liking.
Edit: Didnt see the additional arrays until later...the nested loop should suite you better.
Siniseus way works but its too much code for a simple task. I did work with it to finally come to this
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id, city_id,area FROM area");
foreach($rows as $row){
echo "<option value='".$row['id']."'>".$row['area']."</option>";
}
?>
</select>
Simple, clean and really straight forward without too many variables.
$rows = db_select ("Select Query")foreach($rows as $row){
do this
}
Im trying to load data from the database dynamically. Like when user click on select button in a form, the data will be loaded dynamically from the database. But the problem is I have to use PDO. Im not getting the output, don't know what's wrong. Here is my code-
<tr><td><font size="+1">Region :</font></td>
<td><Select name="region" class="regionfields" id="wineRegion">
<option id="0">-- Select Region --</option>
<?php
$hostname = 'localhost';
$username = 'ovic';
$password = 'root';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=winestore", $username, $password);
echo 'Connected to database<br />';
$sql = "SELECT region_name FROM region";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
foreach($obj->region_name AS $W)
{?>
<option id="<?php echo $W; ?>"><?php echo $W; ?></option>
<?php
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</Select></td></tr>
You may need to use $stmt->fetchAll() which returns an array of objects. The fetch() method returns only a single object.
$regions = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($regions as $region) {
?>
<option id="<?php echo $region->region_name; ?>">
<?php echo $region->region_name; ?></option>
<?php
}
If that fails, trying doing a print_r on the result of fetchAll() to see if you are getting anything back.
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 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.