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...
Related
I am currently trying to echo data which I have selected from a database using the following code:
(DB Connection line)
$sqlQ = 'SELECT w_Continent.ID, w_Continent.NAME as continent_name, w_Country.Name, w_Country.Continent FROM w_Continent JOIN w_Country ON w_Continent.ID = w_Country.Continent';
//Execute SQL Query
$stmtRow = $db->query($sqlQ);
<?php foreach($stmtRow->fetchAll() as $cont):;?>
<?php echo $cont['continent_name']; ?>
<?php endforeach; ?>
However, when checking the browser, this does not have the continents listed.
If you want your data listed you have to add this line to your code, after echoing "continent_name".
<?php echo "<br/>"; ?>
Or you can add "\n" and view listed text in "View Source" page of your browser.
<?php echo "\n"; ?>
Please bear in mind, I'm very new to PHP. I've only started taking it this semester at my school.
Here's what I want to eventually do: I have a senior project where I'm building a computer repair system. In the repair MySQL table, I have a bunch of fields and one of them is CustomerID (so I know which customers had which repair). I want to have a drop drown of customer's names, and then when I click on it, some how attach that customer's ID to a variable so I can do an INSERT statement. In order to partially achieve this, I've done things in smaller parts. The small part I have working is when I select a dropdown value, it outputs it to the screen, but that's in the javascript function.
Here's my code:
<?PHP
include('session.php');
$db_name = "";
$mysql_username = "";
$mysql_password = "";
$mysql_server = "";
$mysqli = new mysqli($mysql_server, $mysql_username, $mysql_password,
$db_name);
$query = "SELECT custID, CONCAT(custFirstName, ' ', custLastName) as
Customer_Name FROM customer";
$result = mysqli_query($mysqli, $query);
echo "<select name ='names' id='myselect' onchange = \"myFunction()\">";
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
echo "</select>";
echo "<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id=\"demo\"></p>
<script>
function myFunction() {
var x = document.getElementById(\"myselect\").value;
document.getElementById(\"demo\").innerHTML = x;
}
</script>";
$content = "<script> document.write(x) </script>";
echo "<br> <br> The technician ID = $sTechID <br> <br> The customer ID = $content";
?>
I can output the ID to the screen with the Javascript function, but when I try to store "x" into a php variable, it doesn't work. In chrome, the inspector says that X is undefined.
A side note: I made a test file with this code and it worked:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
Because the above code worked, I don't understand why my bigger code is not working.
I understand that my code is a mess, but any help will be greatly appreciated. Thanks!
PHP is a back-end language and can't detect front-end events such as click, change, etc.
In your larger code, the value of x will only be defined once the event is fired(onchange), that's when the select input changes. Javascript works that way, but PHP doesn't. Once PHP sends a response the first time, its job is done.
This is when you will want to use forms or Ajax.
Using forms would be a good start.
Quick note, it's good practice to try to keep HTML, CSS and JS separate from PHP as much as possible.
...
$result = mysqli_query($mysqli, $query);
?>
<form method='post' action='insert.php' /> <!-- Link to php file to insert data to database -->
<select name ='names' id='myselect' onchange = "myFunction()">
<?php
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
?>
</select>
<input type="submit" value="submit" /> <!-- You will need a button to submit the data -->
</form>
<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id="demo"></p>
And now your insert.php file would look like:
<?php
// Get data from that was posted from the form
$customer_id = $_POST['names'];
// Now do whatever with the customer ID
echo $customer_id;
I think you need a better understanding of PHP in general. PHP is executed BEFORE the browser executes the html/js that you've echo'd to it. The reason this works:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
is because you are writing JS to the dom and it's being executed once your browser reads it. If you run a var_dump($content); you will see that what you have stored in that PHP variable is not the result of x but actually a literal string that contains the text "<script> document.write(x) </script>".
The line echo "$content <br> <br> $content"; prints "<script> document.write(x) </script> <br> <br> <script> document.write(x) </script>"; to the DOM, which in turn is run as JS in the browser.
If you want your drop down selection to do something in PHP I would suggest triggering a JS function on change of the drop down that in turn sends an AJAX request to a separate PHP file that does what you need to do there and returns it to your function. This way you can update the HTML without navigating to another PHP page.
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.
I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>
At the moment I using a dynamic select to populate a dropdown. What I would like to do is display a 2nd dropdown with results based on the selection of the first. I have no idea how to go about this and have searched for an answer but to no avail. I have included the code I using to populate the first menu, and if you need any further code, please let me know. I am quite willing to look at jQuery or javascript if someone could help with the code. Many thanks
<form id="boxform" method="post" class="webform" name="boxform" />
<label for="company">Select a Company:</label>
<select name="company" id="company" />
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
UPDATE:
This is the code for the 2nd dropdown in php format that I have at the moment if it would help move on with this, thanks
<label for="boxrtnaddress">Select Address</label>
<select name="boxrtnaddress" id="boxrtvaddress" />
<option SELECTED VALUE="">Select Delivery Address</option>
<?php
while ($row_rs_select_address2 = mysql_fetch_assoc($rs_select_address2))
{
$value=$row_rs_select_address2['address1_com']. " ". $row_rs_select_address2['address2_com']. " ". $row_rs_select_address2['address3_com']. " ". $row_rs_select_address2['town_com']. " ". $row_rs_select_address2['postcode_com'];
$caption=$row_rs_select_address2['address1_com']. " ". $row_rs_select_address2['address2_com']. " ". $row_rs_select_address2['address3_com']. " ". $row_rs_select_address2['town_com']. " ". $row_rs_select_address2['postcode_com'];
echo "<option value=\"", $value, "\">", $caption, "</option>";
}
?>
</select>
+++++++++++++SOLUTION++++++++++
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#company").change(function() {
if ($(this).val()!="") $.get("getOptions.php?customer=" + $(this).val(), function(data) {
$("#divId").html(data);
});
});
});
</script>
getOptions.php
<?php
$customer = mysql_real_escape_string( $_GET["customer"] ); // not used here, it's the customer choosen
$con = mysql_connect("localhost","root","");
$db = "sample";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query_rs_select_address2 = sprintf("SELECT * FROM company_com where idcode_com = '$customer'");
$rs_select_address2 = mysql_query($query_rs_select_address2, $con) or die(mysql_error());
$row_rs_select_address2 = mysql_fetch_assoc($rs_select_address2);
$totalRows_rs_select_address2 = mysql_num_rows($rs_select_address2);
$address=$row_rs_select_address2['address1_com']. " ". $row_rs_select_address2['address2_com']. " ". $row_rs_select_address2['address3_com']. " ". $row_rs_select_address2['town_com']. " ". $row_rs_select_address2['postcode_com'];
echo '<select name="customer">'.'<option value="">Select delivery address</option>'.'<option value="address">'.$address.'</option>'.'</select>';
?>
it may help, here is a fiddle
http://jsfiddle.net/gZzQr/
that dynamically appends a select based on the selection of first select the code is messy and dirty so im not gonna post it here :)
you can have a look at the following to better understand the working
change triggers when the selected value of a select is changed
is(':empty') checks whether the div to which the newly created `select
is to be appended is empty or not
http://api.jquery.com/is/
http://api.jquery.com/empty/
Edit
i'll give you hints hopefully you'll fill in the rest of code...
first of all what you need to do is handle the change event of your first drop down and when the value changes you can do an ajax, get, post request to your server, fetch the results and populate the second drop down, here is a useful stackoverflow link that may help you
php dropdown menu population
$("#firstDD").change(function(){
var value = $(this).val();//get the changed value of first dd(drop down)
//now do a post request
$.post("results.php",{data:value},function(data){
//get the values here and populate the second drop down
});
});
in your results.php
get the value from first drop down
$val = $_POST['data'];
//now do the sql queries to fetch desired result
//and echo the results back
echo $results ;
here are some useful links
http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/
http://api.jquery.com/jQuery.post/
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php