So I load 3 records with this msql query:
$query = "SELECT * FROM adatok ORDER BY `id` DESC LIMIT 3 "
And I created a load more button for user can be load the other 3 records with this query:
$query = "SELECT * FROM adatok ORDER BY `id` DESC LIMIT 4,3
And then come the problem.
Becouse when the user click for the load more button again, this get the same record as which had been received.
So how can I autoincrement limit number?
demo page:
http://neocsatblog.mblx.hu/addvideos/type.html
Press crtl+i for open box.
Update:
The id is auto incremented.
Thanks for the improvements for #spencer7593.
My table strukture looks like this.
Full php code, for what happening if you click the more button:
<?php
$connection = mysql_connect('localhost', 'neocsat_videos', 'password'); //The Blank string is the password
mysql_select_db('neocsat_videos');
mysql_query("SET CHARACTER SET utf8 ");
$page = 1
$query = "SELECT * FROM adatok ORDER BY `data_reg` DESC LIMIT 3,4 ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo '<div class="video-header">';
if (!function_exists('echoOnce')) {
$runOnce = false;
function echoOnce()
{
global $runOnce;
if(!$runOnce)
{
$runOnce = true;
return "<img class='close2' src='/kep/icon_24x24_close_highlight.png'>";
}
}
}
$datatime=$row['date_reg'];
$img = '<img title="' . $datatime . '" src="time.png" class="time_icon" >';
echo echoOnce();
echo '<p>';
echo $row['name'];
echo '</p>';
echo $img;
echo '</div>';
echo '<div class="result">';
echo ' <iframe class="video" allowfullscreen style="overflow-x: hidden; overflow-y: hidden;" width="658px" height="569" frameborder="0" src="'.$row['url'].'"></iframe>' ;
echo '</div>';
echo '<div class="leiras">';
echo '<p>';
echo $row['leiras'] ; //$row['index'] the index here is a field name
echo '</p>';
echo '</div>';
echo '<div class="clear">';
echo '</div>';
?>
<a class='load'><div class='more'>További videók betöltése</div></a>
<?php
$connection = mysql_connect('localhost', 'neocsat_videos', 'zP77XRavaXMA'); //The Blank string is the password
mysql_select_db('neocsat_videos');
mysql_query("SET CHARACTER SET utf8 ");
$page = 1
$query = "SELECT * FROM adatok ORDER BY `data_reg` DESC LIMIT 3,4 ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo '<div class="video-header">';
if (!function_exists('echoOnce')) {
$runOnce = false;
function echoOnce()
{
global $runOnce;
if(!$runOnce)
{
$runOnce = true;
return "<img class='close2' src='/kep/icon_24x24_close_highlight.png'>";
}
}
}
$datatime=$row['date_reg'];
$img = '<img title="' . $datatime . '" src="time.png" class="time_icon" >';
echo echoOnce();
echo '<p>';
echo $row['name'];
echo '</p>';
echo $img;
echo '</div>';
echo '<div class="result">';
echo ' <iframe class="video" allowfullscreen style="overflow-x: hidden; overflow-y: hidden;" width="658px" height="569" frameborder="0" src="'.$row['url'].'"></iframe>' ;
echo '</div>';
echo '<div class="leiras">';
echo '<p>';
echo $row['leiras'] ; //$row['index'] the index here is a field name
echo '</p>';
echo '</div>';
echo '<div class="clear">';
echo '</div>';
?>
<a class='load'><div class='more'>További videók betöltése</div></a>
<?php
}
mysql_close(); //Make sure to close out the database connection
?>
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Nunito:700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style2.css">
<style>
#video-body,.video-body{
background-color:white;
width:780px;
position: fixed !important;
top: 100px;
right: -799px;
border-radius: 5px;
padding-left: 13px;
padding-bottom: 30px;
max-height: 453px;
overflow-x: hidden;
}
#video-header,.video-header{
border-bottom: 6px solid gray;
margin-left: 73px;
width: 628px;
}
#result,.result{
margin-left: 62px;
}
#video-header p,.video-header p{
margin-left: 158px;
font-family: 'Nunito', sans-serif;
font-size: 22px;
font-weight: bold;
padding-top: 12px;
margin-bottom: 11px;
}
#clear,.clear{
border-bottom: 6px solid gray;
width: 625px;
margin: 50px 82px;
}
#leiras, .leiras{
margin: -274px 139px 28px;
font-family: 'Nunito', sans-serif;
font-size: 13px;
font-weight: bold;
word-wrap: break-word;
background-color: rgba(0, 0, 0, 0.8);
border-radius: 5px;
min-height: 29px;
text-align: center;
padding: 3px;
}
.leiras p{
color:white;
}
</style>
<script>
$(".close2").click(function(){
$(".video-body").fadeOut();
$( "iframe" ).remove();
$( "div" ).remove();
$( "p" ).remove();
});
$(".video-body").on('click', '.load', function() {
jQuery.ajaxSetup({ async: false }); //if order matters
$.get("next.php", '', function (data) { $("#video-body").append(data); });
});
$( ".time_icon" ).tooltip({
show: null,
position: {
my: "left top",
at: "left bottom"
},
open: function( event, ui ) {
ui.tooltip.animate({ top: ui.tooltip.position().top + 10 }, "fast" );
}
});
</script>
<script>
// The plugin code
(function($){
$.fn.urlToLink = function(options) {
var options = $.extend({}, $.fn.urlToLink.defaults, options);
return this.each(function(){
var element = $(this),
expression = /(\b(https?|ftp|file|https|http):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// The magic
return element.html( element.text().replace(expression, "<a class=lightview href='$1' target='"+options.target+"'>$1</a>") );
});
}
/**
* Default configuration
*/
$.fn.urlToLink.defaults = {
target : '_self' // Link target
}
})(jQuery)
// The call
$('p').urlToLink();
</script>
Javascript:
$(".video-body").on('click', '.load', function() {
jQuery.ajaxSetup({ async: false }); //if order matters
$( "#video-body" ).load( "next.php" );
});
$limit = 2; //how many items to show per page
$page = $_GET['page'];
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
$sql = "SELECT column_name FROM tbl_name LIMIT $start, $limit";
$query = "SELECT * FROM adatok ORDER BYidDESC LIMIT ".($page*3 ).",3"; where $page is number of times that More button pressed.
on first click $page = 1, on second $page = 2 and so on
Assuming that id is unique, the normal pattern is to save the last id value retrieved by the previous query:
Then your "next" query would be of the form:
SELECT ... FROM adatok WHERE id < :last_id ORDER BY id DESC LIMIT 3
supplying the last retrieved id value for the :last_id placeholder.
For example, the previous query returns id values of 214, 212, 211. We "save" the value of 211 on the page. When the user clicks the "more data", then we take that value of 211, and supply it in the "next rows" query.
SELECT ... FROM adatok WHERE id < 211 ORDER BY id DESC LIMIT 3
^^^
This query is guaranteed to not return id values that were retrieved by the previous query. If the execution of this query returns id values of 210, 209, 208... we save that last retrieved id value, 208. A subsequent "next" query would use that saved value...
SELECT ... FROM adatok WHERE id < 208 ORDER BY id DESC LIMIT 3
^^^
And so on.
The OP "next" query is going to skip the fourth row; the first argument to LIMIT should be the number of rows retrieved previously... LIMIT 3,3. (Using LIMIT 4,3 as in the OP query is actually going to "skip" the fourth row.
For the next sets:
... LIMIT 6,3
... LIMIT 9,3
One of the issues with this approach is that if there are any insertions to the table with a larger id value, since the query is ordering by descending id value, a subsequent "next" query has the potential to return a row(s) that were retrieved previously. If rows with higher id values are deleted, this form has the potential to "skip" some id values.
Using a queries of the first form, at the top of my answer, results are unaffected by insertions/deletions of rows with higher id values.
Related
A couple of months ago, I asked a similar question like this and the answer that where given worked for me. I now have another change I would like to add to my page. I would like that each post I create has its own unique div. My page currently looks like this:
the previous question helped me break the div each 3 post, so what I tried was within the if statement that creates a new dive each 3 div was to add another if which would break each 1 div so that each post has its own div and it still breaks to a new div section each 3, maybe I just complicated everything with my description, but I want to get something like:
Here is my code
CSS:
.column {
display: inline-flex;
border: 5px black;
border-style: solid;
padding: 10px;
background: #ffa500;
}
PHP:
else {
$break = 0;
$nRows = $connection->prepare("SELECT post_id, post_title,
post_author, post_file, post_time
FROM posts
ORDER BY post_id DESC");
$nRows->execute();
if($nRows->rowCount() > 0) {
while ($row = $nRows->fetch()) {
$post_title = str_replace('_', ' ', $row['post_title']);
$post_author = $ed->encrypt_decrypt('decrypt',$row['post_author']);
$post_file = $row['post_file'];
$post_date = $row['post_time'];
// Create a new div each 3 columns
if ($break % 3 === 0) {
echo '<br><div class="column"><br>';
}
$break++;
?>
<!-- Blog Content BEGIN Display-->
<div class="box"><?php
// Display the content
$file_parts = pathinfo($post_file);
if(isset($file_parts['extension'])) {
switch ($file_parts['extension']) {
case "jpg":
if(!empty($post_file)) { ?>
<img src="post/postFiles/<?php echo $post_file;?>"><?php
}
break;
case "mp4":?>
<div class="thumbnail">
<video preload="auto" loop muted>
<source src="post/postFiles/<?php echo $post_file;?>">
</video>
</div>
<!-- Preview video on hover -->
<script>
$(document).ready(function () {
$(".thumbnail").hover(function () {
$(this).children("video")[0].play();
}, function () {
var el = $(this).children("video")[0];
el.pause();
el.currentTime = 0;
});
});
</script><?php
break;
case "": // Handle file extension for files ending in '.'
case NULL: // Handle no file extension
break;
}
}
// Title URL Variable
$urlFetchPostId = '<h2><a href="post/postFetch/fetchByTitle/fetchByPT.php?post_id=';
$urlFetchPostTitle = '&post_title=';
$urlFetchPostAuthor = '&post_author=';
echo $urlFetchPostId . $row['post_id'] . $urlFetchPostAuthor. $row['post_author']. $urlFetchPostTitle . $row['post_title'] . '"' . 'class="link-post-title" style="font-family: Arial">' . " ". $post_title . '</a></h2>';
// Author/User URL Variable
$urlFetchPostUser = '<a href="post/postFetch/fetchByAuthor/fetchByPA.php?post_author=';
echo $urlFetchPostUser . $row['post_author'] . '"' . 'class="link-post-author" style="font-family: Arial">' . " ". strtoupper($post_author) . '</a>';
// Posted Date
echo '<br><p style="font-family: Arial">Posted on ' . $post_date . '</p>';
?>
</div><?php
if ($break % 3 === 0) {
echo '<br></div><br>';
}?>
<!-- Blog Content END Display --><?php
}
} else { ?>
<p style="color: darkgoldenrod" class="mssgAlign"><u>NO RECORDS</u></p><?php
}
$nRows = null;
}
Any help, tip or improvement suggestion is welcomed
You want to use margins. Margins specify a buffer around the outside of your container. As opposed to padding, which specifies buffer inside the container. Add this to your css
.column {
display: inline-flex;
border: 5px black;
border-style: solid;
padding: 10px;
background: #ffa500;
margin-left: 20px;
margin-right: 20px;
}
This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 2 years ago.
I am sorry if this is a noob question, but I've been searching all over the internet for an answer and could find nothing that could solve my issue. Anyways, I've taken a look at the php documentation on mysqli_num_rows() (which is https://www.php.net/manual/en/mysqli-result.num-rows.php) since I am trying to find the amount of rows in a column. My table looks like this:
id | follower | followee
1 Xp10d3 IiBlurBeriI
2 IiBlurBeriI Xp10d3
In id number 1, the table shows that IiBlurBeriI has a follower of Xp10d3, and in id number 2 the table shows that Xp10d3 has a follower of IiBlurBeriI. I am trying to get all the subscribers where the username is equal to the profile that is being viewed. Anyways, I used the mysqli_num_rows() method to try and execute this but obviously it doesn't work. I don't get any MySQL errors whatsoever, but when viewing the amount of followers it is blank like this:
Username
followers.
following.
But I want it to look like this:
Username
5 followers.
2 following.
The rest of the MySQL that I used to view the profile worked fine; it was just the follower/following system that I had an issue with. My code is below:
<?php
session_start();
$servername = "localhost"; // Host name
$user = "xxxx"; // Mysql username
$pass = "xxxx"; // Mysql password
$dbname = "xxxx"; // Database name
$tbl_name = "forum_question"; // Table name
// Connect to server and select databse.
$conn = new mysqli($servername, $user, $pass, $dbname);
$userGet = $_GET['username'];
$userGetSQL = "SELECT USERNAME FROM data WHERE USERNAME='".$userGet."'";
$result = $conn->query($userGetSQL);
$userRow = $result->fetch_assoc();
$pfp = "SELECT PFP FROM data WHERE USERNAME = '".$_GET['username']."'";
$pfpresult = $conn->query($pfp);
$pfprow = $pfpresult->fetch_assoc();
$rank = "SELECT LEVEL FROM data WHERE USERNAME = '".$_GET['username']."'";
$rresult = $conn->query($rank);
$followers = "SELECT * FROM subscribers WHERE follower = '".$_GET['username']."'";
$fresult = $conn->query($followers);
$fcnt = $fresult->num_rows;
//echo "FOR TESTING PURPOSES! Followers query: " . $followers . ". Result: " . $fresult . ". num_rows: " . $fcnt . ".";
$following = "SELECT * FROM subscribers WHERE followee = '".$_GET['username']."'";
$ffresult = $conn->query($following);
$ffcnt = $ffresult->num_rows;
//echo "FOR TESTING PURPOSES! Following query: " . $following . ". Result: " . $ffresult . ". num_rows: " . $ffcnt. ".";
$desc = "SELECT DESCRIPTON FROM data WHERE USERNAME = '".$_GET['username']."'";
$descresult = $conn->query($desc);
$descRow = $descresult->fetch_assoc();
if (!isset($_SESSION['username']) && empty($_SESSION['username'])) {
echo 'You are not logged in! Go home to login!';
} else {
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
text-align: center;
font-family: sans-serif;
}
.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
max-width: 300px;
margin: auto;
text-align: center;
}
.title {
color: grey;
font-size: 18px;
}
.msg{
border: none;
outline: 0;
display: inline-block;
padding: 8px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 18px;
}
a {
text-decoration: none;
font-size: 22px;
color: black;
}
.msg:hover, a:hover {
opacity: 0.7;
}
</style>
</head>
<body>
<button type="button" style="cursor:pointer">
Home
</button>
<br />
<?php
$check = mysqli_query($conn, "SELECT * FROM subscribers WHERE follower = '".$_SESSION['username']."' AND followee = '".$_GET['username']."'");
if (mysqli_num_rows($check) > 0) {
?>
<button type="button" style="cursor:pointer">
<a href='unfollow.php?username=<?php echo $userGet ?>'>Unfollow</a>
</button>
<?php
} else {
?>
<button type="button" style="cursor:pointer">
<a href='follow.php?username=<?php echo $userGet ?>'>Follow</a>
</button>
<?php
}
?>
<div class="card">
<?php
if ($pfprow['PFP'] == none.png) {
?>
<img src="<?php echo $pfprow['PFP'] ?>" id="pfp" style="width:100%" />
<?php
} else {
?>
<img src="pfp/<?php echo $pfprow['PFP'] ?>" id="pfp" style="width:100%" />
<?php
}
?>
<h1 id="username"><?php echo $_GET['username'] ?></h2>
<p id="title"><?php echo $rrow['LEVEL'] ?></p>
<p><strong><?php echo $fcount ?></strong> followers.</p>
<p><strong><?php echo $ffcount ?></strong> following.</p>
<div class="desc">
<?php
echo $descRow['DESCRIPTON'];
?>
</div>
<p><button class="msg"><i class="fa fa-envelope-o" aria-hidden="true"></i> Send Message</button></p>
</div>
</body>
</html>
<?php
}
exit();
?>
On a side note, yes I know my code is vulnerable to SQL injection. I am trying to learn how to use prepared statements (I am a new to PHP but have used HTML+CSS for a couple of years) so that I can change my code later on. I don't believe I have any INSERT statements so this should be fine.
Setting aside the SQL injection vulnerabilities that you already mentioned, if you want to know how many rows have, for example, follower = 'some_follower', do a COUNT instead:
SELECT COUNT(1) FROM subscribers WHERE follower = 'some_follower'
Because if you do a SELECT * FROM subscribers WHERE follower = 'some_follower' you are asking the DB to return all the results, while you just want to know the COUNT.
Example in PHP:
$result = $conn->query("SELECT COUNT(1) FROM subscribers WHERE follower = 'some_follower'");
$row = $result->fetch_row();
echo '#: ', $row[0];
I am not great with php/sql - still learning.
I am trying to get it so 5 url's (there are over 20 to chose from) are randomly selected from the user database and displayed on a page. In the event that the user has not filled out all 20+ url's in the members area of our site, I want it to skip the ones they have not filled out.
The problem is it is selecting and displaying 5 whether they are NULL or not and stopping after 5. Its not only counting the ones that are not null.
What do I need to fix, how would I go about this? I pasted the entire code from the page in question - hope its not to much to understand what I need.... like I say I am not that good at this stuff.
<?php
include "config.php";
if ($_GET['r']) {
if($_COOKIE['referid']!=$_GET['r']) mysql_query("UPDATE members SET hits_unique=hits_unique+1,hits_visitor=hits_visitor+1 WHERE userid='".$_GET['r']."'");
else mysql_query("UPDATE members SET hits_visitor=hits_visitor+1 WHERE userid='".$_GET['r']."'");
setcookie('referid', $_GET['r'], time()+365*24*60*60);
setcookie('referrer', $_SERVER['HTTP_REFERER'], time()+365*24*60*60);
}
include 'headsplash.php';
echo '<body style="font-family: "Lato", sans-serif; background-color: black; color: white; height:100%; overflow:hidden;">';
echo '<script src="modernizr-0.9.min.js"></script>';
echo '<canvas id="theapt" style="width:100%; height:100%; position:fixed; top:0;left:0; background-color:black; z-index:-1;"></canvas>';
echo '<center><h1 id="congrats" style="font-size:55px; margin: 0 6px 20px;">'.$_GET['r'].' Recommends</h1></center>';
echo '<div style="margin-bottom:5px; font-size:17px; text-align:center;">';
echo '\'s Downline Builder</h2>';
echo '<div class="wall_back shadow" style="opacity: .9; width:478px; margin: 15px auto 0; border: 1px solid white; border-radius:10px; padding:20px; background-color: #161616;">';
//Get the user links
$ub = array();
$sql = mysql_query("SELECT * FROM builder WHERE userid = '".$_GET['r']."'");
if(#mysql_num_rows($sql)) $ub = mysql_fetch_array($sql);
$lastcat = "";
//Get the links for each site
$slist = mysql_query("SELECT s.*,c.name as catname FROM builder_sites s JOIN builder_cat c ON s.category=c.id ORDER BY RAND() LIMIT 5");
while($each = mysql_fetch_array($slist)) {
$user = $_GET['r'];
$found = 0;
while($found == 0) {
//Referrer exists?
$sql = mysql_query("SELECT m.referid FROM members m JOIN members r ON m.referid = r.userid WHERE m.userid = '".$_GET['user']."'");
if(#mysql_num_rows($sql)) {
$referrer = mysql_result($sql, 0);
$sql = mysql_query("SELECT site".$each['id']." FROM builder WHERE userid = '".$_GET['r']."'");
if(#mysql_num_rows($sql)) {
// Found a row, check if it's empty
$value = mysql_result($sql, 0);
if($value) {
//found a link, end the loop
$links = $value;
$found = 1;
} else {
//No link, next.
$user = $referrer;
}
} else {
//No row, next.
$user = $referrer;
}
} else {
//No more referrers, use default values
$links = $each['url'];
$found = 1;
}
}
if($lastcat != $each['category']) ;
$lastcat = $each['category'];
?>
<table width="50%" cellspacing="5" cellpadding="5">
<tr>
<form method="post"><? echo $each['desc']; ?><input type="hidden" name="sid" value="<? echo $each['id']; ?>">
<br><b><? echo $each['explain']; ?></b>
</form>
</tr>
</table>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41048281-1', 'thedownliner.com');
ga('send', 'pageview');
</script>
<? }
echo '<center><h3><br>Get your FREE downline builder here</button></h3></center>';
echo '</div>';
echo '</div>';
mysql_close($dblink);
?>
I am brand new to php and a beginner with jQuery. I have a php page that is populated with data from a mySQL table. What I am trying to achieve is for the h3 that contains "View Job" to have a unique id assigned to it, as well as the div that prints out the job description. Then, I would like to reference these with jQuery so that if someone clicks View Job, only the description for that job will show. I hope this makes sense.
I tried this with classes and of course all the job descriptions revealed themselves when any View Job was clicked.
I tried the solution here, but this ended up with 36 "View Job" links on my page, and I need to assign the unique ID to the h3 and div as they are created.
I am open to suggestions for another way to achieve what I'm looking for - basically to hide/collapse each description as the user clicks on View Job for each job.
here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div#job-details").css("display" , "none");
$("h3#view-job").click(function() {
$("div#job-details").css("display" , "block");
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
Print "";
while($info = mysql_fetch_array( $data ))
{
Print "<div class='job-post'>";
Print "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
Print "<h3 id='view-job'>View Job:</h3> <div id='job-details'>".$info['jobdesc'] . " </div>";
Print "</div>";
}
?>
</div><!--//END job-container-->
Assign the classNames instead of id's
Then use the this context to select your div which will only search for the one in the context and not all the divs
$("h3.view-job").on('click',function() {
$(this).next("div.job-details").css("display" , "block");
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-details{display:none;}
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
// Please hide this class on CSS
// $("div.job-details").css("display" , "none");
$("h3.view-job").click(function() {
// you ned to use this keyword
// it is very important when you use javascript or jquery
// this keyword only pick element on which you click
$(this).parent().find(".job-details").show();
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs")
or die(mysql_error());
?>
<div id="job-container">
<?php
// First of all Please use echo instead of Print
echo "";
while($info = mysql_fetch_array( $data ))
{
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
// you can't use id multiple time in a same page so instead of id use Class
// if you want to use id then you have to generate uniq id
// check below I generate id --> I don't know your database field that's why I used jobId
echo "<h3 class='view-job' id='job".$info['jobId']."'>View Job:</h3> <div class='job-details'>".$info['jobdesc'] . " </div>";
echo "</div>";
}
?>
</div><!--//END job-container-->
This should do what you want (tested okay). Just replace your mysql login info and the example should work.
I completed your job-details div (it was missing the data from php), but what you were really looking for is the jQuery code.
When an <h3> tag whose id begins with the characters view-job is clicked, the jQuery click event handler will:
re-hide all divs whose id starts with the chars job-details
display the next div in the DOM tree
CODE:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style type="text/css">
.job-post{border-bottom: 1px solid red; padding: 0; margin: 10px 0;}
h3, p{padding: 0; margin:0;}
.view-job{cursor: pointer;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("div[id^='job-details']").css("display" , "none");
$('h3[id^="view-job"]').click(function() {
$("div[id^='job-details']").hide(500);
$(this).next('div').show(500);
});
});
</script>
<?php
// Connects to your Database
mysql_connect("xx", "xx", "xx") or die(mysql_error());
mysql_select_db("lcwebsignups") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
$data = mysql_query("SELECT * FROM openjobs") or die(mysql_error());
?>
<div id="job-container">
<?php
echo "<br>";
while($info = mysql_fetch_assoc( $data )) {
echo "<div class='job-post'>";
echo "<h3>Position / Location:</h3> <p>".$info['jobtitle'] . ", ".$info['joblocation'] . "</p>";
echo "<h3>View Job:</h3> <div id='job-details'>".$info['jobdetails']."</div>";
echo "</div>";
}
?>
</div><!--//END job-container-->
what i want is when a user clicks a link it should automatically create two text box's at a time and from which we can click and create unlimited numbers of textboxs which when submitted it should save all the dynamically created textbox two text box's in a row.
meaning textboxA textboxB
in this manner......
I found a code on net which works very similar to that how i wanted...but instead of two textboxs it creates only one textbox at a time when clicked the link First i'll give u the full original code...
1) index.php
<?php
//Include the database class
require("classes/db.class.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery</title>
<script type="text/javascript" src="js/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="css/css.css" />
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /><br />' );
});
});
</script>
<body>
<?php
//If form was submitted
if (isset($_POST['btnSubmit'])) {
//create instance of database class
$db = new mysqldb();
$db->select_db();
//Insert static values into users table
$sql_user = sprintf("INSERT INTO users (Username, Password) VALUES ('%s','%s')",
mysql_real_escape_string($_POST['name']),
mysql_real_escape_string($_POST['password']) );
$result_user = $db->query($sql_user);
//Check if user has actually added additional fields to prevent a php error
if ($_POST['fields']) {
//get last inserted userid
$inserted_user_id = $db->last_insert_id();
//Loop through added fields
foreach ( $_POST['fields'] as $key=>$value ) {
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_URL) VALUES ('%s')",
mysql_real_escape_string($value) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
//Insert into users_websites_link table
$sql_users_website = sprintf("INSERT INTO users_websites_link (UserID, WebsiteID) VALUES ('%s','%s')",
mysql_real_escape_string($inserted_user_id),
mysql_real_escape_string($inserted_website_id) );
$result_users_website = $db->query($sql_users_website);
}
} else {
//No additional fields added by user
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> website(s) added for this user!</h1>";
//disconnect mysql connection
$db->kill();
}
?>
<?php if (!isset($_POST['btnSubmit'])) { ?>
<h1>New User Signup</h1>
<form name="test" method="post" action="">
<label for="name">Username:</label>
<input type="text" name="name" id="name" />
<div class="spacer"></div>
<label for="name">Password:</label>
<input type="text" name="password" id="password" />
<div class="spacer"></div>
<div id="container">
<p id="add_field"><span>» Add your favourite links.....</span></p>
</div>
<div class="spacer"></div>
<input id="go" name="btnSubmit" type="submit" value="Signup" class="btn" />
</form>
<?php } ?>
</body>
</html>
2) db.class.php
<?php
class mysqldb {
/*
FILL IN YOUR DATABASE DETAILS BEFORE RUNNING THE EXAMPLE
*/
var $hostname = "localhost";
var $username = "root";
var $password = "mypassword";
var $database = "unlimited";
function db_connect() {
$result = mysql_connect($this->hostname,$this->username,$this->password);
if (!$result) {
echo 'Connection to database server at: '.$this->hostname.' failed.';
return false;
}
return $result;
}
function select_db() {
$this->db_connect();
if (!mysql_select_db($this->database)) {
echo 'Selection of database: '.$this->database.' failed.';
return false;
}
}
function query($query) {
$result = mysql_query($query) or die("Query failed: $query<br><br>" . mysql_error());
return $result;
mysql_free_result($result);
}
function fetch_array($result) {
return mysql_fetch_array($result);
}
function num_rows($result) {
return mysql_num_rows($result);
}
function last_insert_id() {
return mysql_insert_id();
}
function kill() {
mysql_close();
}
}
?>
3) css.css
html, input {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 0.8em;}
body { width: 500px; margin: 50px auto 0 auto; display: block;}
h1 { font-size: 1.5em; color: #333; }
input { font-size: 0.9em; padding: 5px; border: 1px solid #ccc; margin: 0; display: block;}
a { text-decoration: none; color: #666; font-weight: bold; }
a:hover { color: #ff0000; }
#divTxt { width:400px; padding: 5px; }
p a img { border: none; vertical-align: middle; }
.spacer {clear: both; height: 10px; }
.btn { width: 90px; font-weight: bold; }
#container { border: 1px solid #ccc; padding: 2px; }
.clear {overflow: hidden;width: 100%;
}
4) JQUERY.js
With this code i am only allowed to dynamically create one textbox when clicked the link as i said earlier, so to make it for my use as i wanted to have two textbox's i have edited the jquery part in the index.php page as below...
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<label for="fields[]' + '">Colour</label><input id="field_' + count + '" name="fields[]' + '" type="text" /><label for="fields2[]' + '">Quantity</label><input id="field2_' + count + '" name="fields2[]' + '" type="text" /><br />');
});
});
</script>
Till here i am successfull... but the main problem is I cannot save them both the two textbox's in a row in mysql table..
Please review this code and reply me if u get any answers.....
I'll surely click the green arrow for the working answer as accepted answer..
Please HELP guys......
Try this
jQuery
<script type="text/javascript">
var count = 0;
$(function(){
$('p#add_field').click(function(){
count += 1;
$('#container').append(
'<strong>Link #' + count + '</strong><br />'
+ '<label for="field_'+count+'_1">Name</label><input id="field_'+count+'_1" name="fields[]['name']" type="text" /><label for="field2_'+count+'_2">URL</label><input id="field2_'+count+'_2" name="fields[]['url']" type="text" /><br />');
});
});
</script>
PHP
//Insert into websites table
$sql_website = sprintf("INSERT INTO websites (Website_Name,Website_URL) VALUES ('%s','%s')",
mysql_real_escape_string($value['name']),
mysql_real_escape_string($value['url']) );
$result_website = $db->query($sql_website);
$inserted_website_id = $db->last_insert_id();
I am assuming that the 1st column is Website_Name and the 2nd column is Website_URL
P.S. : You've said it creates two text boxes, which means there should be two table fields where you want to add those two values. But in your MySQL query, there is only one column insert.
"INSERT INTO websites (Website_URL) VALUES ('%s')"
Specify the 2nd column name to answer your question correctly.