Loop sql-php conditional 5 times then exit - php

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);
?>

Related

Nothing is being echoed when using mysqli_num_rows() [duplicate]

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];

how to show different number of records until a submit button is pressed in php

I just want that if a user enters the name of item in text box then particular details from database should be displayed on the same page in a table below. Right now its working for one item. Now if a user wants to select multiple items and want to show record of each selected item on the page until a submit button is not pressed. Here is my code. Any help will be appreciated.
<html>
<head>
<title>Sales</title>
<script>
function search(string){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("search").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "sales_search.php?s="+string, true);
xmlhttp.send(null);
}
</script>
</head>
I have not included the CSS code to shorten it.
<?php
include "connection.php";
function sales_result()
{
$submit = $_GET['finish'];
if(isset($_GET['mname']) && $_GET['mname'] != '')
{
$name = $_GET['mname'];
$sql = "SELECT * FROM `medicine_item_record` WHERE `medicine_item_name` LIKE '%$name%'";
$result = mysqli_query($GLOBALS['link'],$sql);
$row = mysqli_fetch_assoc($result);
while($check =='submit')
{
echo strtoupper($row['company_name']);
}
}
}
?>
<body>
<div style="text-align: center; width: 500px; margin: 0 auto;">
<h1>Sales</h1><span style="font-family: tahoma, sans-serif, arial; margin-left: 150px; font-size: 13px;"></span><br/><br/>
<table border=1>
<tr><td><input type="text" placeholder="Type to search.." onkeyup="search(this.value)" id="text" ></td>
<td><input type="text" placeholder="Enter Quantity" name="quantity" id="text"></td>
<td><input type ="submit" name="finish" value="finish"></td>
</tr>
</table>
<div id="search">
</div>
</div>
<table border=1 width='100%' align= 'center'>
<tr><?php sales_result() ?> </tr>
</table>
</body>
</html>
code for sales_search.php is as follows:
<?php
include "connection.php";
if(isset($_GET['s']) && $_GET['s'] != '')
{
$s = $_GET['s'];
$sql = "SELECT * FROM `medicine_item_record` WHERE `medicine_item_name` LIKE '%$s%'";
$result = mysqli_query($link,$sql);
while($row = mysqli_fetch_array($result))
{
$name = $row['medicine_item_name'];
echo "<div style='' id='searchtitle'>"."<a style='font-family: verdana; text-decoration: none; color: black;' href='sales.php?mname=$name'>" . $name . "</div>";
}
}
?>
Not sure what you mean by Multiple Items. Taking a stab that you mean if the user enters different search terms? For example: "depressor, swab". You would need to parse this in some way before building your Query. If your separator (my example it's the comma) is in the string, explode it and then make your query using a loop:
<?php
include "connection.php";
if(isset($_GET['s']) && $_GET['s'] != ''){
$search_str = trim($_GET['s']);
if(strpos($search_str, ",")){
// Multiple Search Terms found
$s = explode($search_str, ",");
$sql = "SELECT * FROM `medicine_item_record` WHERE `medicine_item_name` LIKE '%" . mysqli_real_escape_string(trim($s[0]), $con) . "%'";
for($i=1;$i<count($s);$i++){
$sql .= " OR `medicine_item_name` LIKE '%" . mysqli_real_escape_string(trim($s[$i]), $con) . "%'";
}
$sql .= ";";
} else {
$sql = "SELECT * FROM `medicine_item_record` WHERE `medicine_item_name` LIKE '%" . mysqli_real_escape_string($search_str, $con) . "%';";
}
$result = mysqli_query($link,$sql);
while($row = mysqli_fetch_array($result)){
$name = $row['medicine_item_name'];
echo "<div style='' id='searchtitle'>"."<a style='font-family: verdana; text-decoration: none; color: black;' href='sales.php?mname=$name'>" . $name . "</div>";
}
}
?>
Edit after your comment:
That is happening in the response of your AJAX call:
document.getElementById("search").innerHTML = xmlhttp.responseText;
This line of code replaces the content in that element. You will want to append the response:
var current = document.getElementById("search").innerHTML;
document.getElementById("search").innerHTML = current + xmlhttp.responseText;

How can I auto increment mysql LIMIT number?

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.

Increment a value in a sql database when a pdf link is downloaded on a webpage

I'm creating an eBook account on my website: where customers can have a library of ebooks and every time an eBook is downloaded, I need to add 1 to the database for the client to be able to see the number of downloads. I can not figure out the line of code I would need for this and I have done research but nothing can help with this specific query. This is what I have so far, which pulls the information from a sql table and display in html table:
<p>List of Publications</p>
<?php
//connect
$query = "SELECT * FROM AccountTest";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
?>
<table style="width: 80%; border:2px #be9c81 dashed; padding:10px 10px 10px 10px"align="center" >
<tr>
<td> <?php if ($numrows > 0){
while($row = mysql_fetch_array($query))
{
?>
<a href="<?php echo $row['Link']; ?>" target="_blank">
<img style="padding:20px 20px 20px 20px" alt="" src="<?php echo $row['Image']; ?>" /></a> <?php
}
} else
echo "Wrong Query";
?>
</tr>
You could use JQuery
ebookDownloads.php
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="javascript/text">
// JavaScript Document
function Downloaded(id) {
var data = {'id':id};
$.post( "downloaded.php", data);
}
</script>
</head>
<p>List of Publications</p>
<?php
//connect $query = "SELECT * FROM AccountTest";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
?>
<table style="width: 80%; border:2px #be9c81 dashed; padding:10px 10px 10px 10px"align="center" >
<tr>
<?php
if ($numrows > 0){
while($row = mysql_fetch_array($query)) {
?>
<td><img style="padding:20px 20px 20px 20px" alt="" src="<?php echo $row['Image']; ?>" /></td>
<?php
}
} else {
echo "Wrong Query";
}
?>
</tr>
</table>
downloaded.php
if(isset($_POST['id']) && is_numeric($_POST['id'])) {
$sql = "UPDATE table SET downloaded=downloaded+1 WHERE id = $_POST['id']";
}
EDIT: I have not tested this code. Also the user might not have javascript enabled in which case it wouldn't count the download, so if you need to count the downloads (e.g they pay for so many) you could make sure they have javascript enabled before showing the downloads.
Update: another method using a new tab and PHP to record the download then present it
<p>List of Publications</p>
<?php
//connect $query = "SELECT * FROM AccountTest";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
?>
<table style="width: 80%; border:2px #be9c81 dashed; padding:10px 10px 10px 10px"align="center" >
<tr>
<?php
if ($numrows > 0){
while($row = mysql_fetch_array($query)) {
?>
<td><img style="padding:20px 20px 20px 20px" alt="" src="<?php echo $row['Image']; ?>" /></td>
<?php
}
} else {
echo "Wrong Query";
}
?>
</tr>
</table>
<?php
######## download.php #######################
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
$query = "SELECT * FROM ebooks WHERE id = $_GET['id']";
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
$sql = "UPDATE table SET downloaded=downloaded+1 WHERE id = $_POST['id']"; // update downloaded
while($row = mysql_fetch_array($query)) {
header('Content-Type: application/pdf');
header('Content-disposition: attachment;filename='.$row['name'].'pdf');
readfile($row['link']); // should be an absolute path
}
}
}
?>

$_POST variable is duplicating

I do not even know how to google this one...imagine it is something stupid...but any help would be great...
passing a variable when submitting a form...when echo the $_POST it is good...but when i put it into a php variable it is duplicated
<?
//list transactions by month
if ($_POST['m']=="yes"){
$table = $_POST['month'];
$_SESSION['table']=$_POST['month'];
$conn = mysql_connect("localhost", "mss_records", "3205") or die(mysql_error());
mysql_select_db('store_records', $conn) or die(mysql_error());
$result = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_array($result))
{
$id=$row['transaction'];
$date=$row['date'];
$time=$row['time'];
$paid=$row['payment'];
$total=$row['total'];
echo '<style type="text/css">
<!--
.list {
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 12px;
color: #000;
padding: 2px;
border: 2px solid #009;
}
.view {
width: 100px;
}
-->
</style>
<div class="list">
<p><span style="color: #900">Transaction #</span>'.$id.'
<span style="color: #900">Date:</span>'.$date.'
<span style="color: #900">Time:</span>'.$time.'<span style="color: #900">
Paid By:</span>'.$paid.' <span style="color: #900">Total:</span>'
.number_format($total, 2).'
<form name="form1" method="post" action="find.php">
<label>
<input type="submit" name="view" id="view" value="'.$id.'">
</label>
</form>
</p>
</div>
<p></p>';
}
}
//view transaction after viewing by month
if (isset($_POST['view'])){
$conn = mysql_connect("localhost", "mss_records", "3205") or die(mysql_error());
mysql_select_db('store_records', $conn) or die(mysql_error());
$table = $_SESSION['table'];
echo "this is the number ".$_POST['view'];
$post=$_POST['view'];
echo "this is the post ".$post;
$result = mysql_query("SELECT * FROM $table WHERE transaction = '$post'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$items=$row['transaction'];
}
echo $items;
}
?>
after the user goes through the first selection and on the second window the output is...
this is the number 46this is the $post 4646
Your query is mysql_query("SELECT * FROM $table WHERE transaction = '$post'"). Therefore the value of $items=$row['transaction']; is also going to be 46. When you echo out everything without line breaks, it smashes everything together.
POST is not duplicating anything, you are just echoing $items directly after it.
Try this:
$table = $_SESSION['table'];
echo "this is the number ".$_POST['view']."<br /> \n";
$post=$_POST['view'];
echo "this is the post ".$post."<br /> \n";
$result = mysql_query("SELECT * FROM $table WHERE transaction = '$post'")
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$items=$row['transaction'];
}
echo $items;
}

Categories