How to get results from php to html <select> option? - php

i have a select option in index.html , i want to get result from mySQL via php,
but how to get the result from php ,and add results to html automatically
index.html:
<form action="get.php" method="post" >
<select>
<option class="rm" value="trap"><get results from php></option>
.............
</select>
</form>
If you could show me a working example which does that, or may be any similar idea, it would be good.

I don't really understand what you mean. But did you mean something like this:
<html>
<body>
<select>
<?php
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/config.php";
$something1 = "something1";
$something2 = "something2";
$stmt = $pdo->prepare('SELECT DISTINCT from_mysql FROM customers WHERE something1 = :something1 AND from_mysql != :something2 ORDER BY from_mysql');
$stmt->execute(array(':something1' => $something1, ':something2' => $something2));
$results = $stmt->fetchAll();
if (empty($results)) {
echo 'Error: Please contact technical support!';
} else {
foreach( $results as $row ) {
echo "<option>".$row['from_mysql']."</option>";
}
}
?>
</select>
</body>
</html>
P.S. You'll have to use index.php

Related

Creating a line graph taking data from database

I tried to create a simple bar chart in D3 taking data from database. The idea is to fetch year and value from the database using the selection buttons of parameters and country and display it in the form of simple bar chart. I have two selection buttons and a submit button. The code for that is like this :
<form action ="data.php" method ="post">
<tr>
<th valign="bottom">Select country:</th>
<td >
<select name="country" class="">
<option value= "NPL">Nepal</option>
<option value= "IND">India</option>
</select>
</td>
<th valign="bottom">Select parameters:</th>
<td >
<select name="indices" class="">
<option value= "foodfinal">Vulnerability on food</option>
<option value= "waterfinal">Vulnerability water </option>
</select>
</td>
<td valign="top">
<input type="submit" class="action" />
</td>
</tr>
</form>
Foodfinal and waterfinal are the names of tables in the database called 'Climate'. NPL and IND are the countrycodes. My PHP code ( data.php ) is like this :
<?php
$username = "root";
$password = "";
$host = "localhost";
$database="climate";
$country="AFG";
$country=$_POST["country"];
$indices=$_POST["indices"];
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `year`, `values` FROM `$indices` WHERE `countrycode`= '$country'";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
include("linegraph.html");
mysql_close($server);
?>
My problem is that linegraph.html had been working well before the use of the selection forms but this time, it only displays the output of data.php which looks like this.
{"year":"1995","values":"0.525999"},{"year":"1996","values":"0.570037"},{"year":"1997","values":"0.563966"},{"year":"1998","values":"0.513896"},{"year":"1999","values":"0.5346"},{"year":"2000","values":"0.552691"},{"year":"2001","values":"0.545319"},{"year":"2004","values":"0.543972"},{"year":"2005","values":"0.543299"},{"year":"2006","values":"0.546682"},{"year":"2007","values":"0.550066"},{"year":"2008","values":"0.549449"},{"year":"2009","values":"0.548832"},{"year":"2010","values":"0.548215"},{"year":"2011","values":"0.547536"},{"year":"2012","values":"0.547536"}]
Would you please help me.
change this
include("linegraph.html");
To ( as a best practice thing if the "include" is required to display the page just use require )
require("linegraph.html");
And add at the top of the php
ini_set('display_errors', 1);
You will probably find your page missing ( at the very least your life will be easier with error reporting turned on )
oh and change this part too,
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
To this
$data = array();
while ( false !== ( $row = mysql_fetch_assoc($query))){
$data[] = $row;
}
It probably won't fix your problem ( hard to do without the other html page ) but its the preferred way to do this type of loop.
Update: Here you can't pass both html and json the way you are ( just dawned on me ) you have to pick one. Your problem is a structural one, as you cant do both things at the same time, where does the json data go, it just floats on top of the html? Sorry but it wont work like that, either you already have the html and fill it in with the returned json data, or you build the html with the data already in it and send it back.
change this
echo json_encode($data);
include("linegraph.html");
to ( now you are sending valid json / with the html but you'll have to assemble it client side )
ob_start();
include("linegraph.html");
$html = ob_get_clean();
$responce = array( 'data'=>$data, 'html'=>$html );
echo json_encode($responce);
At the very least your output will change. Hard to say how to do it ( again ) without the other page.
Ok,,,, when I asked to echo something at the bottom did you do this?
echo json_encode($data);
include("linegraph.html");
mysql_close($server);
echo "works";
?> //id remove this end tag it's not needed and can cause problems if there is space ( line returns ) after it. Because it will make you json which you may or may not need invalid.
Oyyy. this is .. uhh
if ( ! $query ) {
echo mysql_error();
die;
}
you can just do like this.
if ( ! $query ) {
die ('Query error' . mysql_error());
}

white spaces in $_POST

I have a HTML dropdown list populated by PHP as following:
<form name="selectOccupation" method="post" action="specific_occupation.php">
<div align="centre">
<select name="occupation_dropdown" id="occupation_dropdown">
<?php
include "connection.php";
$sql = mysql_query("SELECT DISTINCT Occupation from patient_info");
while ($row = mysql_fetch_array($sql)) {
echo "<option value=".$row['Occupation'].">".$row['Occupation']."</option>";
}
?>
</select>
</div>
<br>
<br>
<input type="submit" name="submit" value="Proceed"/>
</form>
In the specific_occupation.php file, I have this code:
<?php
include "connection.php";
$selectedoccupation = $_POST['occupation_dropdown'];
echo $selectedoccupation;
$myquery = "SELECT patient_info.Name, test_info.DateOfTest FROM `patient_info`,`test_info` WHERE patient_info.PatientID = test_info.PatientID AND patient_info.Occupation = '$selectedoccupation' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
This works fine if an occupation without any white space between them like "carpenter" is selected from the dropdown menu but doesn't work for "sales person". How can the $_POST be used for occupations with white spaces??
Thanks in advance !!
You're building your HTML wrong. You've got it as:
<option value=Sales Person>
^^^^^---what will get sent as the value
^^^^^^---some wonky unknown/non-standard attribute
This is incorrect. HTML now requires that ALL attributes be quoted:
<option value="Sales Person">
and even when the quotes weren't required, you still had to have the quotes to handle "spaced" data like this.
PHP post replace some characters such as - with whitespaces.
You can try urlencode($var) in your PHP script.

Unable to Submit to Database

Using the MVC Framework, I have made some code that is meant to add information to the Database.
In Index.php (views)
<form method="post" action="<?php echo URL;?>note/updatetopic">
<select>
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
<input type="submit" name="topic_selection" value="Choose" />
</form>
The Code above is meant to post information about what a user would like to revise.
In note.php (controllers)
public function updatetopic() {
if (isset($_POST['topic_selection'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic_selection']);
}
header('location: ' . URL . 'note');
}
The Code above is meant to get information from the code in index.php and forward it onto the note_model where it runs a function.
In note_model.php (models)
public function updatetopic($topic_selection)
{
$topic_selection = strip_tags($topic_selection);
$sql = "INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':topicselected' => $topic_selection, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
}
// default return
return false;
}
This is meant to validate the submitted information and insert it into the database but it outputs:
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
Can someone please help me and tell me what im doing wrong? Thanks.
You are not choosing any name for your select tag:
try like this:
<select name="topic">
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
And now get the the value of yuor drop down list:
if (isset($_POST['topic'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic']);
// $_POST['topic'] == 1 or 2 depends upon selection
}
you can change it like:
<select name="topic">
<option value="coasts">Coasts</option>
<option value="Energy_Demand">Energy Demand</option>
</select>
now u'll get the real value of selected list item and can move further....
Your SQL query will not work as you have tagged mysql which does not support this kind of syntax:
INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id
Basically there is no WHERE in MySQL (MySQL Insert Where query)
You should check for duplicated either in select query, or if there are unique keys - use ON DUPLICATE KEY. Also take a look at the linked topic

Create special dynamic select

I want to do the next thing but I don't know how to do this, I'll try to explain me
I have an field generated by php code like this (Works)
<select id="profiles_select" name="profiles_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['profile']);?>">
<?php echo strtoupper($system['profile']);?></option>
<?php
} while($system = mysql_fetch_assoc($r)); //the "$r" it's the query
$rows = mysql_num_rows($r);
if($rows > 0) {
mysql_data_seek($r, 0);
$systemas = mysql_fetch_assoc($r);
}
?>
</select>
The query
<?php
$q="SELECT DISTINCT profile FROM sys_profiles";
$r=mysql_query($q,$ConecLocal) or die(mysql_error());;
$systemas=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
What I need?
I need generate another similar to first generated by php code but, this time I need made a Query including the value of the first , something like this:
<?php
$value_select=$_GET['profiles_select'];
$q2="SELECT DISTINCT systems FROM sys_profiles where profile=$value_select";
$r2=mysql_query($q,$ConecLocal) or die(mysql_error());;
$profiles2=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
Next of the query I need show in the another the query result, something similar to the first select (generated by php), but do the query when the first of the it's selected
<select id="systems_select" name="system_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['systems']);?>">
<?php echo strtoupper($profiles2['systems']);?></option>
<?php
} while($profiles2 = mysql_fetch_assoc($r2)); //the "$r2" it's the another query
$rows2 = mysql_num_rows($r2);
if($rows2 > 0) {
mysql_data_seek($r2, 0);
$systemas = mysql_fetch_assoc($r2);
}
?>
</select>
Thanks for the help.

Creating an onChange select drop down with javascript and php but it's not working

What I am trying to do is create a drop down container of 32 different locations in Scotland and when one of the selections is selected, for example, Glasgow it should go to a URL which displays content such as heading, text, for each article in a div WHERE location = Glasgow.
I have no error messages or any sort of recognition that my code has worked as when I select one of the four on the drop down it does absolutely nothing.
Can come clean up and put right what I've done so far? I would be extremely greatful!
Here is my files which are being used:
header.php
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#location').change(function(){
//Retrieve Content from the back-end PHP page, and pass the ID selected
var url = 'location.php?location=' + $(this).val();
$('#txtHint').load(url);
});
});
</script>
</head>
<body>
<div id="header">
<div class="headerLeftContent">
<select id='location'>
<option href="Link to a dynamic page with all the content from glasgow" value="Glasgow">Glasgow</option>
<option href="Link to a dynamic page with all the content from x" value="x">x</option>
<option href="Link to a dynamic page with all the content from test" value="test">test</option>
<option href="Link to a dynamic page with all the content from edinburgh" value="Edinburgh">Edinburgh</option>
</select>
<div id='txtHint'></div>
</div>
</div>
</body>
</html>
location.php
<?php
$connect = mysql_connect('xxxxxx', 'xxxxxx', 'xxxxxx');
$select_db = mysql_select_db('xxxxxx');
$location = $_REQUEST['location'];
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
while($row = mysql_fetch_array($query))
{
echo $row['text'];
}
mysql_close($connect);
?>
And please any comments regarding 'SQL injection' or how 'mysql' should be 'PDO' are unwanted as I do understand this but I am simply testing at the moment and will amend this.
Thanks.
You seem to have a mistake concatenating your location name inside your MySQL query, and it's not matching anything (so nothing is echoed back). Change this:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
to
$query = "SELECT * FROM podContent WHERE location = '$location'";
(Unless you have stuff like .Glasgow. in your database...)
Then you have to call mysql_query($query) as Alon suggested.
You need to use mysql_query and pass the resource to the mysql_fetch_array function:
$query = "SELECT * FROM podContent WHERE location = '.$location.'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['text'];
}

Categories