Php dropdown menu displaying data via MySQL - php

I've installed the MySQL database using the script as in http://www.databasejournal.com/scripts/practice-sql.html :
Then I have my PHP code learnt from Youtube video about how to populate dropdown with data from SQL, but It still can't work that nothing turns out when clicking the "Show details" submit button. I am still new to PHP and can't sort it out myself. Thank you !!
// PHP Code
<?php
require'require.php';
$usersQuery="
SELECT DISTINCT
c.cno,
c.cname,
o.eno,
o.shipped
FROM customers c
RIGHT JOIN orders o
ON c.cno=o.cno
group by (c.cname)
";
$users=$db->query($usersQuery);
if(isset($_GET['user'])){
$userQuery="
{$usersQuery}
WHERE c.cno=:cno";
$user= $db->prepare($userQuery);
$user->execute(['cno'=>$_GET['user']]);
$selectedUser=$user->fetch(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dropbox</title>
<script language=JavaScript>
</script>
</head>
<body>
<h3>My Dropdown</h3>
<form action="dropbox.php" method="get">
<select name="user">
<option value="">Choose one</option>
<?php foreach($users->fetchAll() as $user):?>
<option value="<?php echo $user['cno'];?>" <?php echo isset($selectedUser)&& $selectedUser['cno']==$user['cno']? "selected":""?> > <?php echo $user['cname'];?> </option>
<?php endforeach ?>
</select>
<input type="submit" value="Show details" >
</form>
<?php if(isset($selectedUser)):?>
<pre><?php echo($selectedUser['cno']);?></pre>
<?php endif; ?>
</body>
</html>

There is problem is you execute statement. you forget : in it and you have to pass array into it.It would be
$user->execute(array(":cno" =>$_GET['user']));
$selectedUser=$user->fetch(PDO::FETCH_ASSOC);
Read execute

This is a code that works.
I tried to commented all the modifications i made from ur code
But first let's look into the query u made :
SELECT DISTINCT c.cno, c.cname, o.eno, o.shipped
FROM customers c
RIGHT JOIN orders o
ON c.cno=o.cno
group by (c.cname)
DISTINCT and GROUP BY #strawberry said doesn't like to be in same query.
IN this query the GROUP BY clause "will merge" the result of the query BY cname.
ORIGINAL :
But let's suppose we entered 2 clients with the same name (it's possible coz PRIMARY KEY is cdo) and both of these clients ordered something. U'll miss one by using GROUP BY on a column that isn't a PRIMARY KEY.
BEST way to GROUP BY was on PRIMARY KEY.
Btw Ur variables names can be tricky (like $users & $user)
Original queries variables :
$usersQuery = "SELECT c.cno, c.cname
FROM customers c, orders o
WHERE c.cno = o.cno
GROUP BY c.cno";
AND
$userQuery = "SELECT *
FROM customers
WHERE cno = :cno";
EDIT : see Strawberry's comment (below)
GROUP BY VS DISTINCT
I was mistaking about how to build query so i made changes in this way. A better process (for the mind) is running with this query :
"SELECT DISTINCT c.cno, c.cname, c.street, c.zip, c.phone
FROM orders o
LEFT JOIN customers c
ON o.cno = c.cno"
Then add a WHERE clause when one user is returned by the form :
.
<?php
// My include of connecting to my DB - same as ur require.php i suppose
include("./inc.connect.php");
// As said before
$usersQuery = "SELECT DISTINCT c.cno, c.cname, c.street, c.zip, c.phone
FROM orders o
LEFT JOIN customers c
ON o.cno = c.cno";
$users = $db->query($usersQuery);
if(isset($_GET['user']))
{
// This query will return all informations about the user u selected
// $userQuery="{$usersQuery} WHERE c.cno=:cno"
// as #saty said u missed ':' but ur string query
// You included 2 clause WHERE
// (from usersQuery and the concatenation)
$userQuery = "{usersQuery} WHERE cno = :cno";
$user = $db->prepare($userQuery);
$user->execute(array(":cno" => $_GET['user']));
$selectedUser = $user->fetch(PDO::FETCH_ASSOC);
// Display the array (<pre> tag make it readable)
print "<pre>";
print_r($selectedUser);
print "</pre>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Dropbox</title>
<script>
</script>
</head>
<body>
<h3>My Dropdown</h3>
<!-- Nothing important : just changed action value coz
of my name's page -->
<form action="index.php" method="get">
<select name="user">
<!-- Added "Default" value for first option -->
<option value="Default">Choose one</option>
<?php
// used echo only to display html tags -
// make it cleaner to read
foreach($users->fetchAll() as $user)
{
// Can't make the display Better - SRY
echo "<option value=\"" . $user['cno'] . "\"";
echo (isset($selectedUser) &&
($selectedUser['cno'] == $user['cno']))
? "selected" :"";
echo ">" . $user['cname'] . "</option>";
}
?>
</select>
<input type="submit" value="Show details">
</form>
<?php
if(isset($selectedUser))
echo "<pre>" . ($selectedUser['cno']) . "</pre>";
?>
</body>
</html>
Hope that helped.

Related

PHP not displaying unordered list

I have a PHP program that is supposed to print customer purchase history after selecting the customer name from a dropdown menu. However, after selecting a customer, the unordered list that is supposed to be displayed, is empty.
Here is my code
<!DOCTYPE html>
<html>
<body>
<script src="customerselect.js"></script>
<?php
include "connecttodb.php";
include "getcustomer.php";
?>
<h1>Customers</h1>
<br>
Customers
Products
<br>
<hr>
<hr>
Select the customer whom you'd like to see what items they've purchased:
<form action="" method = "post">
<select name="pickacustomer" id="pickacustomer">
<option value="1">Select Here</option>
<?php
include "getcustomername.php";
?>
</select>
</form>
<hr>
<?php
if (isset($_POST['pickacustomer'])){
include "connecttodb.php";
include "getcustomerinfo.php"; #This is the line that I expect to print my customer purchase history
}
?>
<hr>
<br>
<br>
<h2>List of all Customers</h2>
</body>
</html>
getcustomerinfo.php
<?php
$connection = mysqli_connect("localhost", "root", "xxx", "xxx") or die("Not connected");
$whichCustomer = $_POST["pickacustomer"];
$query = "
SELECT c.firstname
, c.lastname
, p.description
, u.quantitybought
FROM purchased u
JOIN customer c
ON u.customerid = c.customerid
JOIN products p
ON u.productid = p.productid
WHERE c.firstname = ". $whichCustomer.";";
$result = mysqli_query($connection, $query);
if (!$result) {
die("databases query failed - getcustomerinfo.php.");
}
echo "<ul>";
while ($row = mysqli_fetch_assoc($result)){
echo "<li>" . $row["firstname"] . $row["lastname"]. $row["description"]. $row["quantitybought"]. "</li>";
}
echo "</ul>";
mysqli_free_result($result);
?>
customerselect.js
window.onload=function(){
prepareListener();
}
function prepareListener(){
var droppy;
droppy = document.getElementById("pickacustomer");
droppy.addEventListener("change",getCustomer);
}
function getCustomer(){
this.form.submit();
}
I know that the query in getcustomerinfo.php works because if I enter an actual customer name, it'll display it. However, when I try to dynamically assign a name to it, the program fails to display the proper information. Please excuse how poorly this code is written as I'm just starting to learn PHP.
Thanks to user3783243 reminding me to double check the POST field, I realized that I was receiving the customerid rather than the customer.firstname in the POST field. So in getcustomerinfo.php, the query should be edited like so: ...WHERE customer.customerid... rather than ...WHERE customer.firstname...

How to populate a select tag from values based on another select tag with codeigniter

Please forgive me if I make any mistakes in english, its not really my best language. I will edit this post if I make errors please let me know.
I'm trying to make a php page with Codeigniter with a select tag whose values are from a database, and am trying to populate a second select tag based from the value placed on the former.
My college_subj database have three columns.
CollCode, SC, and Subj.
Basically, the College Code(CollCode) and Subject Code(SC) have combinations. A College Code X can have A,B,C SC, and College Code Y can have B,C,D,E SC. I am trying to make those SC appear on my second select tag when the first select tag, the CollCode, has a value.
The page's function is accept values from the two select tags and insert it into the database.
Here's the select tags on my edit.php:
<form method="post" action="<?php echo base_url();>index.php/Controller/insertfunction" id="crq">
<h3>Select College Code:</h3>
<select id="codecrq" name="code">
<option value="" selected="selected">---Select College Code---</option>
<?php foreach ($code as $row4): ?>
<option label="<?php echo $row4['Code']; ?>" value="<?php echo $row4['Code']; ?>" <?php echo set_select('code', $row4['Code'], False); ?>> <?php echo $row4['Code'] ; ?> </option>
<?php endforeach; ?>
</select>
<h3>Select SC:</h3>
<select id="sccrq" name="sc">
<option value="" selected="selected">---Select SC---</option>
</select>
</form>
Here's how I get the values that I placed in the Code select tag which is in the Model:
public function Code() {
$this->db->distinct();
$this->db->select('college_subj.CollCode');
$this->db->from('college_subj');
$query = $this->db->get();
return $query->result_array();
}
Here's a jquery that I try to use to populate the SC select tag:
$("#codecrq").change(function(){
var selectedMark = $("code").val();
if(selectedMark !== ""){
$.ajax({
type: "GET",
url: "Controller/sccrq/" + selectedMark,
success: function(data){
$("#sccrq").html("");
$("#sccrq").append("<option value=''></option>");
$.each(data, function(){
$("#sccrq").append("<option value='" + this.sc + "'>" + this.sc + "</option>");
});
}
});
}
});
and here's the sccrq code from my controller, which is supposed to get the SCs based from the College Code combination and pass it on the SC select tag:
function sccrq($code){
$this->db->distinct();
$this->db->select('college_subj.sc');
$this->db->from('college_subj');
$this->db->where($code);
$query = $this->db->get()->result_array();
return $query;
}
I try making it run, but nothing comes out from the SC select tag.
Any help will be deeply appreciated!
Thank you for you're time!
You can try
function sccrq($code){
$query = $this->db->query("SELECT SC FROM college_subj WHERE code = '".$code."'");
return $query;
}

Data retrieved from database to Dropdown list. User selects option and then send that value to Database?

Now I have been trying to figure out a way to insert a dropdown menu selection by a user on the web-interface into MySQL database table_2 using PHP. The problem is that the dropdown list items are retrieved from the MySQL database from another table_2. Can someone please help me? Thank you in advance! Below shows the code I am using.
<?php
$con = mysqli_connect("localhost","root","");
$myDB = mysqli_select_db($con, "database");
$sqlSELECT = mysqli_query($con, 'SELECT disastergroup FROM disastergroups');
if (isset($_POST['group']))
{
$group = $_POST['group'];
$test = "SELECT disastergroupid FROM disastergroups WHERE disastergroup = '$group'";
mysqli_query($con, $test);
$test_store = "INSERT INTO events (groupid_FK) VALUES ($test);"
mysqli_query($con,$test_store);
}
else
{
echo "An option must be selected!";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Title of Page</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<body>
<form action = "detailslog.php" method = "POST">
<label for="groups">Disasters:</label>
<select name = "groups">
<option value = "">Select...</option>
<?php while($row = mysqli_fetch_assoc($sqlSELECT)):;?>
<option><?php $row1['disastergroup'];?></option>
<?php endwhile;?>
</select>
<input type="submit" value="Submit Data">
</form>
</body>
</html>
So what I want to do is take the user's selection from the options "groups" and use that value to get the ID of that value from the table disastergroups and then store that ID into the table "events" as a Foreign Key. This have been giving me hell to figure out. Any help would be greatly appreciated! Thank you!
$sql_quer = mysqli_query($con, $test);
$FK_id = mysqli_fetch_assoc($sql_quer);
$test_store = "INSERT INTO events (groupid_FK) VALUES ($FK_id[disastergroupid]);"
mysqli_query($con,$test_store);
This fixed my problem for anyone viewing this post!

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

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

How to populate dependant select menus dynamically using jQuery, PHP and MySQL?

I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.

Categories