if statement bug in php and html - php

<img id="post_like_btn_<?php echo $post_info['id']; ?>" class="post_like_btn"
<?php $like_result = data_like($dbc, $user_info['id']);
while($like_info = mysqli_fetch_assoc($like_result)){
if($post_info['id'] == $like_info['post_id'])
{ echo 'src="img/like/like_active.png"';
} else{echo 'src="img/like/like_dark.png"'}?>>
I have this code to change the icon image on the like button when the post id exists in likes table but when there are no values in the table, else statement does not work and shows no image. I tried to add '&& !== null' to if condition but it does not work either.

If there's no data in the likes tables for the user, the while loop has nothing to iterate over. That means the if condition never actually gets executed.
It's also worth noting another issue: It looks like your while loop will iterate over all results for all posts. If your user has liked other posts (besides the one being displayed) then your else clause will be executed multiple times, giving you multiple src attributes in your img tag (most or all of them referring to like_dark.png).
Ideally, what you need to do is make your database query search only for the user's likes on the ID of the post being displayed. That way you won't need a while loop at all. You just need to check if any result was found. If so, output like_active.png, otherwise output like_dark.png.
If you're not able to modify the query for some reason (or if you want to avoid multiple queries when displaying several posts on a page), your loop will need to go through each record and just set a boolean variable to true if it sees a like matching the current post ID. After the while loop, check that boolean variable in an if condition and only output the src attribute then. That way, you'll only output one src attribute, no matter how many records you've iterated over.

missing closing bracket on the while loop:
while($like_info = mysqli_fetch_assoc($like_result)){
if($post_info['id'] == $like_info['post_id'])
{ echo ' src="img/like/like_active.png"';}
else{echo ' src="img/like/like_dark.png"';}
}?>>
also since the following is common:
src="img/like/like"
you could remove that out of the if statement and just switch between the active and dark.png states.

Related

Prevent end user manipulating URL to change content on website, method GET PHP

I have a personal search site project I'm building, at the moment the only data that is being displayed on the website is data that is retrieved using SELECT queries and the GET method using the super global $_GET['example']. Now I don't know if I'm doing this wrong but some parts of my page are only displayed if certain GET variables in the URL are set or not empty. Below shows how my URL looks
EXAMPLE: index.php?search_category=guitar&main_category=9&postcode_val1=NP22&distance_default=100&submit=search
I have a lot of these if(isset($_GET['search_category']) type conditions in my website which are replied upon and show particular parts of content depending whether or not these are either true or false.
I have been on a lot of other websites that have similar URL's, I have tried to alter and manipulate these and the content does not break, alter or change in any way yet when i try this with my url it breaks my page and only certain parts of content gets displayed by being based on what is set. Is there some other layer of protection I should add, would using something like a rewrite rule help? The code below shows how I have wrote a drop down box based on what has been set In the URL but if a user edits the URL this is easily broken.
if(isset($_GET['search_category']) && isset($_GET['main_category']) &&
isset($_GET['postcode_val1']) && isset($_GET['distance_default']))
{
$stmt = $getFromUi->dispCategories();
echo "<option value='0'>All</option>";
echo "<option value='#'>-------------</option>";
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$selected = '';
if(!empty($_GET['main_category']) && $_GET['main_category'] == $row->cat_id)
{
$selected = ' selected="selected"';
}
echo '<option value="'.htmlentities($row->cat_id).'"'.$selected.'>'.htmlentities($row->cat_title).'</option>';
}
}
It will break because the strict nature of logic you use on your code. The && mark with isset mean any parameter you define not set will not evaluate to true. If the parameter is quite flexible why not ||.
If you need it to still evaluate all parameter try to do limit first if condition to main determiner. like $_GET['search_category'] and use the remaining $_GET['other_parameter'] as needed inside the block code of main if.
You would need to use a post method, so that this goes through as a request instead. In my experiance, get will only fetch the url you open - not actually pass anything through unless its in the URL.
Not sure if that made any sense, but check post out.
https://www.w3schools.com/tags/ref_httpmethods.asp is a good place to start to see the difference of get vs post.

Assign html value to a variable in php

I ran into an issue that I am not able to figure out. I have a page that I want to add an image of "Verified" or "Unverified". The code I have is the following:
PHP
if($listing['priority']==0 {
$header->set('ver_status,'<img src="images/icon_unverified.png"/>');
} else {
$header->set('ver_status,'<img src="images/icon_verified.png"/>');
}
HTML
<?php echo $ver_status; ?>
For some reason when I run the page in my website, that variable comes up empty.
The database contains a listing table, and the table contains a priority field which the default value is 0. Unless a customer updates information, which automatically changes to priority field value to 1, all profiles state "unverified"
The $header is the variable assigned to the template
All priority codes at 0 should show the unverified image. All others 1-5 shold show the veriried image.
I did this in a different page and it worked fine. That code was:
if (config['language'] == 2) {
$header->set('language_flag','<img src="images/flags/Spanish.png" />');
} else {
$header->set('language_flag','<img src="images/flags/English.png" />');
}
where code 2 was Spanish and code 1 was English.
Is there something missing in my code that I am not seeing? I am not getting any error messages, just empty values.
You appear to be missing a close paren in your if statement. If that's copied and pasted directly out of your code, that could be causing issues - it should also be causing error messages, but you may have those turned off.
If it's just a typo from copying your code into SO, of course, this is unhelpful.
The variable comes up empty because there isn't one. If you want to retrieve an image through echoing a variable's value, simply type
if($listing['priority']===0){
$ver_status='<img src="images/icon_unverified.png">';
}else{
$ver_status='<img src="images/icon_verified.png">';
}
What you're doing in your code is setting an object's key, but when you're trying to get that same key, you're not referencing it correctly. echo $header->ver_status is how you should retrieve the value if you don't want to use a normal variable. I suggest reading http://php.net/manual/en/language.types.object.php
To note, you have a typo in your code as well. t('ver_status,' is an open string.
Also to note, there is no need for a slash in an tag unless you're using XML.

How do I use a while loop with counter for echoing else statement?

I'm not a full time PHP programmer by any means, but wondering what the most efficient way to do this would be? I am running a fetch to grab some data that I want to display on a page. The query results usually have multiple rows.
The following below works great, except for the last else statement for showing none. This part doesn't work. Basically I want to display my rows of data and if nothing exists, throw out a message saying "none."
I did some reading around and it looks like with a while loop + multiple result sets you can't simply just use the standard else... both with !empty or isset.
Someone mentioned doing a counter? Would this be the best way to accomplish this. Open to any suggestions as I will probably be adding more data like this in the future and would like to do it in the correct fashion.
Thanks!
while($myvariable = oci_fetch_assoc($stmt))
{
if(!empty($myvariable))
{
echo "<tr><th>DISPLAY FIELD NAME:</th><td>" . $myvariable['myrowdata'] . </td></tr>";
}
else
{
echo "<tr><th>DISPLAY FIELD NAME:</th><td>None</td></tr>";
}
}
Look at oci_fetch_assoc on php manual. This function is typically called in a loop until it returns FALSE, indicating no more rows exist. So you dont need any other if or else inside your while loop.
Do the check before the loop by fetching the first row and checking if it's not FALSE; then, if it's not, feed it to the loop and fetch the next row at the END of the loop. This is called "priming the loop" and isn't uncommon.
if(!($myvariable = oci_fetch_assoc($stmt))) {
echo "<tr><th>DISPLAY FIELD NAME:</th><td>None</td></tr>";
} else {
while($myvariable) {
echo "<tr><th>DISPLAY FIELD NAME:</th><td>" . $myvariable['myrowdata'] . </td></tr>";
$myvariable = oci_fetch_assoc($stmt));
}
}
I think this reference would help you about using function oci_fetch_assoc:
http://php.net/manual/en/function.oci-fetch-assoc.php#100304
Your while statement will run only if you get something in your "$myvariable", therefore your if statement is redundant and your else is irrelevant in this case. If you want to run something along the lines of what you're thinking, you can do "oci_fetch_all()" and then loop through and do your if/else.

how would I return any items in an array that do not match any $_POST results

I am writing a PHP/MySQL application that maintains a masterlist of user preferences and I've gotten myself stuck trying to remove items from that list. Currently the application generates a list of items and marks a checkbox next to the ones a user has previously selected, the user can then change their selections (either adding or removing checkmarks) and resubmit. The form only submits supplyid's for items the user has checked.
I have the list sorted so that unmarked selections are shown first and I've got the code to insert/update items in the database working, but I'm having problems figuring out how to delete the items the user has unchecked (and which now do not return supplyid's).
At this point, I've written a MySQL query to return only results that were previously included on the list (as those are the only ones which could need to be removed.) What I need are the items in the array returned by the query that do not match any $_POST results. I've been successfully comparing the array to the $_POST results of items previously included, but I can see my logic is wrong in the part where I'm trying to get back the results which don't match. While I'm able to view which items match, I'm not sure how to eliminate them as possibilities. Am I going about this in the wrong way entirely?
$iduser = $_SESSION["iduser"];
$possibleresults = $_POST["possibleresults"];
$sql_onlist = "select supply.idsupply from supply, kit
where supply.class = 'basic'
and kit.iduser = '".$iduser."'
and supply.idsupply = kit.idsupply";
$possible_delete = $connection->query($sql_onlist);
//for each record we know is already in the database, check to make sure it has been checked, otherwise delete
for ($i=0; $i<$possibleresults; $i++) {
$count = 0;
$item_delete = $possible_delete->fetch_assoc();
if ($_POST['item_'.$i.'']) {
$idsupply = $connection->real_escape_string($_POST['item_'.$i.'']);
//if there is a match, increase the counter
if ($idsupply == $item_delete["idsupply"]) {
$count++;
//this does successfully return a count = 1 - idsupply = number for all rows which should have matches
echo "count = ". $count . " - idsupply = " . $idsupply;
}
//this statement doesn't work because it doesn't know which idsupply
if ($count < 1) {
$idsupply = $item_delete["idsupply"];
$sql_delete = "delete from kit
where idsupply = '".$idsupply."'
and iduser = '".$iduser."'";
$result_delete = $connection->query($sql_delete);
}
}
There are a couple different solutions to this problem; here's a few strategies I've used before.
-- Delete all the entries every time you update a user's preferences
Not terribly efficient, but it's easy to implement. Every time they save their preferences, first set all the values in the database to whatever the 'unchecked' value is. Then, save their preferences as normal.
-- Give unchecked boxes a value
If you put a hidden input element right before a checkbox and give it the same name as the checkbox, the hidden element will submit its value whenever the checkbox is not checked. E.g.,
<input type='hidden' name='box1' value='off' />
<input type='checkbox' name='box1' value='on' />
This will let you know which IDs to unset in the database.
There may be a more database-oriented solution as well, but I'd have to know more about your structure to suggest anything.
Holy moly, what a tangled mess... kinda painted yourself into a corner eh? No worries it happens to all of us. :)
So I think that once you have a truly working algorithm the code just kinda comes together around it. So lets analyze your problem:
Your main objective is to store a users settings.
You are using a form and checkboxes to both display the current settings and to allow the user to change their current settings. This is graceful enough.
Generate a list of the users POSTed settings (aka get the new settings from the POST array) and store those results in a dedicated data container like an array or a linked list.
Once you have a list of new settings, you need to use that list as a map to set/unset various fields within a database table.
Get a list of ALL of the users saved settings from the database storing that in a different data container
Do a case by case comparison, seeing if the variables match, record the results in yet another data container, or do an immediate write to the database.
Present the user with a human readable result of their operation.
NOTE: Incidentally, you probably already know this, but if you use isset($_POST['mychkbox1']) and it returns a positive value, then that checkbox was checked. If isset() returns false, the checkbox was not set, or does not exist. Like I said you probably already knew that, but I figured I toss it in there.
Good luck
h
I didn't quite understand your code, but I think you need something like this
$to_keep = array();
for ( $i=1 ; $i < 10 ; $i++ ) {
// Add ids of elements we want to save
$to_keep[] = $i;
}
if ($to_keep) {
mysql_query("DELETE FROM table WHERE id NOT IN (". implode(',', $to_delete) . ")");
}

PHP IF statement not taking variable into account!

I have a tabled view in a while loop, where a user can view information on books.
For example, book ISBN, book name, read status...
Basically, when the user sets their 'readstatus' to 'complete' I want that specific table row to become grey! The logic is very straight forward, however I can't get my IF statement to recognise this:
if ($readstatus == 'complete') {
echo '<tr class="completed">';
}
else if ($readstatus != 'complete') {
echo '<tr class="reading">';
}
I'm obviously doing something wrong here, table content to change if the value of 'readstatus' = 'complete', if not, then output is the default
Why are you using $_GET? Does this information come from an HTML form or a URL etc... ?
I suspect you meant to change $readstatus = $_GET['readstatus']; to $readstatus = $row['readstatus'];.
$_GET is an aray of GET parameters which come from the query string.
$row is a row in your database, so if the information is in the database - which I suspect it is - you want to use $row instead of $_GET.
Try changing $readstatus = $_GET['readstatus']; to $readstatus = $row['readstatus'];
The $_GET function relies on the value being contained in the query string of the URL, and it has nothing to do with the database. I have a hunch you're trying to get the value from the database here and you're using the wrong function to do it.
$_GET['readstatus'] says the value is coming from the browser.
$row['readstatus'] says the value is coming from the database.
You need to decide which should take precedence-- probably the $_GET['readstatus']` because it's what the user wants to change. If that's the case, you need to update your database with the new readstatus before you requery the db for the dataset.

Categories