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.
Related
I'm working on a PHP script to make a catalog. The relevant columns in my database are Vid, banner, category and Scategory. Vid is the primary key, banner is the path to my img files, and category and Scategory are both numbers for the their respective ID. Everything is over simplified as I'm just testing the scripts. There is currently 20 records in the table.
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<?php
require "config.php";
$sql = "SELECT Vid,banner,category,Scategory FROM display";
$result = $conn->query($sql);
$row = $result;
$min = 10;
$max = 20;
while ($row = mysqli_fetch_assoc($result)) {
implode ('', $row);
$vid = $row['Vid'];
$banner = $row['banner'];
$cid = $row['category'];
$sid = $row['Scategory'];
if ($cid = 2 && $sid = 1){
echo
'
<div style="display:inline-block;">
<div style="border-color:blue; border-style:solid;">
<a href="#test'.$vid.'">
<img src="'.$banner.'" />
</div>
</div>';
echo $vid;
echo $cid;
echo $sid;
if ($vid % 2 == 0){
echo '<br>';
}
}
}
require'close.php';
?>
</body>
</html>
Now the code runs just fine, but it gets strange I use $cid and $sid as conditions in that IF loop. Given there is 20 records, both $cid and $sid have half their values as '1' and half as '2, so when I set the IF conditions I figured it would return 5 records, but it instead returned all 20. When I echo $vid $cid and $sid, it returns the proper $vid, but $sid returns as whatever condition I set it to. For example conditions set to $cid=1 and $sid=2 returns 1:1:2, 2:1:2, 3:1:2 etc.
Now here is where it gets really strange, regardless of the condition set for $cid it returns as '1', if I set it '7' it still returns as '1'. Whereas $sid returns as whatever number is set. Also when I set either condition to null it returns nothing.
So my question is why it's acting the way it is or how it should be written if I'm writing it wrong.
Also as a side question, when I put <a> before <img> it returns the proper ID that's linked to the <img>. But when I put <a> directly after <img>, it returns the ID of the next iteration's row, and the first iteration returns blank. Anyone happen to know why that happens since regardless of their position in the statement it's still part of the same loop iteration?
You are using a single equal and assign the value to the variable. To compare values you have to use == or ===!
What is the difference between == and ===?
See the following condition to see the difference:
2 == "2" -> Equal
2 == 2 -> Equal
2 === "2" -> Not Equal
2 === 2 -> Equal
How you can avoid this on future? - Yoda condition
You can change your conditions to the following to make sure you are using the conditions on the right way. You only shoud use this for equal comparison not for >, <, <=, >=.
//throws an error
if (0 = $isNull) { ... }
//the right one
if (0 == $isNull) { ... }
== not = in your if statement.
implode line does nothing
Use double-equals instead of singles. Not:
if( $foo = 2 )
...but:
if( $foo == 2 )
Your code is changing the values instead of testing them.
Change if ($cid = 2 && $sid = 1) with if ($cid == 2 && $sid == 1). I think you did it only by mistake, since your other if is fine!
In your if statement you're using a single equals operator it needs to be == or ===
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.
I have tried to create a small 'bookmarking' feature for my website. Users are able to click on the ".bookmarkButton" which will execute the following script:
<!--Add To Bookmarks-->
$(".bookmarkButton").click(function() {
var pid=$(this).closest('div').attr('id');
$('#noBookmark').hide();
$.post('bookmarks/addBookmark.php', 'rid=' + pid, function (addBookmark) {
$("#bookmarkResults").add(addBookmark);
});
});
Here is the code for "addBookmark.php":
<?php
session_start();
if (isset($_SESSION['ridArray']) && count($_SESSION['ridArray'] > 0)){
addBookmark();
} else if (isset($_POST['rid']) && !isset($_SESSION['ridArray'])) {
$_SESSION['ridArray'] = array();
addBookmark();
}
function addBookmark() {
if (is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray']) && isset( $_POST['rid']) ) {
array_push($_SESSION['ridArray'], $_POST['rid']); //push the id value from post to the session array
//$_SESSION['ridArrayClean'] = array_unique($_SESSION['ridArray']); //remove duplicates
print_r($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example WHERE id = $x")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}}}
?>
The variable $_SESSION['ridArray'] holds the array with all the id's that have been accumulated.
My problem is that this script works only when one item is bookmarked. When there is more than one product bookmarked, I only get the product name that was last bookmarked and not every thing that I've bookmarked.
So for example instead of getting multiple product id's after clicking the bookmarkButton class like this: 0,1,2,3 in the array. I only get the one that was clicked last i.e. 6.
I've been looking into this for a while now and I can't seem to see what I'm doing wrong.
The script only echos the productnames, if you posted a "rid".
Also you could write the if like this:
if (isset($_SESSION['ridArray'], $_POST['rid']) && is_array($_SESSION['ridArray'])) {
Checking isset() first. Also you could additionally check for
... && count($_SESSION['ridArray'] > 0)
I do not think that your session starts automatically (is it possible to set its autostart in php.ini, but it does not by default), so
<?php
session_start();
Other thoughts:
SELECT * FROM example WHERE id = $x
Have you ever heard about SQL Injection?
ps: no need in secondary check (they are checked before) and from the first condition follows the second one
is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray'])
I would write it as
<?php
session_start();
if (isset($_POST['rid'])) {
addBookmark(intval($_POST['rid']));
}
function addBookmark($rid) {
$_SESSION['ridArray'][] = $rid;
$_SESSION['ridArray'] = array_unique($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
$result = mysql_query("SELECT * FROM example WHERE id = '$x'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}
}
?>
I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.
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.';
?>