I have two tags, the first one is to select the brand and the second one is to select the product.
My question/problem is that I want to tell php to echo inside the second select tag. The echoed option needs to have the same brand_name as the selected option from the first tag.
What I need is that if I choose Adidas as the brand, php would show every product that has the brand_name Adidas.
I have two different database tables, the first one called brand:
brand_id | brand_name
1 | ADIDAS
2 | NIKE
The second one called product:
product_id | brand_name | product_name | product_image | amount | sell | buy
1 | ADIDAS | T-Shirt | none | 50 | 30 | 28
2 | NIKE | Shoes | none | 20 | 130 | 120
Here is my code:
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
$query = "SELECT `brand_name` FROM `brands`";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] ='Error loading the brands';
$_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option name="brand_name" value='.$row['brand_name'].'>'.$row['brand_name'].'</option>';
}
}
?>
</select>
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
###########HERE WHERE I NEED MY CODE##############
$query = "SELECT `product_name` FROM `product WHERE brand_name = "##### The selected option from the first select tag" ";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] = "Error loading the prouducts";
$_SESSION['errormessage'] = 'Something wrong happend while loading the proudcts.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option name="product_name" value='.$row['product_name'].'>'.$row['product_name'].'</option>';
}
}
?>
</select>
There are two options:
First: Download all contents of 'products' table, and make script that will add items with selected 'brand' attribute to box.
Second: (Recommended) When user selects a brand, make an AJAX query, and get all items with selected brand.
Second one is much better, because you will need to download less data, and page will load faster.
Imagine you have 10^9 products, and 10^7 brands(average 100 products per brand)
Using first solution, you will need to download all 10^9 products, and then use JavaScript(which is not very fast) to select 100 of them.
If you use second solution two things are going to be much better:
1. Download 100 items instead of 10^9.
2. To select items use fast SQL engine instead of slow JavaScript
It is not possible to do it with php, because php is server-side. Server is making page code with php, and then sending it to user. It's impossible to make callback to php without AJAX
The easiest way to do this would be to use a single SELECT with LEFT JOIN, to get all of the columns from both tables at the same time:
SELECT brands.brand_name, products.product_name FROM brands LEFT JOIN products on brands.brand_name = products.brand_name GROUP BY brands.brand_name
And build both of your <select> nodes from that single query. To do this, build your first <select> node from the query, the same as you are doing now, then in the lower part of the code reset the $response with $response->data_seek(0). Then you can build the second <select> as though you had done another query.
It will look something like the following code. There are only two minor changes to your original. Look for some comments in the top section, and some in the bottom section. I don't have an easy mechanism to run PHP, so I can't test it, and it might not run perfectly as it is now. But I think it will give you an idea of what to do.
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
// Notice that the query includes LEFT JOIN, to get the
// columns from both tables in a single query.
$query = "SELECT brands.brand_name, products.product_name
FROM brands left join products on brands.brand_name = products.brand_name"
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] ='Error loading the brands';
$_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option name="brand_name" value='.$row['brand_name'].'>'.$row['brand_name'].'</option>';
}
}
?>
</select>
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
// Here, you don't need another query. You simply reset
// $response, and then fetch as you would from a
// normal query.
$response->data_seek(0);
while($row = mysqli_fetch_array($response)){
echo '<option name="product_name" value='.$row['product_name'].'>'.$row['product_name'].'</option>';
}
?>
</select>
You can simply use Ajax to do this. I'll try to explain step by step.
I assume jQuery is loaded.
Your product table should use brand_id not brand_name.
product_id|brand_name | product_name | product_image | amount | sell | buy
1 |brand_name_1| T-Shirt | none | 50 | 30 | 28
2 |brand_name_2| Shoes | none | 20 | 130 | 120
I hope this will help you.
Step - Create your first and second select box by using name or id attributes. I will be using the name to define them.
<select name="brand_name">
<?php //call brand_name options from your database
//Sample : <option value="brand_name_1">Brand_Name_1</option>?>
</select>
<select name="product_name" disabled >
<?php //dont fill this select box.
//Leave it empty, contents will be created after our ajax call
?>
</select>
Step
Add jQuery script to your page as below.
<script>
$('[name="brand_name"]').change(function(event){
var brand_name = $(this).val();
$.get(
"ajax.php",
{ brand_name: brand_name },
function(data) {
var opts = $.parseJSON(data);
$.each(opts, function(i, d) {
$('[name="product_name"]').append($('<option>', {
value: d.product_name,
text : d.product_name
}));
});
//Enable the product_name select box
$('[name="product_name"]').prop('disabled', false);
//Refresh the product_name select box
$('[name="product_name"]').selectpicker('refresh');
}
);
});
</script>
Step - The ajax.php must look something like below. I have used your php query code here.
<?php
require_once 'connections/dbc.php';
$getBrandName = $_REQUEST['brand_name']; // This is the id of the selected brand name
$query = "SELECT product_name FROM product WHERE brand_id = '$getBrandName' ";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] = "Error loading the prouducts";
$_SESSION['errormessage'] = 'Something wrong happend while loading the proudcts.<br/>Please contact The developer';
//Below Header method will not work cause headers are already been set. You will not be able to redirect page. So just delete it. instead you can return an error by using the json.
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
$prodyctsArray[]['name'] = $row['product_name'];
}
echo json_encode($brandName);
}
?>
For more information I suggest you to visit references below:
jQuery.ajax()
jQuery.get()
Introducing JSON
Related
I have a PHP page that's the product list as depicted below. The last column is the link to the single product page reporting all the details about that product.
ID | Title | LINKTOPAGE
-------|--------------|------------------
001 | ProductTitle | $ID(001)-->Link to the single_product_page.php
002 | ProductTitle | $ID(002)-->Link to the single_product_page.php
003 | ProductTitle | $ID(003)-->Link to the single_product_page.php
The above table is generated by the following loop:
<?php
while ($row = mysqli_fetch_array($risultato)){
echo '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['post_title'].'</td>
<td>'.'LinkToSinglePage >>'.'</td>
</tr>';
}?>
I have already prepared the single page that retrieves data from this query:
SELECT
p.id as ID,
p.post_title,
p.post_status,
p.post_excerpt as shortdesc,
p.post_content as longdesc
FROM mg_posts as p
WHERE p.ID= 13323
GROUP BY p.ID
What I am trying to do it is to link the "linktoProductPaGe" to the single page. If I am not wrong I should replace the ID=13323 with the variable that stores the ID of the selected product in the list.
Any suggestion on how?
You can do it like that, for example (get method):
Product list (products_lists.php):
<?php
while ($row = mysqli_fetch_array($risultato)){
echo '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['post_title'].'</td>
<td>single_product_page.php?product_id='.$row['id'].'</td>
</tr>';
}?>
And in your product detail page (single_product_page.php), you can get the id like that:
<?php $product_id = $_GET['product_id']; ?>
Hope that will help. :-)
To avoid having an syntax error when opening the page single_product_page.php from the browser, you should add the following code:
if(!isset($_GET['product_id']){
echo 'No product selected.';
}else{
// Your code to get the product infos
}
This is probably because the tag "action" of your HTML form is either not defined or has the value "singolo_prodotto.php".
So, at the beginning of the PHP code of your page "singolo_prodotto.php", you should add the following code, as explained further up :
if(!isset($_GET['product_id']){
echo 'No product selected.';
}else{
// Your code to get the product infos
}
And when you'll have to manage the edition of the product, you'll have to add another condition like that :
if(!isset($_GET['a_field_of_your_html_form']){ // Or "$_POST['a_field_of_your_html_form']"
// Your product edition code
}
I have two tables and i want to echo the total call count once each user logins:
Login
Firstname | Lastname | Login ID
------------------------------
Tyler | Durden | 3
Call Count
Name | Call Count | Open | GrandTotal
------------------------------
Tyler Durden| 100 | 33 | 133
i tried:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name=".$_SESSION['firstname']. ' ' .$_SESSION['lastname']." ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
But its not working, i think i have to join the the two tables to get it to work. What do you think?
Assuming your Call Count table is actually called csvdata, you'll want to format your SQL request string a bit by adding single quotes around the WHERE name = part.
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name='".$_SESSION['firstname']. ' ' .$_SESSION['lastname']."' ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Call Count'].' Call Count';
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
Good practice would require that you use primary keys to facilitate joins between tables and make sure two users with the same name can be differenciated.
In that case you may want to consider replacing the Name column in your Call Count table for your loginID. This way you could get your name from the Login table (as shown below). Also, as bad as it is to have duplicated data like your user's name in both tables, you do not need your GrandTotal column since you can easily get the sum of CallCount and Open to get the exact same number. In the end, your query should look more like this (assuming your tables are called Login and CallCount).
<?php
$result = mysqli_query($mysqli, "SELECT l.FirstName, l.LastName, cc.CallCount, cc.Open, (cc.CallCount + cc.Open) AS GrandTotal FROM Login AS l JOIN CallCount AS cc ON l.LoginID = cc.LoginID WHERE l.FirstName LIKE \"".$_SESSION['firstname']."\" AND l.LastName LIKE \"".$_SESSION['lastname']."\"");
// ...
?>
I have a form which puts together an estimate based on the inputs you fill in and select. One of these inputs is a group of checkboxes that determines what finishes the project receives. They go into the database as an array (name="finishes_id[]"). They are put into a table called finishes_used which looks like the following:
used_id | estimate_id | finish_id
This table links together the finishes table with the estimates table. So for example, if 3 different finishes were chosen for one estimate, it would look like this:
used_id | line_id | estimate_id | finish_id
1 1 1000 2
2 1 1000 6
3 1 1000 7
I am now making an edit page for the estimate and I am having trouble figuring out how to pre-select the finishes checkboxes that were used. It is showing ONLY the checkboxes that were selected. I need the option to check the others as well.
My code for the checkboxes part of my form looks like the following. How can I get the desired results above?
<?php
$getid = $_GET['estimate_id']; // The current estimate number
$getLineid = $_GET['line_id']; // The current line item on the estimate
?>
<label for="finish_id">Finishing</label>
<div class="checkbox_group">
<?php
if ($select = $db -> prepare("SELECT f.finish_id, f.finish_name, u.estimate_id, u.line_id FROM finishes AS f INNER JOIN finishes_used AS u ON u.finish_id = f.finish_id WHERE u.line_id = ? ORDER BY f.finish_name ASC"))
{
$select -> bind_param('s', $getLineID);
$select -> execute();
$select -> bind_result($finish_id, $finish_name, $used_estimate_id, $used_line_id);
while ($select -> fetch())
{
echo '<div class="checkbox">';
echo '<input type="checkbox" name="finish_id[]" id="edit_'.$finish_name.'" value="'.$finish_id.'" ';
echo '/><label for="edit_'.$finish_name.'">'.$finish_name.'</label>';
echo '</div>';
}
$select -> close();
}
?>
</div>
It seems to me you have to use left outer join instead of inner join to achieve this.
Here is a great explanation about joins: What is the difference between "INNER JOIN" and "OUTER JOIN"?
What I want to achieve:
Insert data into database table using chained select list (the options values are taken from database table)
Requirement: for the first select list ("tip_cheltuiala"), the available options values must be only the ones that are not used in the rows already inserted (available options are: option 1, 2 and 3; I already inserted rows with option 1 and 3, and now only option 2 must be available)
1. the select list "tip_cheltuiala":
echo '<select name="tip_cheltuiala'.$row_chelt['id_factura'].'" id="tip_cheltuiala'.$row_chelt['id_factura'].'" class="selectContentIncasare">'.$opt_mod_inchidere->TipCheltuiala().'</select>';
and the function for that select list:
class SelectListModInchidere{
public function TipCheltuiala(){
//looking for options that are already in the table
$stmt_chelt_inchisa = $this->conn->prepare('SELECT tip_cheltuiala FROM cheltuieli_mod_inchidere');
$stmt_chelt_inchisa->execute(array());
$results_chelt_inchisa = $stmt_chelt_inchisa->fetchAll();
foreach($results_chelt_inchisa as $row_chelt_inchisa) {
$chelt_inchisa[] = $row_chelt_inchisa['tip_cheltuiala'];
}
print_r($chelt_inchisa); // returns options 1 and 3
for($i=0; $i < count($chelt_inchisa); $i++){
$stmt_tip_chelt = $this->conn->prepare('SELECT * FROM mi_categ_cheltuiala
WHERE tip_cheltuiala <> :chelt_inchisa');
$stmt_tip_chelt->execute(array('chelt_inchisa' => $chelt_inchisa[$i]));
$tip_cheltuiala = '<option value="0">selectati ...</option>';
while($row_tip_chelt = $stmt_tip_chelt->fetch()) {
$tip_cheltuiala .= '<option value="' . $row_tip_chelt['tip_cheltuiala'] . '">' . $row_tip_chelt['tip_cheltuiala'] . '</option>';
}
return $tip_cheltuiala;
}
}
}
$opt_mod_inchidere = new SelectListModInchidere();
There I have the first issue: the select list is populated with option 2 (that is correct) but also with option 3 - I can't figure out why.
2. the select list "mod_inchidere":
returns the option values according with the selected option in select list "tip_cheltuiala
echo '<select name="mod_inchidere'.$row_chelt['id_factura'].'" id="mod_inchidere'.$row_chelt['id_factura'].'" class="selectContentIncasare">
<option value="0">selectati ...</option>
</select>';
and the function for that select list (part of the same class as function TipCheltuiala):
public function ModInchidere(){
$stmt_mod_inch = $this->conn->prepare('SELECT * FROM mi_mod_inchidere WHERE categorie_cheltuiala = :categorie_cheltuiala');
$stmt_mod_inch->execute(array('categorie_cheltuiala' => $_POST['id_categ_cheltuiala']));
$mod_inchidere = '<option value="0">selectati ...</option>';
while($row_mod_inch = $stmt_mod_inch->fetch()) {
$mod_inchidere .= '<option value="' . $row_mod_inch['mod_inchidere'] . '">' . $row_mod_inch['mod_inchidere'] . '</option>';
}
return $mod_inchidere;
}
3. final step: according with the selected option in select list "mod_inchidere, I need to return a value (also stored in database) correlated with the options in select list "mod_inchidre", and put that values in a input field, so the user can (if he wants) modify that value.
At that step I have no idea how to accomplish that.
I can put the value in another select list, but: the user can't modify that value and is not the way to do it.
Please help me with that.
LE
table structures
mi_categ_cheltuiala -> | id | tip_cheltuiala | categorie_cheltuiala |
mi_mod_inchidere -> | id | categorie_cheltuiala | mod_inchidere |
cheltuieli_mod_inchidere (table where I need to insert the data) -> | id | tip_cheltuiala | categorie_cheltuiala | mod_inchidere | valoare |
to get the value that I need to put in the input field I need to interrogate the table "mi_categ_valoare" for the field "mod_inchidere"
mi_categ_valoare -> | id | mod_inchidere | valoare |
$_POST['id_categ_cheltuiala'] -> explanation:
through jQuery I fetch what is selected in this select list "tip_cheltuiala" and send the data to the method TipCheltuiala()
<script type="text/javascript">
$(document).ready(function(){
$("select#mod_inchidere<?php echo $row_chelt['id_factura']; ?>").attr("disabled","disabled");
$("select#tip_cheltuiala<?php echo $row_chelt['id_factura']; ?>").change(function(){
$("select#mod_inchidere<?php echo $row_chelt['id_factura']; ?>").attr("disabled","disabled");
$("select#mod_inchidere<?php echo $row_chelt['id_factura']; ?>").html("<option>asteptati ...</option>");
var id_categ_cheltuiala = $("select#tip_cheltuiala<?php echo $row_chelt['id_factura']; ?> option:selected").attr('value');
$.post("class/select_mod_inchidere.php", {id_categ_cheltuiala:id_categ_cheltuiala}, function(data){
$("select#mod_inchidere<?php echo $row_chelt['id_factura']; ?>").removeAttr("disabled");
$("select#mod_inchidere<?php echo $row_chelt['id_factura']; ?>").html(data);
});
});
</script>
and then I use a service file that will invoke the method TipCheltuiala()
To be honest: Non-English naming conventions making me dizzy :)
Issue: There I have the first issue: the select list is populated with option 2 (that is correct) but also with option 3 - I can't figure out why.
use below single query to get missing tip_cheltuila:
SELECT
tip_cheltuila
FROM
mi_categ_cheltuiala
WHERE
tip_cheltuila NOT IN (SELECT
tip_cheltuiala
FROM
cheltuieli_mod_inchidere);
Need to study other issues...
Say I have the two following tables:
country_table:
---------------------------------
|ID|country_code|country_name |
|01|CA |Canada |
|02|US |United States |
---------------------------------
user_table:
----------------------------------------------
|id|user_id|country_code|email_address |
|01|oswalsh|CA |blah#hotmail.com |
|02|jlong |US |blah2#hotmail.com |
----------------------------------------------
I am creating my user signup/edit account forms, and have a drop down for country. Originally I had simply stored the country_name in the user_table instead of using a country_code, however I have also decided to implement a map script...which is a massive mess of javascript files which make use of the country_code.
Thus I created the country_table so I could match the country_code and the country_name so I could map user interactions...However I am not sure how to go about creating the sql statement for the drop down.
What I have so far:
<?php
include ('../../connect.php');
$account_panel = mysql_query("SELECT * FROM user_table WHERE id=1")
or die(mysql_error());
while($row1 = mysql_fetch_array( $account_panel ))
{
?>
<select name="event_country" id="event_country" required />
<option selected="selected" value="<?php echo $row1['user_country']; ?>"><?php echo $row1['user_country']; ?></option>
<?php
$countries = mysql_query("SELECT * FROM country_table")
or die(mysql_error());
while($row = mysql_fetch_array( $countries ))
{
echo "<option value='". $row['value'] ."'>". $row['name'] ."</option>";
}
echo "</select>";
?>
<?php
}
mysql_close($connection);
?>
So as you should be able to see from above what is happening, is that the list is populated from the country_table, but I am trying to get the selected value from the user table. This does seem to work, but my problem is that the country code is what is stored and being displayed. So say I am grabbing the info for oswalsh...me...the country returned is CA, and I would like it to display Canada.
If I understood you right, you need to familiarize yourself with SQL Joins
To join those two tables and get the country_name along with the user data from the user_table, you'd need an SQL statement like this:
SELECT ut.*, ct.country_name
FROM user_table ut
INNER JOIN country_table ct
ON ut.country_code = ct.country_code
In your case, this would result in the following:
1 oswalsh CA blah#hotmail.com Canada
2 jlong US blah2#hotmail.com United States
Also, you should consider using mysqli_ and stop using mysql_ functions. Here is a discussion on this topic on SA.