How to display different ccs-style depending on php condition - php

Basically, I have an upvote or downvote button for users. When users click the upvote or downvote, the corresponding button changes depending on the user input.
My problem is how do I display which post did the user upvoted or downvoted when a user refreshes the page?
Here's my code:
<?php
if(user_upvoted){
?>
<style>
.button<?php echo $button_id;?>
{//css for upvote}
</style>
<?php
}
else if(user_downvote){
?>
<style>
.button<?php echo $button_id;?>{//ccs for downvote}
</style>
<?php
}
?>
Here is my buttons' code:
while($row=$query -> fetch(PDO::FETCH_ASSOC))
$nid = $row['nid'];
{
<button class="button<?php echo $nid;?>" id="<?php echo $nid ; ?>" name="up">
}
This works but this code seems so dirty and don't feel right if you get my meaning.
PS: This is also in a php while loop that's why this is the method I tried.
What's a cleaner method of doing this

You can code as below:
<?php
while($row=$query -> fetch(PDO::FETCH_ASSOC))
{
$nid = $row['nid'];
// Write your logic here for $user_upvoted and $user_downvote variable
$btnExtraClass = '';
if($user_upvoted){
$btnExtraClass = 'button_upvote';
}
if($user_downvote){
$btnExtraClass = 'button_downvote';
}
?>
<button class="button<?php echo $nid;?> <?php echo $btnExtraClass;?>" id="<?php echo $nid ; ?>" name="up">
<?php
}
?>
and then write your CSS rules separately.
<style>
.button_upvote {......}
.button_downvote {......}
</style>

your question seems bit confusing. Can you first help me explain below points
1) Are you storing your upvote/downvote selected by user in the database ?
Also why are you suing class here
if(user_upvoted){
?>
<style>
.button<?php echo $button_id;?>
{//css for upvote}
</style>
It should be an id. if you are uniquely identifying them, then go for a id

Related

PHP Code is printing text not typed code

I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);

PHP View Counter

I am trying to make a website and it's almost completed but I want to add a view counter so when someone visit the page it count the view and save it into the database.
My script is working fine but the problem is that it continue view count even visitor is viewing anyother page
My pages url show like this
pictures.php?ID=13
I have added this PHP code in *count.php*
<?php
session_start();
if (isset($_SESSION['views'])){
$_SESSION['views']++;
} else {
$_SESSION['views'] =0;
}
//echo $_SESSION['views'];
?>
Page *views.php*
<?php
session_start();
if (isset($_SESSION['$post_id'])){
$_SESSION['$post_id']++;
} else {
$_SESSION['$post_id'] =0;
}
//echo $_SESSION['views'];
?>
<?php
echo "<hr><div align=\"center\">";
echo $_SESSION['$post_id'];
?>
<?php
$save = $_SESSION['$post_id'];
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE save_data SET Views='$save' WHERE ID='$page_id'");
mysqli_close($con);
?>
And added this line in Pictures.php where I want to show and count visits
<?php include("views.php"); ?>
Problem:
When someone visits page pictures.php?ID=8 it will show him page view 1 and save this view in database where ID=8, when he visit page pictures.php?ID=12 it will show him view 2 and save this 2 in database where ID=12. My point is that it is continuously counting instead of each page view.
Thanks in advance
Here is Pictures.php
<?php
include("connection.php");
if(isset($_GET['ID'])){
$page_id = $_GET['ID'];
$select_query = "select * from save_data where ID='$page_id'";
$run_query = mysql_query($select_query);
while($row=mysql_fetch_array($run_query)){
$post_id = $row['ID'];
$post_title = $row['Title'];
$post_image = $row['Name'];
?>
<h3>
<a href="pictures.php?ID=<?php echo $post_id; ?>">
<?php echo $post_title; ?>
</a>
</h3><center>
<form id="search-form" action="javascript:void(0);">
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Resize" Onclick ="splitString()"/></form>
<div id="sizet">
Type size like 200*300 in box
</div></center>
<div id="img"><img id="myImage" src="uploads/<?php echo $post_image; ?>" /></div>
<?php } }?>
<center>
<div id="postdetails">
<?php include("posted_by.php"); ?></center>
</div>
<?php include("views.php"); ?>
<html>
<link href="css/Pictures.css" rel="stylesheet" type="text/css">
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
</body>
Variables inside of single quotes are not evaluated, so regardless of whether $post_id is 8 or 12, $_SESSION['$post_id'] is setting the key named literally $post_id, rather than the key named 12 or 8. Variables are evaluated inside double quotes, so $_SESSION["$post_id"] would work, but the simplest and best way is to use $_SESSION[$post_id] instead.
Additionally, using $_SESSION here is probably not what you want to do. $_SESSION will be different for every user who visits the site, so when a new visitor comes to the site, it will start over with a count of 1. What you probably want to do is load the views value from the database, add one to it, and then save it back to the database. $_SESSION is for keeping data that is specific to a certain user.
Try to use structure like this
$_SESSION['view'][{resource_name}_{resource_id}]
E.g. for picture with id 8 it will be
$_SESSION['views']['picutures_8']++

echo a session variable in a <a href> over to the next page?

Please can someone help me with this. I have this MySQL query which lists users on my site, and echos a link that can be clicked to take you to the user's profile:
<?php
$online_set = online_channel();
while ($online = mysql_fetch_array($online_set)) {
echo "<div class=\"online_row\"><img width=25px height=25px src=\"data/photos/{$online['user_id']}/_default.jpg\" class=\"online_image\"/><div class=\"online_text\">{$online['display_name']}</div></div>";?>
<? } ?>
The link goes to profile.php and echos the users 'user_id' so it knows which users profile to take you to, and now I am wanting to include a session variable in the link somehow so a message is displayed on that users profile after clicking the link.
I have tried including $_SESSION['chat'] in the link but it doesn't work:
<?php
$online_set = online_channel();
while ($online = mysql_fetch_array($online_set)) {
echo "<div class=\"online_row\"><img width=25px height=25px src=\"data/photos/{$online['user_id']}/_default.jpg\" class=\"online_image\"/><div class=\"online_text\">{$online['display_name']}</div></div>";?>
<? } ?>
I am also trying to execute the session in profile.php by using this:
<?
session_start();
if(isset($_SESSION['chat']))
echo $_SESSION['chat']="<div class=\"infobox-favourites\"><strong>Deleted from Favourites</strong> - This user has successfully been deleted from your favourites.</div><div class=\"infobox-close4\"></div>";
unset($_SESSION['chat']);
?>
What I have tried is not working and i'm not sure i'm doing it right, so I would really appreciate any help with this. Thanks
Try this...for easier debugging the entire code you have
<?php
$online_set = online_channel();
while ($online = mysql_fetch_array($online_set)) {
?>
<div class="online_row">
<a href="profile.php?id=<?php echo $online['user_id'];?>">
<img width=25px height=25px src="data/photos/<?php echo $online['user_id'];?>/_default.jpg/" class="online_image" />
<div class="online_text\">
<?php echo $online['display_name'];?>
</div>
</a>
</div>
<?php
}
?>
Just review the code I posted to learn the better way to echo an entire div

Output Name in PHP From mysql Database

I have a list of names in a database that i want to display one by one
(also for bonus points, another column in the database is a Boolean value for if a task is completed or not. if this is true i want the css content box background to be green instead of red.)
so how can i select a name from row one, put it to a PHP variable, then select the value from the "Name" column in row 2 and put that to another PHP variable or the next item in the array?
thanks for any help!
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mngPWinCSS.css"/>
</head>
<body>
<?php
$dsn ='mysql:host=****.******.com;dbname=o****_**n';
$username='********';
$password ='******';
mysql_connect('localhost',$username,$password);
$query=mysql_query("SELECT Name FROM CLOAS_Team LIMIT 0,1");
$bob="dkajfk";
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url");
$com[1]="i";
$com[2]="i";
$com[3]="i";
$com[4]="i";
$com[5]="i";
$com[6]="i";
$name=mysql_fetch_array($query);
?>
<div id="content">
<img src="logjpg.JPG" alt="Smiley face" height="50" width="200">
<h3>CLOAS Tracker</h3>
</div>
<div id="Content">
<?php
?>
<div id="complete">
<h3names>
<?php
echo $name['Name'];
?>
</h3names>
</div>
<div id="incomplete">
<h3names>Name2</h3names>
</div>
</div>
</body>
</html>
First you need to change your SELECT query to select all of the rows that you wish to display, perhaps by taking off the LIMIT clause. Something like this;
$result=mysql_query("SELECT Name FROM CLOAS_Team");
(This will get you all of the names in your table.)
Next, you need to loop through the results you got from this query, like so;
$names = array();
while($row = mysql_fetch_assoc($result))
{
$names[] = $row['Name'];
}
This will put them into the array $names for you, which you can then work with. Instead of putting them into the array, you might want to output them immediately, perhaps like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div>
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
However, you have many more errors in your code. Such as;
You can't just invent html elements called <h3names>
I doubt that you want to set the id attribute to 'incomplete'. An id should be unique, I expect you should be putting this in as a class (class = "incomplete")
I don't think your line header("Refresh: 60; URL=$url"); will do anything as your headers have already been sent to the page. If you want this line to work, it needs to be right at the top, BEFORE any output has been sent to the browser.
And for the bonus point, include the 'Completed' field in your query (if that is what it is called) and use this to add a style to each <div> element that you display in your loop. So your query might become;
$result=mysql_query("SELECT Name, Completed FROM CLOAS_Team");
And your loop would now be like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div style = "background-color:<?php echo $row['Completed'] == true ? 'green' : ' red'; ?>">
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>

while() and onclick

I have this:
while( $rowData = #mysql_fetch_assoc($selectRows2) )
{
?>
<div id="stemmeto"><a href="#" id="thelink" onclick="window.parent.OpenVote(<? echo $_GET['id']; ?>, '<? echo $rowData['username']; ?>');">
<?php echo $rowData['username']; ?> </a></div>
<div id="stemme">
<a href="#" id="thelink" onclick="window.parent.OpenVote(<? echo $_GET['id']; ?>, '<? echo $rowData['username']; ?>');">
<? echo $rowData['stemme']; ?></div></a><br />
<?
}
Now this should activate OpenVote function with (id, username) in the parent.window..
But for some reason this only works for first column, that comes out, nothing is happening when i click the others.. I have tried to remove that column, to check to see if its specially just that column, but it wasnt, its always the "first" column that echo´s out in the while(), that i can click on.. what should i do?
Here's the OpenVote script on the parent window(index.php)
function OpenVote(id, stemme) {
var postThisShit = 'battles/infoaboutvote.php?id='+id+'&stemme='+stemme;
$.post(postThisShit, function(data){
$(".showinfo").html(data).find(".getinfo").fadeIn("slow")
});
}
And the #thedialog on index.php:
<div id="thedialog" title="Showing..">
<p class="showinfo">
You shouldn't see this, something went wrong..
</p>
</div>
The id attribute must be unique across your entire document. Your loop is creating multiple elements with the same id, which will cause behavior like you're describing when trying to interact with the elements. Try appending a unique value to the end of the id, such as id-1, id-2, id-3, etc.

Categories