i almost got this, but i need the comboboxes to be dynamic and i cant get it, this is how it looks:
! http://imgur.com/ppoKOBI
I have this code:
<form action="PostDelPhoto.php" name="delForm" method="post" >
<select name="categoriaMod" id="catMod">
</br>
<?php
require('bd.php');
$sql="SELECT * FROM Categorias ORDER BY ID DESC;";
$queryexec=mysql_query($sql,$conn);
while ($row = mysql_fetch_array($queryexec)){
$Categoria =$row["nombre_categoria"];
echo '<option value="'.$Categoria.'">'.$Categoria.'</option>';
};
echo'</select>';
?>
<select name="SelectPhoto" id="SelectPhoto" value="">
<?php
require('bd.php');
$sql="SELECT * FROM Paisajes ORDER BY ID DESC;";
$queryexec=mysql_query($sql,$conn);
while ($row = mysql_fetch_array($queryexec)){
$filename =$row["nombre_archivo"];
echo '<option value="'.$filename.'">'.$filename.'</option>';
};
echo'</select>';
?>
In this last php While, I need static "Paisajes" from the SQL Query, to take the value in real time from option combobox after it, but i cant manage to get it.
All ideas are welcome! Thanks!
Related
I have a form where user selects the category while adding the product.
When user want to edit the product, i am displaying all the previously populated values but could not able to figure out how to display the category he selected.
addproduct.php (displaying the categories from the database)- this code is working fine and can see all the categories in dropdown
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
In the edit product i want to display all the categories like above, but want to display the selected category in the form which i could not able to do.
editproduct.php (rough draft code) -- not working
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option select="<?php echo $cat;?>"value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
$cat - category value(previously selected) pulled from database
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
<option value="<?php echo $cat;?>"><?php echo $cat;?></option>
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<?php if($cat!=$subjectData['name']){?> <option value="<?
php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
<?php } ?>
Try using this code and please use mysqli as mysql is deprecated. previously selected category should be before while loop. Hope it helps
Two issues with your code:
You are using mysql functions, which are depreciated and don't even exist in the current version of PHP. Use mysqli or PDO functions.
The html you are generating is invalid syntax.
I'll leave the first issue to you to correct.
For the 2nd issue, all of the non-selected options in your dropdown will not have the selected attribute.
Only the selected item will have that attribute. The code below assumes that the variable $cat has the previously selected value, and each row has a
column named 'cat'. When $cat matches the value in the column 'cat', it will add selected='selected' to the option.
<?php
require 'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];
$selected = "";
if($cat == $subjectData['cat']) {
$selected = "selected='selected' ";
}
echo "<option ".$selected."value=".$subjectData['name'].">";
echo $subjectData['name'];
echo "</option>\n";
}
?>
I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.
You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.
I am showing the dropdowns based on the above selected dropdowns. I want the result in third dropdown. For that I am writing the sql query in php and writing the change event in jquery but i am unable to get the result. I am stuck up there
My jquery looks like
$(document).ready(function(){
$("#parent_cat,#city").change(function(){
$.get('loadlocation.php?city=' + $(this).val() , function(data) {
$("#sub_cat").html(data);
});
});
});
parent_cat and city are from selected values
<label for="category">Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label for="city">city</label>
<select name="city" id="city">
<?php while($row = mysql_fetch_array($query_parent1)): ?>
<option value="<?php echo $row['city']; ?>"><?php echo $row['city']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
And my php file loadlocation.php is
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$city = $_GET['city'];
$query = mysql_query("SELECT table_place_detail.post_title FROM table_terms, table_place_detail, table_post_locations
WHERE table_place_detail.post_location_id = table_post_locations.location_id AND table_place_detail.default_category = table_terms.term_id AND table_post_locations.city = '$city' AND table_terms.name = '$parent_cat'");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[post_title]'>$row[post_title]</option>";
}
?>
I want to fetch the values of parent_cat, city to loadlocation.php but i am not able to get those values. I want to load the two values and get the query excecuted and the values should shown in 3rd dropdown as below can any one help this issue
<label>Vendors List 1</label>
<select name="sub_cat" id="sub_cat"></select>
Two things stand out
You send only one value, ?city=
According to the manual jQuery.get(), you can send additional parameters as a plain object. This means, you don't need to build a query string, but can pass parent_cat and city separately, e.g.
$.get("loadlocation.php",
{ parent_cat: $('#parent_cat').val(), city: $('#city').val() },
function(data) {
$('#sub_cat').html(data);
});
And finally, the mandatory hint at each mysql_* page
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
I'm looking for a way to make it so when a user starts typing into a input field, it will start to generate results underneath in a drop down.
For instance, like when you start typing into Google or the Facebook search bar.
What is that actually called?
UPDATE:
I have decided to use jQuery AutoComplete.
I have the following
<form action="" method="post">
<input type="text" class="auto" name="search" autocomplete="off">
</form>
<script>
$(document).ready(function($){
$('.auto').autocomplete({
source:'connect.php',
minLength:1
});
});
</script>
And connect.php
I KNOW I have to sanitize $term before inputting it into my query.
if(isset($_GET['term'])) {
require "db.php";
$con = mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$term = $_GET['term'];
$query = "SELECT `name` FROM `products` WHERE `name` LIKE '%$term%'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
}
Now when I use chrome tools to inspect the response, It works completely fine, it brings back the data I wanted in a JSON format.
However, for some reason, it states 'No results found' on the page even though there is?
It's called typeahead/autocomplete.
Twitter Bootstrap 2.0 (outdated - not available in 3.0) & jQuery UI have what you require.
You need to get all of the records from database and return them.
I suggest making an ajax request to the server (php script). First you would need an oninput event handler for the text box for the search. The php script will return the records you want. Here is my code:
<input type="text" id="searchBox" oninput="searchTheDatabase(this.value)" value="let us search it'>
<div id="results"></div>
Javascript:
<script type="text/javascript">
function searchTheDatabase(searchText)
{
$.post( "search.php", { searchText:searchText})
.done(function( data ) {
$("#results").html(data);
});
}
</script>
PHP:
<?php
//put your connection code here
$searchText = mysql_real_string_escape($_POST['searchText']);
$searchTextLength = strlen($searchText);
$query = "select * from products where";
//I'm not sure how you search for only the first so many characters, but you can use $searchTextLength to help you
$result = mysql_query($query, $connect);
while($row = mysql_fetch_array($result))
{
echo $row['name'];
}
?>
Let me know if this doesn't work for you and I will do some more coding. :-) good luck!
It's sometimes a part of the UI for the Browser, where it auto completes your fields for you with past entries. There is a HTML5 element called datalist where you can tie that element into the list attribute for an input field to get the same results
<div>Choose a browser from this list:</div>
<input list="browsers" />
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
</datalist>
For this, all you need do is populate datalist's option values with entries from your database. something like this would work ...
<?php
$pdo = new POD('mysql:host=localhost;dbname=test', 'username', 'password', [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']);
$sth = $pdo->prepare("SELECT id, value FROM browsers");
$rows = $sth->execute()->fetchAll();
?>
<div>Choose a browser from this list:</div>
<input list="browsers" />
<datalist id="browsers">
<? foreach ($rows as $row): ?>
<option value="<?=$row['value']?>">
<? endforeach; ?>
</datalist>
How am i going to display the data from the database into the textbox? pls help
//Javascript textbox
<div class="Text">
<input class="Text" type="text" value="
<?PHP echo $id?>" name="id" size="19"/>
//PHP MYSQL Connect code
<?php
error_reporting(0);
include('../connection.php');
$id =$_REQUEST['id'];
$result = mysql_query("SELECT * FROM cust WHERE id = '$id'");
$test = mysql_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$id=$test['id'] ;
?>
Place your PHP code before HTML
//PHP MYSQL Connect code
<?php
error_reporting(0);
include('../connection.php');
$id =$_REQUEST['id'];
$result = mysql_query("SELECT * FROM cust WHERE id = '$id'");
$test = mysql_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$id=$test['id'] ;
?>
//Javascript textbox
<div class="Text">
<input class="Text" type="text" value="
<?PHP echo $id?>" name="id" size="19"/>
Note: mysql_* functions are deprecated. please try to use mysqli_* or PDO.
Put following PHP code before your HTML,
PHP
<?php
$con = new mysqli_connect(host,user,pass,dbname);
$id = $_REQUEST['id'];
$query = "SELECT * FROM cust WHERE id = '$id'";
$result = mysqli_query($query);
if (!$result)
{
die("Error: Data not found..");
}
$test = mysqli_fetch_array($result);
$id=$test['id'] ;
?>
HTML & PHP (inside body)
<div class="Text">
<input class="Text" type="text" value="<?PHP echo $id; ?>" name="id" size="19"/>
Hope this help you!
One good approach for element rendering is to make HTML Helper Libraries. Like for example create a class HTML having a set of static tag creator methods.
#Pseudo HTML helper class - HTML.class.php
class HTML
public static input(type, id, class, data, text)
public static heading(mode, text)
#Pseudo input tag helper - HTML.class.php::input
function input(type, id, value) {
# method create the html string for the given input.
return ["<input type=",type," id=",id," value=",value,"/>"].join('');
}
<?php
$con = new mysqli(host,user,pass,dbname);
$query = "SELECT * FROM cust WHERE id = '$id'";
$result = $con-> query($query);
while ($row = $result->fetch_assoc()){
$value = $row['id'];
echo HTML::input('text', id, $id);
}
?>
I think this just the same as above answers. but i prefer when you write code it should be modular, clean and beautiful. Always use good practices. Thats why i shared my thought here. If you create your own or others helper class help you with faster development also i suggest contributions to it help you in learning. I know that this is not the answer what you are looking, but anyway free to revert back at any time.
Working Solution
<?php
include("database.php");
$db=$conn;
// fetch query
function fetch_data(){
global $db;
$query="SELECT * FROM users WHERE username='vii'"; // change this
$exec=mysqli_query($db, $query);
if(mysqli_num_rows($exec)>0){
$row= mysqli_fetch_all($exec, MYSQLI_ASSOC);
return $row;
}else{
return $row=[];
}
}
$fetchData= fetch_data();
show_data($fetchData);
foreach($fetchData as $data){
$firstname=$data['udid'];} // change this 'udid' to your table field
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Retrieve Contact</title>
</head>
<body>
<input type=text value= <?php echo $firstname; ?>
</body>
</html>