crud edit button modal variable is undefined - php

I am creating my first php app and running into an issue on how I should try and edit a sql entry. I was planning on trying to get a modal window to pop up in order to edit.
When I select the edit link to open the modal window the variable says it is undefined. I am thinking it is because the Modal and variable are added to DOM before I click the link to edit and the variable never gets set. How do I get around this?
<?php
$sql = "SELECT id, image, name, score, points FROM teams";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)){
$teams_id = $row["id"];
$teams_image = $row["image"];
$teams_name = $row["name"];
$teams_score = $row["score"];
$teams_points = $row["points"];
// echo "id: " . $teams_id . " image path: " . $teams_image . " name: " . $teams_name . " score " . $teams_score . " points " . $teams_points . "</br>";
echo "<div class='row'>";
echo "<div class='row oval'>";
echo "<div class='col-4 flag {$teams_image}'>";
echo "</div>";
echo "<div class='col-8 text'>";
echo "<p>{$teams_name}</p>";
echo "</div>";
echo "</div>";
// edit and delete button
echo "<a href='add_teams_working.php?edit={$teams_id}' class='btn btn-outline-light btn-sm ml-4 align-self-center' data-toggle='modal' data-target='#editModal'>edit</a>";
echo "<button class='btn btn-outline-light btn-sm ml-1 align-self-center'>delete</button>";
echo "</div>";
}
}else {
echo "No teams added yet";
}
?>
<!-- SET VARIABLE for MODAL -->
<?php
if(isset($_GET['edit'])) {
$edit_id = $_GET['edit'];
$query = "SELECT * FROM teams WHERE id = $edit_id ";
$select_team = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($select_team)) {
$edit_id = $row['id'];
$edit_image = $row['image'];
$edit_name = $row['name'];
}
}
?>
Here is modal if needed.
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3>Edit <?php echo $edit_name; ?> </h3>
</div>
<div class="modal-body">
<?php echo $edit_name; ?>
<?php echo $edit_image; ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="button">Save Changes</button>
</div>
</div>
</div>
</div>

Related

SELECT query returns 1 row when there is more than 1

I'm working on a project for my university homework. Everything works right now except for my activity list. Issue is that whenever I try to view my activity list, it only returns 1 activity instead of all the activities that are still ongoing, when I manually run the query from phpMyAdmin, it returns all the queries but PHP doesn't seem to get it right and I have no idea why.
I have already tried running the query from phpMyAdmin and simplifying my query, also added a bunch of debugging code to see where I am going wrong but all the values are correct, the query is correct and phpMyAdmin runs the query just fine.
$query = "SELECT * FROM activities"; /*LIMIT " . $limit . ", " . $maxActivity;*/
$result = mysqli_query($link, $query);
echo $query;
if(!$result) {
echo "<p class='text-danger'>There are no activities to display.</p>";
} else {
while($row = mysqli_fetch_assoc($result)) {
$activity_id = $row['id'];
$activity_name = $row['name'];
$activity_description = $row['description'];
$activity_end_date = $row['endDate'];
$activity_start_date = $row['startDate'];
$activity_type = $row['type'];
$activityAuthor = $row['author'];
$activityPublished = $row['publishedAt'];
$activityLikes = $row['likes'];
$activityDislikes = $row['dislikes'];
$activityComments = $row['comments'];
$activityViews = $row['views'];
$query = "SELECT * FROM users WHERE Username = '$activityAuthor'";
$result = mysqli_query($link, $query);
if(!$result) {
die("MySQL Query Failed: " . mysqli_error($link));
}
$row = mysqli_fetch_assoc($result);
$authorID = $row['id'];
?>
<div class="row">
<div class="col-md-6">
<a href="#">
<img class="img-fluid rounded mb-3 mb-md-0" src="img/<?php echo "$activity_type";?>.jpeg" alt="">
</a>
</div>
<div class="col-md-6">
<h3><?php echo $activity_name;?></h3>
<p class="lead text-secondary">Proposed by <a class="text-secondary lead" href="profile.php?id=<?php echo $authorID;?>"><?php echo $activityAuthor;?></a> at <?php echo $activityPublished;?></p>
<p><?php echo $activity_description;?></p>
<p><strong>Starts at:</strong> <?php echo $activity_start_date;?></p>
<p><strong>Ends at:</strong> <?php echo $activity_end_date;?></p>
<a class="btn btn-outline-success" href="config/like.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>"><i class="far fa-thumbs-up"></i> <?php echo $activityLikes;?></a>
<a class="btn btn-outline-danger" href="config/dislike.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>"><i class="far fa-thumbs-down"></i> <?php echo $activityDislikes;?></a>
<button class="btn btn-outline-secondary"><i class="far fa-comment-dots"></i> <?php echo $activityComments;?></button>
<button class="btn btn-outline-secondary"><i class="far fa-eye"></i> <?php echo $activityViews;?></button>
<div class="mt-3"><a class="btn btn-primary" href="activity.php?post=<?php echo $activity_id;?>&page=<?php echo $page;?>&commentpage=1">View Activity</a></div>
</div>
</div>
<hr>
<?php }
}?>
<?php
$query = "SELECT * FROM activities";
$result = mysqli_query($link, $query);
if(!$result) {
echo "<p class='text-danger'>There are no activities to display.</p>";
} else {
while($row = mysqli_fetch_assoc($result)) {
$activity_id = $row['id'];
$activity_name = $row['name'];
$activity_description = $row['description'];
$activity_end_date = $row['endDate'];
$activity_start_date = $row['startDate'];
$activity_type = $row['type'];
$activityAuthor = $row['author'];
$activityPublished = $row['publishedAt'];
$activityLikes = $row['likes'];
$activityDislikes = $row['dislikes'];
$activityComments = $row['comments'];
$activityViews = $row['views'];
$query = "SELECT * FROM users WHERE Username = '$activityAuthor'";
$result = mysqli_query($link, $query);
if(!$result) {
die("MySQL Query Failed: " . mysqli_error($link));
}
$row = mysqli_fetch_assoc($result);
$authorID = $row['id'];
}
$output.="<div class='row'>
<div class='col-md-6'>
<a href='#'>
<img class='img-fluid rounded mb-3 mb-md-0' src='img/<?php echo '$activity_type';?>.jpeg' alt=''>
</a>
</div>
<div class='col-md-6'>
<h3><?php echo $activity_name;?></h3>
<p class='lead text-secondary'>Proposed by <a class='text-secondary lead' href='profile.php?id=<?php echo $authorID;?>'><?php echo $activityAuthor;?></a> at <?php echo $activityPublished;?></p>
<p><?php echo $activity_description;?></p>
<p><strong>Starts at:</strong> <?php echo $activity_start_date;?></p>
<p><strong>Ends at:</strong> <?php echo $activity_end_date;?></p>
<a class='btn btn-outline-success' href='config/like.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>'><i class='far fa-thumbs-up'></i> <?php echo $activityLikes;?></a>
<a class='btn btn-outline-danger' href='config/dislike.php?page=<?php echo $page;?>&post=<?php echo $activity_id;?>'><i class='far fa-thumbs-down'></i> <?php echo $activityDislikes;?></a>
<button class='btn btn-outline-secondary'><i class='far fa-comment-dots'></i> <?php echo $activityComments;?></button>
<button class='btn btn-outline-secondary'><i class='far fa-eye'></i> <?php echo $activityViews;?></button>
<div class='mt-3'><a class='btn btn-primary' href='activity.php?post=<?php echo $activity_id;?>&page=<?php echo $page;?>&commentpage=1'>View Activity</a></div>
</div>
</div>";
}
?>
<?php echo $output; ?>

Slider inside modal, modal dissappear when clicking next

So, I am making a slideshow inside a modal. The idea is when user clicks "Slideshow", a modal will popup showing a slideshow of images. However when I click next button to view the next image, the modal suddenly closes. I tried putting the code to disable any external or button clicks but it still closes.
here is the code:
<button type="button" id="slide" class="btn btn-primary" data-toggle="modal" data-target="#mySlider">Persembahan Slaid</button><br><br><br>
<div class="modal fade" id="mySlider" tabindex="-1" role="dialog" aria-labelledby="mySliderLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Tutup</span></button>
<h4 class="modal-title" id="mySliderLabel"><?php echo $title?></h4>
</div>
<div class="modal-body">
<form ACTION="" method = "POST" enctype="multipart/form-data">
<div class="form-group">
<div class="w3-content w3-display-container">
<?php
$sql = "SELECT * FROM storytelling WHERE title = '$title' ORDER BY id";
$result = mysqli_query($db, $sql);
while($row = $result -> fetch_array())
{
?>
<div class="w3-display-container mySlides">
<?php echo "<img src = 'images/".$row['image']."' style='width:100%'>"; ?>
<div class="w3-display-bottomright w3-large w3-container w3-padding-16 w3-black">
<?php echo $row['text']?>
</div>
</div>
<?php
}
?>
<button class="w3-button w3-display-left w3-black" onclick="plusDivs(-1)">❮</button>
<button class="w3-button w3-display-right w3-black" onclick="plusDivs(1)">❯</button>
<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
<?php if(isset($_POST['save']))
{
//target folder to keep the media
$target = "images/".basename($_FILES['image']['name']);
//get all submitted data from form
$image = $_FILES['image']['name'];
$text = $_POST['text'];
if(!empty($_FILES['image']['name']))
{
$sql = "INSERT INTO storytelling(title, image, text ) VALUES ('$title', '$image', '$text')";
$result=mysqli_query($db, $sql);
if($result){
$message = "Cerita akan ditambah selepas diluluskan admin";
echo "<script type='text/javascript'>alert('$message');</script>";
header("Refresh:0");
} else {
$message = "Cerita gagal ditambah";
echo "<script type='text/javascript'>alert('$message');</script>";
}
move_uploaded_file($_FILES['image']['tmp_name'], $target);
echo "<script type='text/javascript'>location.href='?title=$title';</script>";
}
else
{
$message = "Sila pilih semua fail";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>
</div>
</form>
</div>
</div>
</div>
</div>
May I know how to view the next image in the modal without it closing ?
Thank you.

echo bootstarap modal on click function in php with submit data

I am trying to echo a bootstrap modal with php . I have some data from table database and if I click on button and try to echo modal on If(isset) condition, the modal is not showing.
see my Code Here:
<?php
//insert in persnaol user table
$sql = "SELECT id,date,status FROM $x order by id DESC;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class='border'> ";
echo "";
echo "<form action='#' method='POST'>";
$id = $row['id'];
echo "<input type='show' name='statusid' value='$id' >";
echo "<p> " . $row["status"] ."</p><br>";
echo "<a class='pull-right' ><input type='submit' value='Edit Post' class='btn1' name='editbtn' data-toggle='modal' data-target='#qModal' ></a>";
echo "<small> " . $row["date"]. "</small><br>";
$editid= $row['id'];
echo "</form><br>";
echo "</div>";
echo "<br>";
echo'
<script>
$("form").submit(function(e){
e.preventDefault();
});
</script>';
}
} else {
echo "hello";
}
?>
and my modal html code is here. modal window is not established.
<?php
require'db.php';
if(isset($_POST['editbtn'])){
$x = $_SESSION['username'];
$id=$_POST["statusid"];
echo '<div class="modal fade" id="qModal" role="dialog" >';
echo ' <div class="modal-dialog" style="z-index:1000;">';
echo '<div class="modal-content">';
echo '<div class="modal-header">';
echo ' <button type="button" class="close" data-dismiss="modal">×</button>';
echo ' <h4 class="modal-title">Post Editing.</h4>';
echo ' </div>';
echo ' <div class="modal-body">';
echo ' <P>';
echo $id;
echo '</p>';
echo ' <form>';
echo ' <textarea value="" >hello</textarea>';
echo ' </form>';
echo '</div>';
echo ' <div class="modal-footer">';
echo ' <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
echo ' </div> </div> </div> </div>';
}
?>
Your form is actually submited so you should see the screen blinking, modal display but the page is reloaded.
To prevent this you can prevent the default form submit action with jQuery for example or remove your form.
As you have Bootstrap activated for your modal I assume you also have jQuery, try to add this at the end of your php script:
echo'
<script>
$("form").submit(function(e){
e.preventDefault();
});
</script>';
EDIT1:
I made a test file and It works for me, here is what's in my file:
<?php
echo '
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>';
$id=7;
echo '<div class="modal fade" id="qModal" role="dialog" >';
echo ' <div class="modal-dialog" style="z-index:1000;">';
echo '<div class="modal-content">';
echo '<div class="modal-header">';
echo ' <button type="button" class="close" data-dismiss="modal">×</button>';
echo ' <h4 class="modal-title">Post Editing.</h4>';
echo ' </div>';
echo ' <div class="modal-body">';
echo ' <P>';
echo $id;
echo '</p>';
echo ' <form>';
echo ' <textarea value="" >hello</textarea>';
echo ' </form>';
echo '</div>';
echo ' <div class="modal-footer">';
echo ' <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
echo ' </div> </div> </div> </div>';
echo "<div class='border'> ";
echo "";
echo "<form action='#' method='POST'>";
$id = 2;
echo "<input type='show' name='statusid' value='$id' >";
echo "<p> " . "here" ."</p><br>";
//**edit button is here**
echo "<a class='pull-right' ><input type='submit' value='Edit Post' class='btn1' name='editbtn' data-toggle='modal' data-target='#qModal' ></a>";
echo "<small> " . "date". "</small><br>";
$editid= 2;
echo "</form><br>";
echo "</div>";
echo "<br>";
echo'
<script>
$("form").submit(function(e){
e.preventDefault();
});
</script>';

best practices for echo statement that outputs html?

Hi guys I have an application that allows users to post content on an empty div. I need some advice on making it scalable as I have to make sure if users are posting a lot of content the browser will not slow down or crash. I am a beginner so please put up with me. So in my code below I have an echo statement that prints out html content. I want to know how to make that function scalable in the long run? should I set the html as a variable then print it? should I encode it with JSON? please advice me as such. Thank-you
PHP Code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if($result) {
} else {
echo "bitch: " . $conn->error;
}
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
echo " <div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b>{$row['username']}</b></span> &#8195&#8195 &#8195&#8195 <span class='glyphicon glyphicon-time'></span> Posted_on: {$row['time']} </h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>{$row['question']} </h4>
<p> {$row['description']}</p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div> ";
}//end if
}//end while
?>
Did you try to separate the data logic and data display ? if you used php MVC framework which will more convenient on your case.
Following is a simple example.
//demo.html code
<?php
include_once("connection.php");
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//You can use Inner Join to display the matched records in between the two tables
$query = "SELECT * FROM `qpost` A INNER JOIN `user` B ON A.id=B.id ";
$result = $conn->query($query);
if ($result) {
} else {
echo "bitch: " . $conn->error;
}
$time = time();
$data_result = array(); // focus on your data logic process
while ($row = $result->fetch_assoc()) {
if ($time < $row['logged_time'] + 30) {
$data_result[] = $row;
}
}
?>
<?php foreach($data_result as $index => $row) { ?>
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'><span class='glyphicon glyphicon-user'> <b><?php echo $row['username']?></b></span>
&#8195&#8195 &#8195&#8195 <span class='glyphicon glyphicon-time'></span> Posted_on: <?php echo $row['time']?>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4><?php echo $row['question']?></h4>
<p> <?php echo $row['description']?></p>
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
<?php } ?>
It's fine what you're doing.
However as Eric has said you can exit and re-enter your PHP
You could store the html in a file, grab it using file_get_contents then use sprintf to manipulate it
In a file called "row.html"
<div class='row'>
<div class='col-md-8'>
<div id='thePost' class='panel panel-default'>
<div class='panel-heading'>
<h3 class='panel-title'>
<span class='glyphicon glyphicon-user'>
<b>%s</b> <!-- username -->
</span> &#8195&#8195 &#8195&#8195
<span class='glyphicon glyphicon-time'>
Posted_on: %s <!-- time -->
</span>
</h3>
</div>
<div class='panel-body' style='word-break:break-all'>
<h4>%s</h4> <!-- question -->
<p> %s</p> <!-- description -->
</div>
<div class='panel-footer'>
<button class='btn btn-primary'>Request Connection</button>
<button class='btn btn-success'>Chat <span class='glyphicon glyphicon-comment'></button>
</div>
</div>
</div>
</div>
Then in your PHP....
<?php
while($row = $result->fetch_assoc()) {
$time = time();
if( $time < $row['logged_time'] + 30) {
$rowHtml = file_get_contents('row.html');
echo sprintf($rowHtml,
$row['username'],
$row['time'],
$row['question'],
$row['description']);
}
}
?>
I personally like as much abstraction as possible between my languages :)
Good luck!
One way to echo out HTML with PHP is using Heredoc syntax (http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)
<?php
$name = 'MyName';
echo <<<MYHTML
<p>
My name is <b>"$name"</b>.
</p>
MYHTML;
?>

Twitter Bootstrap - Passing a unique ID to a Modal

I have searched a lot and am still having some trouble passing a Unique Id to a Value and then using that ID for a PHP MySQL Query to get the book info.
I currently am passing the unique ID to the Modal and Displaying it through an input type text. I am just having a hard time figuring out how to put the id into a php Variable
Here is my HTMl/PHP code
echo '<a data-toggle="modal" data-id="' . $book_id .'" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">View Info</a>';?>
<!-- Modal -->
<div class="modal hide" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Book Info</h3>
</div>
<div class="modal-body">
<p>some content</p>
<?php
echo $test = '<input type="text" name="bookId" id="bookId"/>';
$book_info = get_book_info($book_id);
while($row1 = mysqli_fetch_array($book_info))
{
$email = $row['email'];
echo "<p><strong>Title: </strong>" . $row1['title'] . "</p>";
echo "<p><strong>Author: </strong>" . $row1['author'] . "</p>";
echo "<p><strong>Edition: </strong>" . $row1['edition'] . "</p>";
echo "<p><strong>ISBN: </strong>" . $row1['isbn'] . "</p>";
echo "<p><strong>Price: </strong>" . $row1['price'] . "</p>";
echo "<p><strong>Seller's Name: </strong>" . $row1['name'] . "</p>";
echo "<p><strong>Seller's E-mail: </strong><a href='mailto:$email'>$email</a></p>";
}?>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
here is my jquery
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
});
You need to echo the value:
data-id="<?php $book_id ?>"
Use this instead:
data-id="<?php echo $book_id; ?>"
You could do something like this by javascript/coffee script.
($ "a[data-toggle=modal]").click ->
target = ($ #).attr('data-target')
url = ($ #).attr('href')
($ target).load(url)
URL = unique ID

Categories