Echoing a <div> and obtaining the id of it - php

Currently, when displaying all posts made by users I do the following:
while($info=mysql_fetch_array($data)) {
echo "<div id = 'posts'>";
echo $info['subject'];
echo $info['post-item'];
echo "</div>";
}
But, however, I now need to treat each element fetched as an actual post rather than just an outputted div for obtaining the post_id of each post to be able to actually enable a user to interact with different posts e.g. to 'like' a post.
I had tried hyperlinking the like href to ?id=$thispost which worked for liking however had problems such as a user altering the url, or even if I would like to also add the commenting functionality, I would need a different method!

As for different tasks, you would pass different querystrings:
like this
comment
share this
In page.php, you would then...
if (isset($_GET['do'] && isset($_GET['id'])) {
$do = $_GET['do'];
$id = $_GET['id'];
} else exit("blabla");
switch ($do) {
case 'like':
// do sth
break;
case 'comment':
// do sth
break;
// etc.
} // switch
Of course, passing the values by URL open the gate to manipulation.
So either store $do and $id in $_SESSION or in $_POST.
Example for $_POST:
$h = "";
while ($info = mysql_fetch_array($data)) {
$h .= '<div id = "posts">';
$h .= '<form method="post" action="page.php">';
$h .= "{$info['subject']}<br />{$info['post-item']}";
$h .= "<input type=\"hidden\" name=\"id\” value=\”{$info['id']}\” />';
$h .= '<input type="submit" name="do" value="like" />';
$h .= '</form></div>';
}
echo $h;
Comments:
1. don't use mysql_*, but mysqli_* or PDO -> makes your code future-proof and more secure
2. this code creates a form around every post, with a hidden field containing the id (from db) of that post...
3. and a button that will send the id invisible for the user to page.php.
4. in page.php, you read $_POST, as in my above exaple with $_GET:
if (isset($_POST['id'])) {
$do = $_POST['do'];
$id = $_POST['id'];
} else exit("blabla");
// etc.

Related

onclick attribute in tag <a> doesnt work correctly

I have a menu which get its items from database.
I want to get the menu id of clicked menu in following for each:
public function gen_menu($menuItems, $pId = 0)
{
$menu = '';
$ulStart = 0;
$base_url = base_url();
$uri = $this->uri->segment(1);
foreach($menuItems as $row)
{
if($row->parent_id==$pId)
{
if($ulStart==0) { $menu .= "<UL>"; $ulStart++; }
$url = $row->item_url;
stripos($url,$base_url)===0 || $url==""?$base_url = base_url():$base_url="";
{
if($row->external==1){
$menu .= '<LI>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
else{
$class = ($uri==$row->custom_url)?"class='selected'":"";
$menu .= '<LI '.$class.'>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
}
}
}
}
if($ulStart!=0) { $menu .= "</UL>"; }
return $menu;
}`
When I am using onclick in it returns the last id of table always.
Try this:
$menu .= '<LI '.$class.'>'.$row->item_title.''.$this->gen_menu($menuItems, $row->item_id).'</LI>';
You had $row->item_id inside the quoted string, so it wasn't expanded. You should have gotten a javascript error from that.
UPDATE:
The problem you're having is that you're confusing server-side and client-side actions. The code in this PHP script all runs on the server when it's creating the page to send to the user. If you're setting a session variable in the loop, the variable will contain the value from the last iteration. Putting PHP code inside onclick doesn't run it when the user clicks, it runs it when the server is composing the onclick attribute to put in the HTML that gets sent to the browser.
If you want to do something on the server when the user clicks, you need to put a Javascript function in the onclick attribute, and that function should use AJAX to call another PHP script.

Can I show, hide and toggle results in PHP echo?

Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>​
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
​
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}

Passing form ID's as a variable back and forth between javascript and php

Let me start off by saying while I'm pretty good with PHP and HTML, I don't know much about javascript/jquery. I also apologize if this has been answered before, but I haven't had much luck finding anything in the search.
I'm working on a project where we have a form of undetermined size that I want to build some autocomplete functionality into. The form fields and necessary div's are being named using a counter as you can see in the code below.
$set_b = 'upl_band'.$count;
$sugbox = $set_b."sug";
$autobox = $set_b."auto";
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup='bandlookup(this.value,'$set_b');' onblur='bandfill();'></div>";
echo "<div class='suggestionsBox' id='$sugbox' style='display: none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;' alt='upArrow' /><div class='suggestionList' id='$autobox'> </div></div>";
I'm trying to pass the main value - $set_b into my javascript onkeyup. However, somewhere along the line I'm losing my values. If I setup my form with concrete id's this code works fine, but when I make my id's variable I'm getting lost. My javascript is below. The post call to band.php is my lookup script.
function bandlookup(bandString, boxName) {
if(bandString.length == 0) {
// Hide the suggestion box.
var s = boxName+"sug";
$("#"+s).hide();
} else {
var su = boxName+"sug";
var suauto = boxName+"auto";
$.post("band.php", {queryString: ""+bandString+"", inputName: ""+boxName+""}, function(data){
if(data.length >0) {
$("#"+su).show();
$("#"+suauto).html(data);
}
});
}
} // lookup
function bandfill(thisValue, boxName) {
var s = boxName+"sug";
$("#"+boxName).val(thisValue);
setTimeout("$('#'+s).hide();", 200);
}
and band.php
$db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$box = $_POST['inputName'];
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT band_name,band_id FROM upl_band WHERE band_name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
echo '<li onClick="bandfill(\''.$result->band_name.'\',\''.$box.'\');">'.$result->band_name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
My problem could be with the post call in the javascript, but I'm more leaning towards me improperly dealing with the variable variable names as an id tag.
Your string is broken, try this:
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup=\"bandlookup(this.value,'$set_b');\" onblur='bandfill();'></div>";

Detect session/cookie variable in wordpress to prevent access to documents

Hey guys, I've gotten as far as my code below, but I am trying to create an AJAX search form that is 'safe' on my wordpress blog, by detecting the session variable or a cookie or something
<?php
#session_start();
If (!array_key_exists(‘authed’, $_SESSION))
{
include ‘not_authed.inc’;
exit();
}
// go about your business.
?>
and i'm trying to add that to this:
<?php
function checkValues($value)
{
// Use this function on all those values where you want to check for both sql injection and cross site scripting
//Trim the value
$value = trim($value);
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Convert all <, > etc. to normal html and then strip these
$value = strtr($value,array_flip(get_html_translation_table(HTML_ENTITIES)));
// Strip HTML Tags
$value = strip_tags($value);
// Quote the value
$value = mysql_real_escape_string($value);
return $value;
}
mysql_connect ("mysql.*****.com", "****","$*****") or die (mysql_error());
mysql_select_db ("***********");
$term = checkValues($_REQUEST['val']);
$term = mysql_real_escape_string($term);
$sql = mysql_query("select * FROM patient_db WHERE id_number = '$term'");
if($row = mysql_fetch_array($sql)) {
echo "<img src=\"******\" class='leftfloat' border=0>";
echo '<p>';
echo '<br /> ID Number: ' .$row['id_number'];
echo '<br /> Name: ' .$row['Name'];
echo '<br /> Exp. Date: ' .$row['exp_date'];
echo '<br /> DOB: ' .$row['dob'];
echo '</p>';
//echo "<a href='******' title='Printer Friendly Version' alt='Printer Friendly Version'><img src=\"*****\" class='rightfloat' border=0 height=33 width=33></a>";
} else {
echo "<img src=\"*****\" height=50 width=50 class='leftfloat' border=0>";
print "<h1>USER ID <br/>NOT FOUND</h1><br />";
print "<strong>OOPS!! THIS COULD BE AN ERROR</strong><br />";
print "<br />";
print "<div>*****</div>";
}
?>
The problem you are going to have is that the AJAX request is a separate session / cookie as it is a completely different process not tied into to the browser.
So how do you go about authenticating someone? A Token of sorts. So you would create a hash, which would need to be stored in the database for the user, which can be regenerated upon login etc. Then you would use this token to validate that user and allow the AJAX submission to work.
Hopefully that gets the ball rolling for you. So in your AJAX push script you would just appened a variable to the GET or POST data called token and then check it on the receiving PHP script. There are other ways of doing it, this is just one that I know of :)

PHP, MySQL & JQuery Question?

I have this script that displays all the users images which i will display below.
My question: Is there a way I can display the first 10 images in the MySQL database and have the script hide the rest of the users images until the user clicks the link View All and have the rest of the images slide down when the user clicks the link?
Here is my PHP & MySQL script?
$multiple = FALSE;
$row_count = 0;
$dbc = mysqli_query($mysqli,"SELECT *
FROM images
WHERE images.user_id = '$user_id'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
if(($row_count % 5) == 0){
echo '<ul>';
}
echo '<li><img src="/images/thumbs/' . $row['url'] . '" /></li>';
if(($row_count % 5) == 4) {
$multiple = TRUE;
echo "</ul>";
} else {
$multiple = FALSE;
}
$row_count++;
}
if($multiple == FALSE) {
echo "</ul>";
}
}
echo 'View All';
Split the images into two parts. And set the second part to be hidden. Then add a click handler to slideDown. Here is the code:
UPDATE: it's not necessary to put the first 10 images into a div, but won't hurt either.
PHP
<?php
//echo '<div id="images">'; // visible images
while($row = mysqli_fetch_array($dbc)) {
// other stuff
// ...
// after the 10th image (0-9)
// open the hidden div
if ($i == 9) {
//echo '</div>'; // end of visible images
echo '<div id="hidden">'; // hidden images
}
}
echo '</div>'; // end of hidden
echo 'view all'; // view all
?>
jQuery
$(document).ready(function(){
$("#hidden").hide();
$("#view_all").click(function(){
$("#hidden").slideDown();
});
});
See it in action
Note: be sure not to hide the div with CSS. You do it in jQuery, and by this you allow users with JS disabled to get the content.
I'm not sure how many, or how large these images are, but if you want to make this scalable, I'd suggest doing an ajax callback that retrieves and fills in the "hidden" images, if the user requests them.
Yes, in your loop echoing out the list items, add the style="display:hidden" class="hidden" attribute when the count is > 10. Then use the window's scroll event to detect when the browser is scrolled near to the bottom of the window and then use jQuery to show the first hidden list item.
EDIT: This actually will show the items as the user scrolls down and does not need a "Show all button".
JQuery:
$(".hidden").hide();
$(window).scroll(function(){
if ($(window).scrollTop()+$(window).height > $("li:hidden:first").offset().top - SOMEPADDING )) {
$("li:hidden:first").fadeIn(200);
}
}

Categories