How do I Limit some information displayed from the database and add a link eg "More" to enable read all information in a drop down using PHP. such as what is on facebook (Read more...). I am dealing with a lot of content and I dont want it all displayed at once.
Here is part of the code
echo "<p>".$row['Firstname']." ".$row['Lastname']."</p>";
echo "<p>".$row["Course"]." | ".$row["RegID"]."</p>";
echo "<p>".$row["Email"]."</p>";
echo "<p>"."Tel:".$row["Telephone"]."</p>";
echo "<p>".$row["info"]."</p>";
The code is running well only that I want to limit the information
echo "<p>".$row["info"]."</p>";
so that not all is displayed
Thanks
Use Jquery-ui click on "view source" and you'll see it's very simple really, just set the row that you want as the header (what's clicked to show the rest) and store the rest in a div below.
Split info into two strings, one intro, and the rest. Display only the intro to begin with. Insert a link that displays the rest when clicked.
$intro = substr($row['info'], 0, 200);
$rest = substr($row['info'], 200);
echo sprintf(
<<<HTML
<p>
<span class="intro">%s</span><span class="rest" class="display: none">%s</span>
Show more
</p>
HTML
, htmlentities($intro)
, htmlentities($rest)
);
displayRest is a Javascript-function that, given a link, finds the previous span with class rest, shows it and removes the link. I leave it as an exercise to implement this in a way that fits your project. You can go with native Javascript, or use a library such as jQuery, YUI, MooTools, Prototype etc.
if(isset($_POST['more']))
{
$query="select col1,col2,col3, ... ,colN from tableName ";
}
else
{
$query="select col1,col2,col3 from tableName ";
}
//HTML
<form method="post">
<input type="submit" name="more" value="More" />
</form>
//PHP
$records=mysql_query($query);
while($row=mysql_fetch_assoc($records))
{
//Display
}
The limit must be fixed on the SQL request.
// If you want to transmit limitation with a GET PARAMETER.
// You can also $_POST ur data.
$limitation = $_GET['limit'];
//..... And in your SQL REQUEST
$sql = "SELECT * FROM your_table LIMIT 0 , $limitation";
//And in the link....
echo 'Show only 10 Results'
?>
You can optimize that and add security precaution to prevent errors when $limitation receive empty or non numeric parameters.
<?php if(isset($_GET['limit']) && !empty($_GET['limit']) && !preg_match(EXPRESSION, $_GET['limit'])){
//YOU CAN DO THE LIMITATION WHITOUT SQL ERRORS
}
else{
//ERROR DIRECTIVE
}
?>
Related
I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery
I want to get details from one site. That web page is having 3 different select box:
1) Choose Branch
2) Choose Semester
3) Choose Exam Year and then click on show button. This site is using AJAX to show table(output).
I tried with HTML dom parser but don't know the parameters to be passed with that. How to automize such thing which works(submit) with AJAX?
My code is:
<?php
include('simple_html_dom.php');
$html = file_get_html("http://www.abc.com/Engineering-Degree/ExamPapers/ExamPapers.aspx");
foreach($html->find('select[id=Branch]') as $branchSelect)
{
echo $branchSelect;
foreach($html->find('select[id=Semester]') as $semSelect)
{
echo $semSelect;
foreach($html->find('select[id=Exam]') as $examSelect)
{
echo $examSelect;
echo "<input type='submit' value='Show' id='BranchSemesterExamBtn'/>";
}
}
}
?>
Those selects are using get method to retrieve data maybe. Goto you browser console(F12) and change those select options. You may get the links there.
I have worked on this for a few days now.
This snippet finds the correct row(s) from the database. It works fine. However, when the Button is clicked, I only want for the comment it is next to targeted, not all the comments on that page. It's hard to explain.. Let me show you image.
What I am doing currently is selecting the database rows and outputting them for debugging, instead of removing them (I don't want to go around deleting sections of my database with broken code)
$db is mysqli connection to the database
Snippet of the while loop:
TL/TR
I want to do the following with this in the end:
Remove the comment from the database.
Give the feedback to an admin.
This may sound like a noob question, but please help me.
Many thanks!
Just can't wrap my head around this, made like 6 pages single-handed and now I am stuck in a thing this "easy" for a d**n week and i still can't get it right.
EDIT
Latest snippet (Still doing it, What the hell!?!)
$query = $db->query("SELECT * FROM comments WHERE post_id='$id'");
while($row = $query->fetch_object()){
echo "<h5>".$row->name."</h5>","<br>";
$strip_comment = strip_tags($row->comment);
$delComment = $row->comment_id;
$strip_comment_shlashes = stripslashes($strip_comment);
echo "<blockquote>".$strip_comment_shlashes,"<br><br></blockquote>";
//button stuff
if($is_admin){
$query1 = $db->prepare("SELECT comment_id FROM comments WHERE comment_id = '$delComment'");
$query1->execute();
$query1->bind_result($commId);
while($row2 = $query1->fetch()):
?>
<form action="<?php echo $_SERVER['PHP_SELF']."?id=$id"?>" method="post">
<input type="submit" class="closeButton" name="deleteComment" value="<?php echo $commId; ?>" />
</form>
<?php
if(isset($_POST['deleteComment'])&& $is_admin){
if($is_admin && $commId){
echo "Comment ID <b>$commId</b> Removed";
}
}
endwhile;
}
Edit: NON-OBJECT error..
$delComment_2 = $_POST['deleteComment'];
$query2 = $db->prepare("SELECT * FROM comments WHERE comment_id='$delComment_2'");
$query2->execute();
Edit 2: (31/10)
Please, Could someone fix this snippet and post it? I don't usually ask for working snippets, but this one is driving me crazy. I just am too noob to understand how this goes. Thanks.
Change the input to this:
<input type="submit" class="closeButton" name="deleteComment" value="$comment_id_here" />
And then just use the comment id to delete a specific one from the database. (check $_POST['deleteComment'])
Of course, there are numerous other ways to do this - but the point is the same: you need to pass the comment id (not the post id) from your page to the query string. Whatever way you use to accomplish that is up to you, I just gave you an example.
I'm trying to make a simple vote script in PHP and need help. The problem I'm having is that I've created a form with two buttons, like and dislike, which correspond to an if else statement.
If the like button is clicked do an update, else the dislike button was clicked do an update.
Here is the code I have so far, there is more above it, but not necessary to my problem:
while($row = $q2->fetch())
{
$up_vote= $row['up_votes']; /*Current Up Votes*/
$down_vote= $row['down_votes']; /* Current Down Votes*/
echo '<form method="post" action="">';
echo '<input type="button" id="up_vote" name="up_vote" value="Like" /> OR';
echo '<input type="button" id="down_vote" name="down_vote" value="Dislike" />';
echo '</form>';
echo round($row['rating'], 0);
echo '% of voters Liked this';
}
$up_votes = $up_vote +1;/*$up_vote referes to original # of up_votes, $up_votes adds 1 to the number of votes*/
$down_votes = $down_vote +1;/*$down_vote referes to original # of down_votes, $up_votes adds 1 to the number of votes*/
if ($something);/*upvote clicked*/
{
$vote_update = "UPDATE images
SET up_votes:up_votes
WHERE vote_item_id: vote_item_id";
$q3 = $conn-> prepare($vote_update);
$q3->execute(array(':up_votes'=>$up_votes, /*$up_vote referes to original # of up_votes, $up_votes adds 1 to the number of votes*/
':vote_item_id'=>$current_vote_item_id));
/* ALSO create INSERT INTO votes_done to track the user vote*/
$conn = null;
}
else ($something2);/*down vote clicked*/
{
$vote_update = "UPDATE images
SET down_votes:down_votes
WHERE vote_item_id: vote_item_id";
$q3 = $conn-> prepare($vote_update);
$q3->execute(array(':down_votes'=>$down_votes, /*$down_vote referes to original # of down_votes, $up_votes adds 1 to the number of votes*/
':vote_item_id'=>$current_vote_item_id));
/* ALSO create INSERT INTO votes_done to track the user vote*/
}
What should the if and else statements look like? I'm not sure how to go about this, can't have two submits, should I have two different forms, one for each button? Either way how can I say if like was clicked go to if and run code, or if dislike was clicked go to else and run code?
Thanks
Syntax errors aside, you can give the two buttons the same name, but different values.
echo '<form method="post" action="___URL OF YOUR PAGE___">';
echo '<input type="submit" id="up_vote" name="vote" value="Like" /> OR';
echo '<input type="submit" id="down_vote" name="vote" value="Dislike" />';
echo '</form>'
...
if($_POST['vote'] == "Like") {
...
} else if ($_POST['vote'] == "Dislike") {
...
}
Note that I changed the input's type to submit instead of button. This will cause the data to send itself to the page (button won't do anything unless you start adding JavaScript).
You can read more about this in these answers:
https://stackoverflow.com/a/6129301/1451957
html button v.s. html submit?
PHP is server side, while you want to control events triggered in client side (a user clicks one button, or another).
Javascript/Jquery are client side, there you can control and trigger events that call to PHP scripts that will do the query.
Also else(){ is not valid in PHP, you should use elseif(){.
This sounds like an instance where using JavaScript would be more useful, but if you really want to use PHP you can either use two separate forms or change the buttons to links that look like buttons and add URL parameters.
Also: you've got some syntax errors. Examples: you shouldn't be putting semicolons after your if/elseif conditions, else() should be elseif(), you're using two different variable names when trying to increment $up_votes and $down_votes, etc.
Why dont't you add an 'onclick' event to each of the like and dislike buttons, and execute different script?
I have put up some code to make an ajax, php, mysql chat in real time...
this is my code:
-jQuery/Ajax
$(function(){
setInterval(function() {
$('#chMsgCont').load('./ajax/msg.php');
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
}
,1000);
});
"./ajax/msg.php"
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg ORDER BY timestamp ASC");
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
?>
I haven't found any method for not loading every second the "msg.php" file... I thought: is it possible to load initially the messages and then with setIntervall check for new messages to append to #chMsgCont? I think it is possible, but i can't figure out how to code it :/, can anyone help me?
Yes it is possible to load all messages upon initial page load; then subsequently update the chat window with new messages (have you ever wondered how Gmail auto populates new mail into your Inbox without a page refresh? Lots of AJAX requests).
You're on the right track. Just make sure you have a column in your MySQL database that holds a "yes/no" value on whether its a new message or not. Then everytime a new message is fetched using ajax/msg.php, in addition to fetching and outputting the content, perform a SQL update to update the fetched data as well.
Once you have that working you can further optimize your chat application by creating a simplier MySQL SELECT statement that simply checks the count of "new" rows (SELECT COUNT(new_message) FROM messages). Then check the value returned and whether it's greater than 0 before attempting to append content. I would also check for empty return data in your JavaScript to prevent from unnecessarily manipulating DOM elements.