Retrieve data from database based on radio button value - php

I'm quite new to php and mysql so forgive me if I'm doing this completely wrong. I am making a printing balance application and the code below is a part of it.
$command="SELECT itemname FROM items";
$results = mysql_query($command);
while($row = mysql_fetch_assoc($results))
{
foreach ($row as $key => $value) {
print "<input type='radio' name='itemtype' value='$value'>".$value."</input><br />";
}
}
This here is supposedly the price printing form where the user chooses between SHORT BOND PAPER and LONG BOND PAPER (the column itemname from items). The options appear as radio buttons. It works but now I'm stuck with the issue of being able to fetch the price as inserted in their respective rows. Since the itemname and their price are all user-inputted into the database, I'm not supposed to declare their specific price into the code itself, and should be able to retrieve it from the database. I want to be able to get the prices based on the item chosen by the user once they click submit, because I'd need to do this to compute for the price of printing when multiplied with the number of pages later.
I think it's definitely possible but I'm not quite sure how. Theoretically, it would be along the lines of SELECT itemprice FROM items WHERE itemname = $value but ha, I don't think it works that way.
solution edit: here's the complete solution for reference. $compute is just a sample to test if it works while 5 is a sample number of pages that would be entered.
if ($command = mysql_query("SELECT `itemprice` FROM `items` WHERE `itemname` LIKE '" . mysql_escape_string($_POST['itemtype']) . "'"))
{
while($row = mysql_fetch_assoc($command))
{
$compute = $row['itemprice'] * 5;
echo $compute;
}
}
else
{
echo (mysql_error ());
}

It would be something like that indeed.
SELECT itemprice FROM items WHERE itemname = $_POST['itemtype']
assuming that itemprice is the actuial colum of the price. HOwever, doing it like this, makes your code vulnerable to mysql injections. So before you contine, consider reading up a little.

Related

My cart items aren't printing in the same order in which they're placed

My code isn't printing the products in the order I placed them into the cart session. The product ids are as follow:
Apples value of 2
Blackberries value of 3
Green grapes value of 6
As you can see in the printed array, the order in which I placed them into the cart session is Grapes, Blackberries and then Apples but for some reason it's printing in the order of their given values rather than their cart order.
The code still treats each of the products as if they're in the correct place however. For example, Apples are suppose to be the third item in the cart array where the grapes currently are. If the quantity button of the grapes is changed, the quantity of Apples would be changed instead because it's still reading the array correctly.
I suspect the problems lie in one of the loops but I just can't seem to find what it is.
<?php
$total = 0;
$id_count = 0;
if(isset($_SESSION['cart']) and count($_SESSION['cart']) > 0){
$product_ID = array_column($_SESSION['cart'],"product_ID");
$result = $database->getData();
while($row = mysqli_fetch_assoc($result)){
foreach($product_ID as $id){
if($row['id']==$id){
print_r($product_ID);
print_r($row['product_name:']);
echo " value: $id";
$itemQuantity = $_SESSION['cart'][$id_count]['quantity'];
cartMethod($row['product_name'],$row['product_img'],$row['product_price'], $row['id'], $itemQuantity);
$total = $total + ($itemQuantity*(float)$row['product_price']);
$id_count++;
}
}
}
}
else{
echo "<h5>Cart is currently empty</h5>";
}
?>
This is the getData() function located in a different file.
//get method to retrieve database information
public function getData(){
$sql = "SELECT * FROM $this->tablename";
$result = mysqli_query($this->connection, $sql);
if(mysqli_num_rows($result)>0){
return $result;
}
}
You're iterating over the product catalog from the database ($database->getData()), and then for each entry in there crosschecking if it exists in $product_ID.
So the effective order follows that of the query (which is probably ORDER BY id or something i suspect (i can't tell; the code isnt included).
It's not hard to fix but you are building the cart in a very inefficient method here. It would make a lot more sense to do the bulk of data collation (which is what most of this page is), inside the database.
Of course, i don't know what the product catalog looks like in the database, and i don't know what query hides behind $database->getData(), so i cannot really give more targetted advice.
If i had to guess, i'd suspect that $database->getData() contains a query such as SELECT * FROM products ORDER BY productid ASC. If that is indeed the case then i would extend that query so you can feed the $_SESSION['cart'] data into the SELECT query, and join that against the products table.
That way:
A) you have full control over the ordering
B) you only have to return the relevant products and not "all" products, muchhh more efficient.
C) you dont have to mix&match the 2 datasets in PHP

Getting value from multiple drop down menus in PHP

Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.

Using a set of Mysql results as a comparison in PHP

This question is quite simple but I'm not sure of the terms involved to look up the answer myself. What I have is a MYSQL database containing all of my product information. I would like to make an image appear on the product pages for products that have a certain attribute. I have created this SQL query which outputs the list of product_ids for the products that I would like the image to show up on. However, I do not know how to use this set of results in the page itself.
I currently have:
$cupwinnerids = mysql_query("SELECT product_id FROM `jos_vm_product_type_1` WHERE jos_vm_product_type_1.Cup_Winner ='Cup Winners';");
while($row = mysql_fetch_array($cupwinnerids))
{
echo $row['product_id'] . ",";
}
This outputs the correct ids with a comma in between them. What I would like to do is wrap the whole thing with something like $listofids = (...) and then I can use in the product page PHP file: if $product_id is in $listofids then ... if not then ... I am just having a problem understanding how to use this selection of ids. If I try to output the list directly I just get "array". Any help would be greatly appreciated.
The problem may be that you are trying to display the array using echo, while you should use print_r.
In your case you could do something like this:
$listofids = array();
$cupwinnerids = mysql_query("SELECT product_id FROM `jos_vm_product_type_1` WHERE jos_vm_product_type_1.Cup_Winner ='Cup Winners';");
while($row = mysql_fetch_array($cupwinnerids))
{
array_push($listofids, $row['product_id']);
}
print_r($listofids);
As Ryan commented, if you want to manage the values of the array you should then use a foreach loop, that iterates through the array, something like this
foreach ($listofids as $id) {
echo $id . ", ";
}
// EDIT: you could also use echo implode($listofids,", ") which will do basically the same
If what you want is to compare if $product_id is in $listofids us in_array, that returns true if the value you are looking for is in the array, and false if it isn't:
if (in_array($product_id, $listofids)) {
echo "Product ID is in the List of Product ID's";
}
else {
echo "Product ID isn't in the List of Product ID's";
}
Why not return $cupwinnerids to your products page, and then do something like...
while($row = mysql_fetch_array($cupwinnerids)) {
if ($row['product_id'] == $product_id)
// display your image
}
It sounds like you would be better off modifying your query for returning the products so that it joins to the jos_vm_product_type_1 table -
SELECT `jos_vm_product`.*, IF(`jos_vm_product_type_1`.`product_id` IS NULL, 0, 1) AS `winner`
FROM `jos_vm_product`
LEFT JOIN `jos_vm_product_type_1`
ON `jos_vm_product`.`product_id` = `jos_vm_product_type_1`.`product_id`
AND `jos_vm_product_type_1`.`Cup_Winner` ='Cup Winners'

Renaming and Inserting Array results into a different table

//First I'm assigning a $variable ($emailzipmatch) to query a database table called(repzipcodes) and having it pull and display 1 to 3 records based on matching up a customer's zip code (RepZipCode = $CustomerZipMatch) with 1 to 3 other people (GROUP BY RepId HAVING COUNT(1) <= 3") that want that customer's information from that particular zip code.
// CODE WORKS BELOW
$emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error());
$recipients = array();
while($row = mysql_fetch_array($emailzipmatch))
{
$recipients[] = $row['RepEmail'];
echo "Agent's Email Address: ";
echo 'font color="#FF7600"',$row['RepEmail'], '/font';
echo '<br />';
echo "Rep's ID: ";
echo '<br />';
echo 'font color="#FF7600"',$row['RepId'], '/font';
echo '<br />';
echo 'hr align="left" width="50%" size="2" /';
}
//MY PROBLEM BELOW
// For the NEXT step of the process above I would take $row['RepEmail'] and $row['RepId'] which can have 1 to 3 results and assign the 1 to 3 results a new $variable so it can be inserted into a different db table so I can track the results of the query ($emailzipmatch = ) from the top of the page: ie..
<New Variable> <Listed from above>
$SentRepId 0 = RepId (results from above echo area)
$SentRepId 1 = RepId (results from above echo area)
$SentRepId 2 = RepId (results from above echo area)
// Below I'd like to insert the above results into a new database
$?Variable??? = mysql_query("INSERT INTO sentemail
(SentRepId0, SentRepId1, SentRepId2,SentDateTime
) VALUES (
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
NOW()
)") or die(mysql_error());
//Thank ahead of time for any help you guys can give me. Please respond with ANY question if my coding or request isn't clear or if I've been confusing due to my lack of experience with PHP and MySQL.
I think I know what you are going for here. I have done something similar before where I needed to keep a record for a while so I gave each search result an id on output and placed them in separate rows of a table along with a time stamp so it could be cleaned up at a later time or if you wish to search by time (mysql has a timestamp of it's own also but that's another thing to look in to if you haven't already)
So to make a 'log table' for example you might want to design something that works like the following:
<?php
$search_id = md5(uniqid()).rand(100,999); //// MAKE AN ID FOR THE SEARCH;
$timestamp = time(); // IN CASE YOU WANT TO CLEAN UP AT A LATER DATE, MUST BE AN INTEGER IN MYSQL (so you can use a less than $timestamp in the delete query)
$emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error()); // if you are just wanting to limit the results look at LIMIT in a mysql tutorial somewhere.
$recipients = array();
while($row = mysql_fetch_array($emailzipmatch))
{
//// THE REST OF YOUR CODE HERE (and at the end of the while loop insert in to a table, in your case 'sentemail')
mysql_query("INSERT INTO sentemail (search_id, rep_email, rep_id, zip_code, timestamp) VALUES ('$search_id', '{$row['RepEmail']}', '{$row['RepId']}', $CustomerZipMatch, $timestamp);") or die(mysql_error()); // or what ever details you are after
}
?>
This should leave you with a reference table that you can search for by different criteria. Not the most perfect way of doing it but it will get the job done.
Hope that gives you a different perspective on it :)
In regards to "due to my lack of experience with PHP": As you develop your skills, and you will I'm sure, take some time to look at Object Oriented PHP in the future. For more server heavy or complicated things it can be worth knowing. I'm saying this to you now because I wish someone had told me earlier.
Good luck.
As long as you have user access, you can do:
$?Variable??? = mysql_query("INSERT INTO db1.sentemail (SentRepId0, SentRepId1,SentRepId2,SentDateTime) VALUES (
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', NOW())") or die(mysql_error());

Possibly simple PHP/MYSQL issue with retrieving and showing data

I have been racking my brains over this for a while now. Here is the data I have in the SQL data base as an example:
ID | TYPE | DATA
1 | TXT | TEST
2 | PHP | php
3 | JS | JAVASCRIPT
That is just an example, there are multiple listing for TXT, PHP and JS throughout the table. What I want to do is retrive all the data and display it all into separate drop down/select boxes. Meaning, select box one would list all data with type TXT, select box two would list all data with type PHP and select box 3 would list all data with type JS. The only way I have came about doing this is doing individual sql queries for each different type. I know there is a way to do it all in 1 query and then display it the way I want to but I just can't seem to figure out how and I know its going to drive me nuts when someone helps and I see just how they did it.
The only way that I know of to get all of the data in one query is just to do a generic SELECT * FROM tbl, and then you can group them in the code:
$res = mysqli_query('SELECT * FROM tbl');
$data = array();
while($row = mysql_fetch_assoc($res)) {
$type = $row['type'];
$data[$type][] = $row;
}
// $data contains all of the record, grouped by the TYPE column
foreach($data as $type => $records) {
echo "records for $type: <select>";
foreach($records as $record) {
echo "<option value='$id'>$id</option>";
}
echo "</select>";
}
Just retrieve all records and loop through them using PHP. Use an iterator if the recordset is going to be huge to prevent using too much memory.
$lists = array();
foreach($recordset as $record) {
$lists[$record['type']][$record['id']] = $record['data'];
}
Know you have an array containing all data.
Just order it by Type and make a loop using "foreach" into the results, changing of select box when the type is different than the preivous.
In this way you only loop once over the array.
You can do kind of grouping with "ORDER BY TYPE":
SELECT id, data
FROM table
ORDER BY type;
Then, in data output loop you can track current type, and build another select box once type changed:
$currentType = "no type";
while($row = mysql_fetch_assoc($res)) {
if ($currentType != $row['type']) {
$currentType = $row['type'];
// start new select box here
}
// do some other work here
}
BTW, such approach looks like kind of hack :)

Categories