Hi guys I was wondering if they is a way to cross check select options getting posted to a different page with a database just to make sure that someone hasn't change anything using a inspect element or firebug or any developer tool.
database table product
my database looks something like this but they are over 400 data in it.
pid name size
1 grey 12 inch
2 blue 16 inch
database table category
pid category
1 vans
2 nike
database table itemised
pid price
1 30.00
2 50.00
item.php
in my item.php page I have a table. The size and category and SELECT OPTION then I have an input field for amount which uses jquery for validation.
in my cartpage.php
I Posting the pid, size and category then I am using all those to find the price(I AM NOT POSTING THE PRICE, I AM USING THE pid, size and category to find it.)
Now the problem is, if someone was to change the value for the size or category or both. They will still get posted but obviously the price wouldn't be find because the database can't find those value getting posted.
How I show my value category example *similar to how i show size too apart from I change the select statement*
<select id="Category" name="Category">
<?php
dbconnect();
$stmt = $conn->prepare("SELECT Name FROM Category WHERE pid=:id");
$stmt->bindParam('id',$id);
$stmt->execute();
$i = 0;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row ) {
if ($i == 0) {
echo '<option SELECTED value="'.$row['Name'].'">'.$row['Name'].'</option>
';
}
else {
echo '<option value="'.$row['Name'].'">'.$row['Name'].'</option>';
}
$i++;
}
?>
</select>
My question
Is they a way to find out that what is getting posted exist in the database and it is related to the pid? and if not that item shouldn't be added.
Edited to add how my cart page looks like Jim Martens I have added the code you show in your answer
//I have session start on top of this page.
<?php
*jim matens your code starts here*
if (isset($_GET['pid'])){
$id = $_GET['ProdID'];
$categoryID = (isset($_POST['Category']) ? intval($_POST['Category']) : 0);
dbconnect();
$stmt1 = $conn->prepare("SELECT CatID FROM Category WHERE pid=:id");
$stmt1->bindParam('id',$id);
$stmt1->execute();
$isValid = false;
$rows2 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows2 as $row1) {
if ($row1['CatID'] == $categoryID) {
$isValid = true;
break;
}
}
}
*My code starts here*
if(isset($_POST['pid']) && isset($_POST['length']) && isset($_POST['Qty']) && isset($_POST['Category'])){
$pid = $_POST['pid'];
$length = $_POST["length"];
$qty = $_POST['Qty'];
$Category = $_POST['Category'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["cart_array"]as $array_key=>$each_item) {
if ($each_item['item_id'] == $pid && $each_item['length'] == $length && $each_item['Category'] == $Category) {
$_SESSION["cart_array"][$array_key]['quantity']+=$qty;
$wasFound = true;
} // close if condition
} // close while loop
// close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
}
}
header('Location: '.fetchinline($bpages).$currentFile);
exit();
}
?>
I hope I have explain this clearly and if not please leave a comment and I will try and rephrase the question.
Thanks
JavaScript validation is a nice gimmick for spelling issues and the like. But it is neither foolproof nor able to actually verify if the data is semantically correct. Therefore you need to send the data to the PHP script.
That script now verifies it first for integrity (correct value type and the like). After this initial step you verify against the database in your case. If I understand you correctly, you want to make sure that the sent category is an existing category. There is one very simple way to achieve that.
First your form.
<select id="Category" name="Category">
<?php
dbconnect();
// select the ID of the category as well (should be there anyway)
$stmt = $conn->prepare("SELECT ID, Name FROM Category WHERE pid=:id");
$stmt->bindParam('id',$id);
$stmt->execute();
$i = 0;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
if ($i == 0) { ?>
<option selected="selected" value="<?php echo $row['ID']; ?>"><?php echo $row['Name']; ?></option>
<?php } else { ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Name']; ?></option>
<?php
}
$i++;
}
?>
</select>
For the actual processing of the input, you read all categoryIDs from database and check if the selected ID (should be made to integer by now) is among them. If yes, everything's fine, if not the user has given invalid input.
A quick example for that:
$categoryID = (isset($_POST['Category']) ? intval($_POST['Category']) : 0);
dbconnect();
$stmt = $conn->prepare("SELECT ID FROM Category WHERE pid=:id");
$stmt->bindParam('id',$id);
$stmt->execute();
$isValid = false;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
if ($row['ID'] == $categoryID) {
$isValid = true;
break;
}
}
ID stands here for the category ID (whatever that is in your case).
Of course your real code would continue before and after this, but it should give you the general direction.
Related
I got a DB query that pulls out three items randomly from several categories. I want to show "Selected" if one of the items is from a specific category. Right now if one of the items is from that specific category the "Selected" is showing on all three items. How can I target the specific item only?
foreach ( $rows as $row ) {
if ($row->catid == 56) {
echo "Selected";
}
Your question isn't very clear, but I suspect you're trying to add the attribute to an option. You need to do this in the same loop that echoes the option.
foreach ($rows as $index => $row) {
$selected = $row->catid == 56 ? "SELECTED" : "";
$itemnum = $index + 1;
echo "Item $itemnum - Category $row->catid $selected | ";
}
foreach ( $rows as $row ) {
if ($row->catid == 56) {
echo "Selected";
break;
}
Not sure what u want accomplish but i guess u want to show only one selected so u need to break loop if item is found
I have some file names stored in my table with a category_id for each image.
I have the gallery all on one page.
So my question is, if my category_id's value is 3 then I want it to show the image.
If the category_id is not 3 I want to display a message saying, "no content", or whatever.
Here is my code. Not sure where I went wrong. Hoping someone can give me a hand.
<?php
$newlogos = DB::getInstance()->query("SELECT `logo_id`, `creation`, `logo_name`, `category_id`, `org_img`, `new_img` FROM `logos` WHERE category_id = 3 ORDER BY `logo_id` DESC ");
$category_id = ('category_id' == 3);
if($category_id == false){ ?>
<div><h2>No Content</h2></div>
<?php }
if($category_id == true){
foreach($newlogos->results() as $nl){ ?>
//Do Stuff
I've tried a bunch of combinations like this for example:
$category_id = ('category_id' == 3);
if($category_id != 3){ ?>
<div><h2>No Content</h2></div>
<?php }
else{
//Do Stuff
Just can't seem to figure it out.
Your statement here is not correct:
<?php
$category_id = ('category_id' == 3);
?>
You are trying to compare a string with an integer and this always returns false.
Edit:
After you execute your query, you need to fetch the data from the database. After you have stored the data in a variable (e.g. $data), you can compare it like this:
<?php
$category_id = ((int)$data['category_id'] == 3);
?>
Edit: #cwd:
Here is one way to do it:
<?php
//$con is database connection object
$result = mysqli_query($con,"SELECT `logo_id`, `creation`, `logo_name`, `category_id`, `org_img`, `new_img` FROM `logos` WHERE category_id = 3 ORDER BY `logo_id` DESC LIMIT 0,1");
$row = mysqli_fetch_assoc($result);
$category_id = (int)$row['category_id'] == 3 ?true:false;
?>
This might help you.
I have a table teamtrack_activity that holds id and activity_name.
I have table teamtrack_entry that holds all team daily entries. This table has a field "activity_id" that I want to store the teamtrack_activity id. I have this part working.
However I am having 2 issues:
Displaying activity_name instead of id. When I try to do this then activity_name gets passed and this of course doesn't work.
When I go back to edit the entry it does not show the value in the database. It just shows the select box anew.
if ($key == "activity_id")
{
$query="SELECT id, activity_name FROM teamtrack_activity Order By id";
$res = sql_query($query);
if ($res === FALSE)
{
trigger_error(sql_error(), E_USER_WARNING);
fatal_error(FALSE, get_vocab("fatal_db_error"));
}
$select_options["entry.$key"] = array();
for ($i = 0; ($row = sql_row_keyed($res, $i)); $i++)
{
$select_options["entry.$key"][$row['id']] = $row['id'];
}
}
Change:
$select_options["entry.$key"][$row['id']] = $row['id'];
into
$select_options["entry.$key"][$row['id']] = $row['activity_name'];
to get a dropdown with the activity ame, which submit the activity ID for your script.
Based on your comment;
It might be the parsing of your $select_options.
In a foreach loop you would want to
foreach($select_options["entry.$key"]) as $key => $label)
{
echo "<option value=".$key.">".$label."</option>";
}
This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>
I am working on a simple order system.
the peice of code I am stuck on is the following:
if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
foreach ($items as $product)
{
if ($product['id'] == $id)
{
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}
This is the code is build on a preset array. I am working with a table with a few columns in mysql.
I have decided on the following:
if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
while($row = mysql_fetch_assoc($productsSql)) {
foreach ($row as $product)
{
if ($product['id'] == $id)
{
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}}
To display this "cart" I have decided on this:
foreach ($cart as $item) {
$pageContent .= '
<tr>
<td>'.$item['desc'].'</td>
<td>
R'.number_format($item['price'], 2).'
</td>
</tr>
';
}
All this seems to do is produce my cart in a fashion where when viewed it displays a list of only the items' id, e.g. where the description and price are supposed to be, I only get the items id in both fields... I also get a total price of 0.
Can anyone spot where I am going wrong here?
Or atleast try to give me some input so that I get going in the right direction!
Thanks!!
$productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
$productsSql = mysql_query($productsQuery) or die(mysql_error());
if (mysql_num_rows($productsSql) == 0) {
die('No results.');
} else {
$orderContent = '';
while($row = mysql_fetch_assoc($productsSql)) {
$prId = $row['id'];
$prRefCode = $row['refCode'];
$prDesc = $row['desc'];
$prPack = $row['pack'];
$prMeasure = $row['measure'];
$prQuantity = $row['quantity'];
$prDeptCode = $row['deptCode'];
$prTaxable = $row['taxable'];
$prPrice1 = $row['price1'];
$prPrice2 = $row['price2'];
$prCrdCode = $row['crdCode'];
$prCost1 = $row['cost1'];
$prCost2 = $row['cost2'];
$orderContent .= '
<tr>
<td>'.$prId.'</td>
<td>'.$prDesc.'</td>
<td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
<td>R'.$prPrice1.'</td>
<td>
<form action="" method="post">
<div>
<input type="text" size="3" name="quantity" />
</div>
</form>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="id" value="'.$prId.'" />
<input type="submit" name="action" value="Order" />
</div>
</form>
</td>
</tr>
';
}}
Let's say that each of the rows in your database looks like this...
[product_id][product_name][product_description][product_price]
When you assign your query return to a variable passed through mysql_fetch_assoc() using a while loop, each pass will isolate a whole row. Of which you can piece apart manually by array key reference ($array['product_id']) or by using a foreach loop. I think the problem you're having is that you are mixing this up. Keeping the above example table layout in mind, you could do something like the following:
while ($tableRow = mysql_fetch_assoc($query)) { // Loops 3 times if there are 3 returned rows... etc
foreach ($tableRow as $key => $value) { // Loops 4 times because there are 4 columns
echo $value;
echo $tableRow[$key]; // Same output as previous line
}
echo $tableRow['product_id']; // Echos 3 times each row's product_id value
}
Look at this line in your code: if ($product['id'] == $id) { }
I think you probably mean if ($row['id'] == $id) { } instead.
Your middle code block makes no sense. You loop over session variables, and run a query each time... but it's the SAME query, and using an undefined variable to boot. Looping over a result row doesn't make much sense, as you'd be looping over the individual fields that your query returns for each row.
e.g. If your products table has just (id, name, description) as fields, then $row would be an array that looks like:
$row = array('id' => xxx, 'name' => yyy, 'description' => zzz);
When you foreach() on $row(), you'd not getting individual products, you'd be getting those fields in the row. $product would be xxx, then yyy, then zzz.
I don't know what your code is trying to accomplish - I'd guess you're trying to retrieve prices for products that a user is adding into their cart, but you're going about it in a very strange and highly inefficient manner.