pagination and url encoding help - php

<?php $name=$_POST['name']; ?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name">
<input type="submit" value="GO" name="submit">
</form>
<?php
include ('db.php');
if(isset($_POST['submit']))
{
mysql_query ("INSERT INTO example (name) VALUES('$name')") or die(mysql_error());
}
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
}
else {
$startrow = (int)$_GET['startrow'];
}
$query = "SELECT * FROM example ORDER BY id DESC LIMIT $startrow, 20";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<li>";
echo $row['name'] ." "." <a href= 'like.php?quote=" . urlencode( $row['name'] ) . "'>Click Here</a>";
echo "</li>";
}
echo 'Next';
?>
I want to make my page links hidden , how can i make then hidden so that a user cant edit it.
2nd question,
currently i am showing total 10 records on each page and then a next page button , but the next button is keep showing even when there is no more records...! how to remove a next page button when records ended. ??
line number 28 is the link to pages which can be easyily editable by any user, i wnat to make them secure (using ID)
and line 35 is n'next' page link , this link should not be appear when number of records ended

I can't think of a reason why you really should hide the page numbers from the user in the link. Keeping them in the query string as $_GET variables is probably the most common practice i know of in this specific case of paging.
I would do validation on the numebrs being recieved in the $_GET variables, since this could often lead to SQL Injection and other problems... Make sure it's a number, possibly divisible by 10 (if that's how you like the site to be), perhaps not bigger than a certain defined number, etc...
If you REALLY still don't agree, and you want to hide it, then you could always do that by saving cookie on the user's computer (this is still exposed to user in some way) or save the page number in the session (although this seems like a big waste of server resources to me!).
About your second question - There are so many possibilities to this...
Here's one way :
Create an sql query that queries how many rows are there to your table.
Let's say the number is 55. You put that into a hidden value.
If you're displaying 10 items on a page then you know the last page is number 6 (showing items 50-55, if you start counting at page number 1).
Simple php check when page loads: if ($_GET['page'] == 5) then you don't display the next button.
something like this (skipping out validation checks and the sql query) :
<input type="hidden" value="<?php echo $itemCount;?>">
<?php
if ($_GET['page'] < ($itemCount \ 10))
{
echo "<a href=\"items.php?page=".($_GET['page']+1)."\">";
}
?>
Using this, I would add a check to make sure the user doesn't enter a number bigger than this number as well, and if they do, just redirect them to the last number they can.

Related

How to INSERT multiple rows with multiple values, but only for items that have checkboxes ticked next to them

I am coding a discography tool for a music database.
Artists are able to insert tracks, singles, EPs, and albums all into separate tables on the database.
Having tracks be in their own separate table allows the same tracks to be attached to multiple singles, EPs and albums while only requiring there to be one record for that track in the database.
Which means individual track pages can have an automatically generated list of links back to the Singles, EPs and albums that they appear on. Making navigating the database through the website a much smoother experience.
I have come to the point where I am coding a tool to attach any existing tracks in the database for a given artist onto an album page.
I am using another table in the database called 'trackconnections' to create the relational links between the track ids from the track table and the album id from the album table, with an additional column called albumtracknum available to be able to output the tracks in the right order when queried on the album page.
The code for the tool is behind a button labelled 'Attach existing track(s) to album'. The code for this tool is as follows:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
while ($row = $stmt->fetch())
{
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknum'>Track number:</label><br>
<input type='text' name='albumtracknum[]'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
<?php }
else {
header("Location: /index.php");
exit();
}?>
(NB: The post data here is not sanitised for the sql query as it has been passed along in a hidden form from the original album page)
This generates a page with all track names for the current artist available on a list with checkboxes, with each track name being followed by a data entry box to enter the track number for the album being added to.
Submission of the form then hands off to the following include code:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumtracknum = implode(',',$_POST['albumtracknum']);
$albumidforreturn = $_POST['albumidforreturn'];
// echo 'albumid: '.$albumid.'<br>';
// echo 'trackid: '.$trackid.'<br>';
// echo 'albumtracknum: '.$albumtracknum.'<br>';
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackid,$albumtracknum]);
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
(NB: The commented out echos are there to test what the output is from the previous form)
The 2 problems I am having are that my 'Attach existing tracks to album' form submit:
1. Passes on too much data.
The generated form should only pass on the track ids, album number, and track numbers that have had their checkboxes ticked. For insertion into the 'trackconnections' table.
Instead it narrows down the ticked checkbox track ids only and then creates comma separated values for every available track to select, rather than just those actually selected.
Which leads to annoying outputs such as the following when passing on data from form to include:
albumid: 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4
trackid: 30,14
albumtracknum: ,2,3,,,,,,,,,,,,,,,,,,,,,
Where it should only read as:
albumid: 4,4
trackid: 30,14
albumtracknum: 2,3
Having too much data get passed through means that the row inserts won't be correct on multiple INSERTS once I do get this working, as they won't align with one another in the correct order.
2. The include only INSERTS 1 row to the 'trackconnections' table.
It seems I am misunderstanding how to add multiple rows to the database with my code here.
As having multiple checkboxes ticked on my 'Attach existing tracks to album' form only inserts 1 single row to the database on submission of the form each time.
Consistently the only track that gets added to the 'trackconnections' table is the first track with its checkbox ticked and, because of issue no. 1 above, the albumtracknum is always 0 unless I type a number into the first albumtracknum box on the available checklist.
I need to make tweaks to this code so that both problem 1 and 2 are addressed together, meaning that ticking the checkboxes & adding track numbers into each box following the track names actually adds multiple rows to the database along with their corresponding album track numbers.
I hope someone can help.
EDIT TO SHOW REFINED AND WORKING CODE:
New code for checkbox and textbox sections -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
while ($row = $stmt->fetch())
{
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknumber'>Track number:</label><br>
<input type='text' name='albumtracknumber_".$row['id']."'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
</form>
<?php }
else {
header("Location: /index.php");
exit();
}
New code for the include INSERT processing -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumidforreturn = $_POST['albumidforreturn'];
foreach($_POST['trackid'] as $trackidloop) {
$albumtracknum = $_POST["albumtracknumber_{$trackidloop}"];
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackidloop,$albumtracknum]);
}
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
This isn't an entire solution but I see some problems:
You are looping through tracks and creating a new form for each one. The first problem is , you are missing the closing form tag. I guess the browser is automatically creating one, when it sees the next form start tag. ?? That's why you only get one single posted checkbox.
I would put all the track checkboxes into a single form. Then the posted trackid[] array will contain all the checked items.
[EDIT after your comment: The hidden fields albumid[] post the entire array, whereas the trackid[] checkboxes only post the actual checked boxes (HTML spec).
Instead of having albumid[], You could put the trackID and albumID together for the checkbox value, then parse them apart when you handle the post:
$value = $row['id']. ',' . $row['albumid'];
echo "<input type='checkbox' name='trackid[]' value='".$value."' />";
ALSO, the SQL, "INSERT INTO (..) .. VALUES (...) " only inserts one row.
It's easy to do that SQL in a loop for all the checked boxes.
foreach($_POST['trackid'] as $value) {
// parse the $value...
// SQL Insert...
}
EDIT 2: From my own comment:
Like hidden fields, input (text) field arrays also post the entire array (with empty values for blank inputs). (Again, this is not a PHP thing, it's a web browser standard to only post checked checkboxes and radio buttons. But ALL text and hidden INPUTs are posted.) So in your example, you need to code a mechanism to know which textbox goes with each checkbox. Quick and dirty...You could add a row index (0,1,2,3...) as another comma-separated number in your checkbox values, then you'll have the index into the posted textbox array. Alternatively, you could name the textboxes ' .. name="textinput_' . $row['trackid'] . '" ...' (not an array), then upon post, read them in your foreach loop with
$val = $_POST["textinput_{$trackid}"];

dropdown from MySQL database

Having solved the populating the dropdown from the array, the next phase of my project is pulling data from a database to allow users to put limits on the data they want to see.
Again, I'm having trouble populating the dropdown. This time however, the problem seems to be that when I put the HTML interspersed with the PHP, the whole thing stops- the form loads, but nothing goes into the drop down.
Here's the code.
//Step One: Query the DB, and get a list of monthly reports
$sql = "SELECT Report_Text, Report_Date FROM ADM_8_Reports_List";
$result = $conn->query($sql);
//print_r ($result);
$reports_in_db = mysqli_fetch_all($result,MYSQLI_ASSOC);
if (sizeof($reports_in_db) > 0)
{
print_r ($reports_in_db);
echo "\n";
//Now, like the front page, create a form and populate it.
?>
Choose a Monthly Report <select name = "monthly_report">
<?php
foreach($reports_in_db as $row)
{
echo 'option value"' . $row ["Report_Date"] . '">' . $$row ["Report_Date"] . " " . $row ["Report_Text"] . '</option>';
}
}
else
{
echo "I'm sorry, there's no data here. Please start again\n";
} ?>
</select>
<input type="submit" name="monthly report" value="Retrieve Report"">
the output
what it looks like is happening is that the code is freezing where I'm interpolating the HTML and PHP, and actually creating the dropdown.
basically on the previous page, the user can choose one of 4 things to do. On this page, there's an if statement based on $_POST from the previous page. Depending on the choice, the databased will be polled to get, in this case, a list of all the monthly reports. I've copied exactly the structure of what I did on the first page (where I was going from an associative array I hard-defined). I can't figure out what's wrong with the declaration of the dropdown, but that's where the thing's .. well stopping.
I am really annoyed by this.
I forgot '<'when declaring the option. And didn't see it until I posted the question here.
Sorry.

Writing single page logging tool in php

Im making a small php webpage which I plan to use to track on which subjects a helpdesk receives calls. My database has 3 important fields: id, name, and amount for each subject.
On my page I have a form with a dropdown list where you select a type of call and click submit. The idea is that every time you click submit the page reloads and the amount in the database for the chosen id is heightened by 1.
The form gives me the id and name for each call:
<form method="post" action="index.php">
<select class="select" id="calltype" name="calltype">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value=".$row["ID"].">".$row["NAAM"]."</option>".PHP_EOL;
}
}
?>
</select></br>
<input class="input" type="submit" name="Submit" value="Submit">
</form>
This part works, if I echo $_POST['calltype'] I get the correct ID. What I can't get to work is the update statement which I want to heighten the counter, like:
if(isset($_POST['calltype']{
mysqli_query("UPDATE calls SET amount=(amount+1), WHERE id = $_POST['calltype']");
}
How would I go about this? I tried several methods but can't get it to work
besides for the extra comma, interpolation with the POST array like this is risky. maybe try:
mysqli_query("UPDATE calls SET amount=(amount+1) WHERE id = " . mysqli_real_escape_string($link, $_POST['calltype']) . " ;");

GET POST mysql data on next page

Ok, I haven't done much of this sort of stuff, so I am clueless right now.
On the first page you hit the form submit that generates a bunch of information/stuff and displays it underneath submit button, but I don't know how to take the displayed information and use it on the next page I will show some of my code. btw I know the code is bad, just ignore that fact.
<form name="input" action="slaymonster.php" method="post" id="id">
<div align="center">
<input name="Submit" id="Submit" type="submit" class="button" value="Explore Map!"/>
</div>
</form>
if (isset($_POST['Submit'])) {
include 'includes/mapstuff.php';
// So here we pick a random row from the table pokemon notice the order by rand
$sql23 = "SELECT * FROM map1pokemon ORDER BY RAND() LIMIT 1;";
// We then check for errors
$result23 = mysql_query($sql23) or die(mysql_error());
// we then make the result into a virable called battle_get23
$battle_get23 = mysql_fetch_array($result23);
$sql2 = "SELECT * FROM pokemon WHERE name='".$battle_get23['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
// Now we need to make sure the image is safe be for we use it
$pic2= mysql_real_escape_string($battle_get2['pic']);
$pic = strip_tags($pic2);
include 'includes/maptypes.php';
?>
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
<p></p>
<?php
echo "You have just found a " ;
echo $randomview97[0];
echo " ";
echo $battle_get23['pokemon'];
$_SESSION['pokemon'] = $battle_get23['pokemon'];
$_SESSION['type'] = $randomview97[0];
$_SESSION['pic'] = $battle_get2;
$_SESSION['money'] = $randomview2[0];
$_SESSION['level'] = $randomview3[0];
$_SESSION['ticket'] = $randomview4;
?>
<p></p>
<?php
echo "You have gained ".$randomview3[0]." levels" ;
echo " ";
?>
<p></p>
<?php
echo "You have received $".$randomview2[0]."" ;
echo " ";
?>
<p></p>
<?php
echo "</center>";
}
?>
it displays the pokemon's picture it's name, type,amount of money you got ect...
I need all that information to be useable on the next page.
Any help is appreciated :)
At the top of your PHP code, be sure to include session_start();
You are already using session variables, so you should refer here to see what a PHP session is: PHP session_start() - Manual. It makes sure to do exactly what you are asking for (someone may point out that in certain cases session_start(); is not necessary, but for your purposes, while learning, stick to the Manual for best practices)
This information will be usable on the next 'page', just as the manual describes, and will be available, until you call something like session_destroy().
If you want to pass the information from one page to another. You have to put the result inside the form tag. Then it is possible to pass the information to another page. Or you can put it on the session and get information from any page.
you got my point? If you explain what you want to do. Then I will do something for you.

Knowing which <li> item is selected using PHP and mySQL

I have 2 questions. One is if there is any error in this code.
The 2nd question I want to ask is how do you know which <li> item is selected. Right now, the code performs a search in mySQL for all rows that matches city, language and level and returns the results in a list item.
I want it so that when the user clicks on anyone of the list items, it will goes into another page displaying a more detail description by querying the selected list item.
I have a guess, which is for step 2, I also grab the ID (primary key) for each row and somehow keep that stored within the list but not echo.. Would I need to wrap <a> in <form action="XX.php" method="get">?
<?php
//1. Define variables
$find_language = $_GET['find_language'];
$find_level = $_GET['find_level'];
$find_city = $_GET['find_city'];
//2. Perform database query
$results = mysql_query("
SELECT name, city, language, level, language_learn, learn_level FROM user
WHERE city='{$find_city}' && language='{$find_language}' && level='{$find_level}'", $connection)
or die("Database query failed: ". mysql_error());
//3. Use returned data
while ($row = mysql_fetch_array($results)){
echo "<li>";
echo "<a href=\"#result_detail\" data-transition=\"flow\">";
echo "<h3>".$row["name"]."</h3>";
echo "<p>Lives in ".$row["city"]."</p>";
echo "<p>Knows ".$row["level"]." ".$row["language"]."</p>";
echo "<p>Wants to learn ".$row["learn_level"]." ".$row["language_learn"]."</p>";
echo "</a>";
echo "</li>";}
?>
Your code looks alright from what I can see. Does it not work?
One way would be to get the ID through your SQL-query as well and then add the id to the href in your link. Then you can fetch it through the querystring on the other page, to display the proper post depending on which li-element the user clicked on:
echo "<a href=\"details.php?id=". $row["id"] ."\" data-transition=\"flow\">";
Not sure how you mean "somehow keep that stored within the list but not echo" - it wouldn't be possible to store anything in the list, if it is not echoed, as it then wouldn't be sent to the client. You can of course store the id in a data-attribute on the li-element, which won't be displayed to the user. It will however be visible through the source code! Don't know why that should be a problem though?

Categories