Populate input values with PHP variables with related ID - php

I am trying to create a form when the user clicks a button on a selected element. However, when i try it, i click a button and it either loads multiple, or loads 1 but shows only one value, if that makes sense. Here is my code:
<?php
$sql = "SELECT * FROM services";
$result = $database->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
?>
<div class="service_display">
<div class="service_header"><?php echo $row['service_name']; ?></div>
<div class="service_desc"><?php echo $row['service_desc']; ?></div>
<div class="service_options">
<button type="button" class="additional_files" id="additional_files">Edit</button>
</div>
</div>
<?php
}
?>
I have a form that will appear with jQuery when the button is pressed, and im trying to fill the values with the respective id's. Here is my code for that:
<div class="show-onclick">
<h3>Edditing service: <?php echo $row['service_name']; ?></h3>
<hr>
<form action="inc/save_edit.php?id=<?php echo $row['id']; ?>" class="service_editform">
<input type="text" name="service_name" value="<?php echo $row['service_name']; ?>">
<textarea><?php echo $row['service_desc']; ?></textarea>
</form>
</div>
I think the problem is me not knowing where to put that code, if i put it in the while loop, it works, but understandably, i have like 10 input fields pop up..
if i put it outside the while loop and run a separate query to fill it, its empty..

As per you explanation of the problem its clear that you are looping the forms along with the front end display divs, which is not that good idea.
Always its better to use one modal window and then depending upon the click you have to load the data onto it and then pop it up.
Anyway for your scenario there may be more than one solution but this one will also serve the purpose:
Put the "show-onclick" whole div inside the "service_display" div so that now also it gets looped with no issues.
Now when the button gets clicked find the closest "service_display" div, it will give you the dom element & then use that and popup the "show-onclick" div enclosed within that.
Follow the code below:
<?php
$database = new mysqli("localhost", "root", "", "so");
$sql = "SELECT * FROM services";
$result = $database->query($sql);
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
?>
<div class="service_display" id="sd_<?php echo $row['id']; ?>">
<div class="service_header"><?php echo $row['service_name']; ?></div>
<div class="service_desc"><?php echo $row['service_desc']; ?></div>
<div class="service_options">
<button type="button" class="additional_files" id="additional_files">Edit</button>
</div>
<div class="show-onclick">
<h3>Edditing service: <?php echo $row['service_name']; ?></h3>
<hr>
<form action="inc/save_edit.php?id=<?php echo $row['id']; ?>" class="service_editform">
<input type="text" name="service_name" value="<?php echo $row['service_name']; ?>">
<textarea><?php echo $row['service_desc']; ?></textarea>
</form>
</div>
</div>
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".show-onclick").css("display", "none");
$(document).on("click", ".additional_files", function() {
$(".show-onclick").css("display", "none");
var sd_id=$(this).closest('div.service_display').attr("id");
$("#"+sd_id+" .show-onclick").css("display", "block");
});
});
</script>
The only change i made to your code is i have added a dynamic id field to service_display div.
And i have used jquery to show and hide the forms of respective clicked buttons.
Again here i have used oop based mysqli which is not mandatory yours is also perfectly fine.

Related

Comment and subcomment form: problems when showing and hiding it inside while loop (php) and based on a jquery script logic

The problem is with my two forms (for comments and subcomments by the users). I've implemented a jquery code so that this such form can show or hide when clicking on the "reply" button. Well, man, so far so good. But I noticed after a few tests that this works out on the comments but not on the subcomments.
On the subcomments it works but only on the subcomments I posted and when I'm logged in my own system. On the rest of the subcomments, it does not work, and when I click on the secondary comment or subcomment "reply" button, it doesn't show or hide anything and the other buttons like "delete" and "edit" look unactive and don't work at all. Well, this is my first problem. Now, my second problem is with the span "view replies".
When I click on it, it hides all "ul"(unordered lists) with class ".replies" at once (in which there are the subcomments to the main comment) and not one by one (hide-and-show switching) like I'd like. Besides, when I click on it again, it simply doesn't reshow. This is the jQuery code:
$(document).ready(function(){
$(document).on('click' , '.reply' , function(){
var closestDiv = $(this).closest('div'); // also you can use $(this).parent()
//closestDiv.fadeOut();
$('.replyto').not(closestDiv.next('.replyto')).hide();
//$('.reply').closest('div').not(closestDiv).show()
closestDiv.next('.replyto').slideToggle(100);
});
});
This one above is to toggle the "reply" form of comments. It's working on the first level (comments), but not for the subcomments.
$(document).ready(function(){
$(document).on('click' , '.clicktoviewreplies' , function(){
var closestUl = $(this).closest('ul'); // also you can use $(this).parent()
//closestUl.fadeOut();
$('.replies').not(closestUl.next('.replies')).hide();
//$('.clicktoviewreplies').closest('ul').not(closestUl).show()
closestUl.next('.replies').slideToggle(100);
});
});
This one above is to toggle the subcomments or replies. It's something like "show replies" and "hide replies". And this is the whole php code. It's based on four tables: registered_users, videos (although it's not here), comments and subcomments, as you can see.
<?php
while($commentslist = $showcomments->fetch()){
$iduser = $commentslist['idUser'];
$idcomment = $commentslist['id'];
$showuser = $pdo->prepare("SELECT * FROM registered_users WHERE id = ?");
$showuser->execute(array($iduser));
while($row6 = $showuser->fetch()){
<li>
<div>
<b><?php echo $row6['username']; ?></b><br>
<?php echo $commentslist['comments']; ?>
<!--additional comment buttons or controllers-->
<?php
if($iduser == $row['id']){ ?> <button>Edit</button><?php }else{ ?> <button>Report</button><?php } ?> <button class="reply">Reply</button><?php if($iduser == $row['id']){ ?> <a onClick="return confirm('You sure you wanna delete that comment there')" href=""><button>Delete</button></a><?php }
?>
</div>
<div class="replyto">
<!--THIS IS TO SUBMIT THE CHILD COMMENTS(SUBCOMMENTS)-->
<form enctype="multipart/form-data" method="post" action="<?php echo "postsubcomment.php?id=$idcomment"; ?>">
<textarea name="subcomment" cols="50" rows="4"></textarea>
<input type="submit" name="reply" value="Submit">
</form>
</div>
<span class="clicktoviewreplies"><b>View replies</b></span> <!--ATTENTION!HERE IT IS WHERE MY PROBLEM IS. I CLICK ON IT AND IT HIDES ALL "UL"(Unordered Lists) WITH CLASS ".REPLIES" AND NOT ONE BY ONE (SWITCHING) LIKE I'D LIKE. AND WHEN I CLICK ON IT AGAIN, IT DOESN'T RESHOW.-->
<!--SECOND LEVEL UNORDERED LIST-->
<ul class="replies">
<!--Subcomments go/show here. This happens everytime the user replies to a main comment-->
<?php
$showsubcomments = $pdo->prepare("SELECT * FROM subcomments WHERE idComment = ?");
$showsubcomments->execute(array($idcomment));
while($subcommentslist = $showsubcomments->fetch()){
$subcommenter = $subcommentslist['idComment'];
$selectcomment = $pdo->prepare("SELECT * FROM comments WHERE id = ?");
$selectcomment->execute(array($subcommenter));
$row7 = $selectcomment->fetch();
//This is to get the parent comment user
$selectuser = $pdo->prepare("SELECT * FROM registered_users WHERE id = ?");
$selectuser->execute(array($row7['idUser']));
$row8 = $selectuser->fetch();
$subcommentslist['idUser']; //The user that made the subcomment
$selectuser2 = $pdo->prepare("SELECT * FROM registered_users WHERE id = ?");
$selectuser2->execute(array($subcommentslist['idUser']));
$row9 = $selectuser2->fetch();
?>
<!--SECOND LEVEL LIST ITEM: This is to show the subcomments-->
<li>
<div>
<?php echo "<b>".$row9['username']; ?>
<?php echo "<br>".$subcommentslist['subcomments']."<br>"; ?>
<!--additional subcomment buttons or controllers-->
<?php
if($row9['id'] == $row['id']){ ?> <button>Edit</button><?php }else{ ?> <button>Report</button><?php } ?> <button class="reply">Reply</button><?php if($row9['id'] == $row['id']){ ?> <a onClick="return confirm('You sure you wanna delete that comment there')" href=""><button>Delete</button></a><?php }
?>
</div>
<div class="replyto" style="margin-left:5%; position:relative;">
<!--THIS IS TO REPLY TO BOTH THE MAIN COMMENT AND SUBCOMMENTS BELOW IT-->
<form enctype="multipart/form-data" method="post" action="<?php echo "postsubcomment.php?id=$idcomment"; ?>">
<textarea name="subcomment" cols="50" rows="4"></textarea>
<input type="submit" name="reply" value="Submit">
</form>
</div>
</li>
<?php
}//THIRD (SUBCOMMENTS) WHILE CLOSED
?>
</ul> <!--SECOND UNORDERED LIST CLOSED -->
</li>
<?php
} //SECOND WHILE CLOSED
} //FIRST WHILE CLOSED
?>
Well, the first instance (comments) "reply button "behaviour works. Why not the second instance one (reply for subcomments)? I wonder if the problem is the second or third while loop or maybe it has something to do with the "ul" and "li" arrangements.
Well, the boss here will solve these problems for you, man.
For the second problem (span:"view replies"), change your code to this:
$(document).ready(function(){
$(".clicktoviewreplies").click(function(){
//$(this).closest('ul').next('.replies').hide();
//$('.replies').
$('.replies').not($(this).next('.replies')).css("display", "none");
$(this).next('.replies').slideToggle(100);
});
});
And also change the text to "show/hide replies".
As for the first problem (reply buttons and comment and "subcomment" forms), delete the "style" tag and all css, except the attribute "display: none". Remember that the jQuery or even a Javascript code might have a malfunction since you're using something beyond the class itself needed to identify the element in the code. I don't know how to explain why this happens.
So instead of using:
<div class="replyto" style="margin-left:5%; position:relative;">
Use:
<div class="replyto">
And in CSS, use only:
.replyto
{
display: none;
}
And a tip: for a matter of having a well structured and "understable" way of code implementation, you could avoid "style" tags and use only CSS organized in a separated stylesheet document. I hope to have helped you, dude.

How to send corresponding var to second php page without form or into url?

I have two php page.I'm using Bootstrap, php and mysql. In the first page I load three objects into div from mysql database of the user logged. To do this I'm using the next code:
<div class="container">
<div class="row">
<?php
require_once('function.php');
conectar('localhost', 'root', '', 'mydb');
$consulta1 = mysql_query('SELECT id FROM user WHERE username="'.$_SESSION["name"].'"');
$result = mysql_query('SELECT * FROM finc WHERE Usuario_idUsuario="'.$_SESSION["idUser"].'"');
if ($row = mysql_fetch_array($result)){
do{
echo '<div class="col-lg-4">' ;
echo '<img class="center-block img-circle" src="data:image/gif;base64,R0lGODlhOw=="
alt="Generic placeholder image" style="width: 140px; height: 140px;">';
echo '<h2 class="text-center">'.$row['name'].'</h2>';
echo '<p align="center">'.$row['data'].'</p>';
echo '<p align="center">'.$row['tao'].'</p>';
echo '
<a type="button" class="btn btn-success" href="secondPage.php" role="button">Entrar »</a>
';
echo'</div>';
}while ($row = mysql_fetch_array($result));
} else {
echo "¡ No data for this user!";
<a}
?>
<!-- /.col-lg-4 -->
</div>
<!-- /.row -->
</div>
I need send the id value depending of the button clicked for load the data associated in the next php page. For example, If I click in the second button created in the do-while loop I need send the id=2 to the sencondPage.php. I have searched how to do this, but only find how to send var into url like sencondPage.php?var=2, And I hate this because user can change url... And adding value into session, but on click I haven't get this.
So, how can I pass the corresponding id value when user click in the link??
Thanks!
You could use an html <form>:
<form method="post" action="[URL FOR NEXT PAGE]">
...
<input type="submit" name="value1" value="Button 1" />
<input type="submit" name="value2" value="Button 2" />
</form>
Now if someone clicks the first button it will send them to the next page with the post data: value1=Button%201, and if they click the second button the it will instead be value2=Button%202. In either case any other form elements inside the form will also be submitted via post. With PHP you can retrieve these values using something like:
if ($_POST['value1']) {
...
elseif ($_POST['value2']) {
...
}

PHP separate id for every div

to be honest this is more of a how to then help with code i already have. So i hope this is okay, else of course i will delete my question again. Anyway here goes i have a site with boxes, with a picture headline and a submit button. All the info in these boxes is being delivered, from my database. And of course in my database i also have a id cell, and if i try to echo out the id cell with the rest of the info in the box it shows up fine. But when i try to assign the id output variable to a header location, i do for some weird reason always get the id 3. Eventhough the id´s shows up perfectly fine, in the boxes. I have included my php code and i am still a beginner to php so sorry for this noob question. :)
session_start();
include 'connection.php';
$sqlSelect = mysqli_query($con,"SELECT * FROM inspi");
while ($feed=mysqli_fetch_array($sqlSelect))
{
$id = $feed['id'];
if(isset($_POST['readArticle']))
{
$id = $_SESSION['id'];
header("Location:"."redirect.php?".SID.$idArticle);
}
?>
<div class="contentBoxOne">
<img width="100%" height="170px" src="userpics/<?php echo $feed['image']; ?>">
<div class="line"></div>
<form method="post" action="">
<input type="submit" name="readArticle" class="readArticle" value="Læs nu!">
</form>
<?php $idArticle= $feed['id'];?>
<h2><?php echo $feed['headline'];?></h2>
</div>
You are setting $idArticle at the bottom of the loop but trying to use it at the top so it will be pulling it from the previous result. Try:
while ($feed=mysqli_fetch_assoc($sqlSelect)){
$idArticle= $feed['id'];
$sid = $_SESSION['id'];
if(isset($_POST['readArticle']))
{
header("Location:"."redirect.php?".$sid.$idArticle);
}
//rest of code
}
You will have to put div inside the loop.
I also replaced the header redirect with form action attribute (you may want to replace method POST with GET instead).
ID is passed with a hidden field
<?php
include 'connection.php';
$sqlSelect = mysqli_query($con,"SELECT * FROM inspi");
while ($feed=mysqli_fetch_assoc($sqlSelect))
{
$id = (int)$feed['id'];
?>
<div class="contentBoxOne">
<img width="100%" height="170px" src="userpics/<?php echo $feed['image']; ?>">
<div class="line"></div>
<form method="post" action="redirect.php">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" name="readArticle" class="readArticle" value="Læs nu!">
</form>
<h2><?php echo $feed['headline']; ?></h2>
debug: <pre><?php print_r($feed); ?></pre>
</div>
<?php } // end of while loop ?>

Form submitting in php

--EDIT---
i have created a text box area where users can input some data,
Basically when i press the submit button, it should save the inputted data. here is the full code, i can't fix it. :/
The user entry does not get updated.
<?php
if ( $act == "htmlprofile" ) {
?>
<div class="contentcontainer">
<div class="contentmboardheaderarea"><img src="images/header.png" />
<div style=”word-wrap: break-word”><div class="contentheadertext"><?php echo "$hlang2"; ?></div></div></div>
<div class="contentheading">
<form id="htmlform" name="htmlform" method="post" action="options.php?act=htmlsubmit">
<div class="contentheading4">
<?php echo "$olang15"; ?></div>
</div>
<div class="contentmboardlistarea2"><textarea id="htmlprofile" name="htmlprofile" cols="33" rows="10"><?php echo $qry2[htmlprofile];?>
</textarea></div></form>
<div class="contentbuttonarea">
<div class="contentbutton1" onClick="document.location.href = 'profile.php?act=index'";><?php echo "$glang3"; ?></div>
<div class="contentbutton2" onClick="document.forms['htmlform'].submit();"><?php echo "$glang21"; ?></div>
<div class="contentbutton3"></div>
<div class="contentbutton4"></div>
<div class="contentbutton5" onClick="document.location.href = 'help.php#htmlprofile'";><?php echo "$glang5"; ?></div>
</div>
</div>
<?php
}
?>
<?php
if ( $act == "htmlsubmit" ) {
$save ='Profile updated successfully';
$query4 = "UPDATE members SET htmlprofile = '$htmlprofile' WHERE username = '$myuser'";
mysql_query($query4);
?>
There is no value attribute in textarea you have to enter the content between the <textarea>text</textarea>
See for reference tag_textarea
It should be like this
<textarea id="htmlprofile" name="htmlprofile" cols="33" rows="16" >
<?php echo $qry2[htmlprofile]; ?>
</textarea>
Refer to this answer also which-value-will-be-sent-by-textarea-and-why
Your div contentheadertext is not contained within the <form></form> so if you have inputs there, they won't be included in the form submission.
To resolve, move the opening <form> tag higher, so that it encloses all inputs.
the submit works fine. But you have no variables with the post data definied. And textareas haven't "value". And when you don't need fixed strings in your echo, don't use the "
try the following:
<textarea id="htmlprofile" name="htmlprofile" cols="33" rows="16"><?php echo htmlspecialchars($_POST['htmlprofile']); ?></textarea>
if you are trying to use a php variable inside HTML do that simply by echo $myvariable ; Quotes not required there. But if u are trying to echo a string use quotes just like echo 'mystring' .
Moreover when you are trying to pass some values as part of form submission, the required values should be between the tags
if you want to show any value inside text area, remember it doesn't have a 'value' attribute. So write the code like this: value to be displayed

Appending content to page right after database submit

<div class="accordion" id="accordion2">
<?php $info= mysql_query("SELECT id, title, description FROM event"); ?>
<?php while ($row = mysql_fetch_array($info, MYSQL_NUM)): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse<?php print $row[0]; ?>"><?php print $row[1]; ?></a><span class="delete" id="<?php print $row[0]; ?>">×</span>
</div>
<div id="collapse<?php print $row[0]; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<div class="row-fluid">
<div class="span6">
<?php print $row[2]; ?>
</div>
<div class="span6 ppl">
<ul>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
I have a pretty simple way of printing out my twitter bootstrap accordion.
I have this displayed on my page and I also have a form on top of the accordion itself from where I can submit another one into the database using ajax. Here is the form:
<form class="form">
<fieldset>
<legend>Stuff</legend>
<input class="class1" type="text" placeholder="xx">
<input class="class2" type="text" placeholder="xx">
<input class="class3" type="password" placeholder="xx">
<textarea maxlength="320" rows="5" class="class4" placeholder="xx"></textarea>
<div class="submit btn">Add</div>
</fieldset>
</form>
Here is the jQuery:
$(".form .submit").bind("click", function() {
var title = $(".form input.class1").val();
var email = $(".form input.class2").val();
var stuff1 = $('.form input.class3').val();
var stuff2 = $('.form textarea.class4').val();
if (title && email) {
var data = {title: title, email: email, stuff1: stuff1, stuff2: stuff2};
$.post("action.php", data, function() {
$(".form input, .form textarea").val("");
alert('done');
});
}
else {
alert('something went wrong');
}
});
And finally my action.php file:
<?php require('access.php');
if ($_POST['title'] && $_POST['email']) {
$title = $_POST['title'];
$email = $_POST['email'];
$stuff1 = $_POST['stuff1'];
$stuff2 = $_POST['stuff2'];
mysql_query("INSERT INTO events (title, email, stuff1, stuff2) VALUES('$title', '$email', '$stuff1', '$stuff2')");
}
Everything works, but like the title says, I want the information entered to be prepended to the accordion div as a new accordion group (without refreshing the page). My brain refuses to work with me on this, since to me it seems that if I submit the values, I have to make another request to the database to get the freshly generated id of the new event to have my accordion layout working.
Wat do?
And sorry for using a deprecated way of using mysql :O
So mysql functions aside, all you are looking to do is to prepend some html to an element. You already have a callback function on your post and so all you need to do is to make it actually do something i.e.
$.post('action.php', data, function() {
var newID = 123; // get this from the response text
$('div.accordion-inner').prepend('<div class="row-fluid"><div class="span6">'+newID +'</div><div class="span6 ppl"><ul></ul></div></div>');
});
This will attempt to prepend the div as specified to div.accordion-inner
Just replace the prepended with whichever html you are looking for.
And as an additional note, http://php.net/manual/en/function.mysql-insert-id.php will get you the PRIMARY KEY value for the last INSERT performed on your MySQL connection

Categories