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

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?

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

php mysql show result one after another

I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck

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.

Create a table with blank squares for missing mysql data

I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.

not retrieving id from browser url when clicking on back button

I found a problem in my code, when I want to remove a user from database, it has to remove him, the code for removing works perfect, but afterwards, the if condition shows that the user has been removed and I have a Back button there, I click on it and it should redirect me back to the classroom with the rest of the users in it. Classroom is identified by ID of course, but when I click on Back, it shows me classroom without an ID of a class...so its not getting ID...
// get value of id that sent from address bar
$id_student=$_GET['id_student'];
$id_trieda = $_GET['id_triedy'];
// Delete data in mysql from row that has this id
$zmaz='DELETE FROM $tbl_name WHERE id_student="'.$id_student.'" AND id_triedy="'.$id_trieda.'"';
mysqli_real_escape_string($prip, $zmaz);
$row = mysqli_query($prip,$zmaz);
// if successfully deleted
if($row){
echo "Študent bol úspešne vymazaný.";
echo "</br>";
echo "<a href='./trieda.php?id_triedy=".$_GET['id_triedy']."'>Späť do triedy<a/>";
}
else {
echo "Chyba";
}
?>
EDIT:
// get value of id that sent from address bar
$id_student=$_GET['id_student'];
// Delete data in mysql from row that has this id
$zmaz="DELETE FROM $tbl_name WHERE id_student='$id_student'";
$result=mysql_query($zmaz);
// if successfully deleted
if($result){
$id_trieda = $_GET['id_triedy'];
echo "Študent bol úspešne vymazaný.";
echo "</br>";
echo "<a href='./trieda.php?id_triedy=".$id_trieda."'>Späť do triedy<a/>";
}
else {
echo "Chyba";
}
here is edited code which is similar to one that is working when I add a student into the class and then there is a Back button again, but it works....so problem will be in deleting the student, it cant find the ID of class he was in..i think..but I have no idea how to get the ID of the class before he is removed..
Looking at the page you linked to in your comment, I see the problem - you aren't passing id_triedy in your zmazat link. It reads:
http://www.xxx.xx/project/zmazat_studenta.php?id_student=15
Where it should read:
http://www.xxxx.xx/project/zmazat_studenta.php?id_student=15&id_triedy=18
(or whatever the relevant id_triedy is).
Then the $_GET['id_triedy'] in your question code actually has something to get.
You should really build in a check for this kind of thing:
if(isset($_GET['id_triedy'])){
$id_trieda = $_GET['id_triedy'];
} else {
echo 'No trieda ID';
}
This will check the URL for id_triedy and tell you if it's not there.
Is the trieda.php the file that contains the Classroom? If so, this line should be amended:
echo "<a href=\"./trieda.php?id_triedy=".$_GET['id_triedy']."&id_student=".$_GET['id_student']."\">Späť do triedy<a/>";
It looks like you left out the id_student in the URL

Categories