hi i need help i have problem in my code and i can't figure the solutions please help me .
this is the dashboard:
image dashboard
and this is problem after click on delete:
delete problem
and this is my code php of posts file:
<?php
/*
===========================================================
=== Manage Members Page ===
=== You can add | edit | delete Members from here ===
===========================================================
*/
session_start();
if (isset($_SESSION['Username'])) {
include 'init.php';
$pageTitle = 'Posts';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage' ;
//Start Manage Page
if ($do == 'Manage'){ // Manage Members Page
$sort = 'ASC';
$sort_arry = array('ASC', 'DESC');
if(isset($_GET['sort']) && in_array($_GET['sort'], $sort_arry)) {
$sort = $_GET['sort'];
}
$stmt2 = $con->prepare("SELECT * FROM posts ORDER BY Ordering $sort");
$stmt2->execute();
$rows = $stmt2->fetchAll();
?>
<h1 class="text-center"> Manage Posts </h1>
<div class="container categories">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-edit"></i> Manage Posts
<div class="ordering pull-right">
<i class="fa fa-sort"> </i>Ordering: [
<a class="<?php if ($sort == 'ASC') { echo 'active'; } ?>" href="?sort=ASC">Asc </a> |
<a class="<?php if ($sort == 'DESC') { echo 'active'; } ?>" href="?sort=DESC">Desc </a>
]
</div>
</div>
<div class="row">
<?php
foreach ($rows as $image) {
echo '<div class="col-md-3 col-sm-4 "><div class="thumbnail">';
echo '<h2 class="h4">'.$image['Name']. '</h2><div class="main">';
echo '<img src="data:image;base64,'.$image['Image'].' " alt="image name" title="image title" width="255" heigth="255">';
echo '</div>';
echo '<table class="table table-bordered">';
echo '<tr>';
echo '<td>' . "<a href='posts.php?do=Edit&id=". $image['ID'] ."' class='btn btn-xs btn-primary'><i class='fa fa-edit'></i> edit</a>" . '</td>';
echo '<td>' . "<a href='posts.php?do=Delete&id=". $image['ID'] ."' class='btn btn-xs btn-danger'><i class='fa fa-close'></i> Delete</a>" . '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
echo '</div>';
}
?>
</div>
<?php } elseif ($do == 'Add') { //add Member page ?>
<h1 class="text-center"> ajouter un nouveau post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Insert" method="POST">
<!-- start Username fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="image-name" class="form-control" autocomplete="off" placeholder="username pour se connecter dans le site Web" required />
</div>
</div>
<!-- end Username fieled -->
<!-- start Password fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" placeholder="mot de passe doit être difficile et complexe" required/>
</div>
</div>
<!-- end Password fieled -->
<!-- start Full name fieled -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- end Full name fieled -->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="Ajouter" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</form>
</div>
<?php
} elseif ($do == 'Insert') {
//insert Members Page
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h1 class='text-center'> insert an post </h1>";
echo "<div class='container'>";
// Get variable from the form
$name = $_POST['image-name'];
$image= addslashes($_FILES['image']['tmp_name']);
$image= file_get_contents($image);
$image= base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (strlen($name) < 4) {
$formErrors[] = "title name cant be less then <strong> 4 caracter</strong>";
}
if (strlen($name) > 20) {
$formErrors[] = "title name cant be More then <strong> 20 caracter</strong>";
}
if (empty($name)) {
$formErrors[] = "Username Cant Be <strong>Empty</strong>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo "<div class='alert alert-danger'>" . $Error . "</div>";
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// check if user exist in database
$check = checkItem("Username", "users", $user);
if ($check == 1) {
$theMsg = "<div class='alert alert-danger'> Sorry this user is exist </div>";
redirectHome($theMsg, 'back');
} else {
// Insert User info into database
$stmt = $con->prepare("INSERT INTO posts(Name, Image, Cat_id)
VALUES (:name, :image, :cat)");
$stmt->execute(array(
'name' => $name,
'image' => $image,
'cat' => $cat,
));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Inserted </div> ';
redirectHome($theMsg, 'back', 5);
}
}
} else {
echo "<div class='container'>";
$theMsg = '<div class="alert alert-danger"> Sorry you cant browse this page directely </div>';
redirectHome($theMsg, 'back', 5); // 6 is secend of redirect to page in function
echo "</div>";
}
echo "</div>";
} elseif ($do == 'Edit') { // Edit Page
//check if GET request userid Is numeric & Get The integer value of it
$post = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$stmt = $con->prepare("SELECT * FROM posts WHERE ID = ? LIMIT 1");
// execute Query
$stmt->execute(array($post));
//fetch the Data
$row = $stmt->fetch();
// The row count
$count = $stmt->rowCount();
// If Ther's Such Id show The Form
if ($count > 0) { ?>
<h1 class="text-center"> Modifier Post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Update" method="POST">
<div class="col-md-6 col-md-offset-3 panel">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<!-- start title fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="name" class="form-control" autocomplete="off" required value="<?php echo $row['Name']; ?>" >
</div>
</div>
<!-- end title field -->
<!-- start image filed -->
<div class="form-group">
<label class="col-sm-2 control-label">image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" />
</div>
</div>
<!-- end image filed -->
<!-- start Categories filed -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- Categories end-->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="sauvegarder" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</div>
</form>
</div>
<?php
// if there's No Such id Show Error Message
} else {
echo "<div class='container'>";
$theMsg = "<div class='alert alert-danger'>Theres is no such Id</div>";
redirectHome($theMsg);
echo "</div>";
}
} elseif ($do == 'Update') {
echo "<h1 class='text-center'> mis a jour Membre </h1>";
echo "<div class='container'>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get variable from the form
$id = $_POST['id'];
$name = $_POST['name'];
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (empty($name)) {
$formErrors[] = "<div class='alert alert-danger'>Username Cant Be <strong>Empty</strong> </div>";
}
if (empty($image)) {
$formErrors[] = "<div class='alert alert-danger'>FullName Cant Be <strong>Empty</strong></div>";
}
if (empty($cat)) {
$formErrors[] = "<div class='alert alert-danger'>Email Cant Be <strong>Empty</strong></div>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo $Error;
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// Update The Database With This Info
$stmt = $con->prepare("UPDATE posts SET Name = ? , Image = ? , Cat_id = ? WHERE ID = ?");
$stmt->execute(array($name, $image, $cat, $id));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Updated </div> ';
redirectHome($theMsg, 'back');
}
} else {
$theMsg = '<div class="alert alert-danger">Sorry you cant browse this page directely </div>';
redirectHome($theMsg);
}
echo "</div>";
}
elseif ($do == 'Delete') { // Delete Member Page
echo "<h1 class='text-center'> Delete Membre </h1>";
echo "<div class='container'>";
//check if GET request userid Is numeric & Get The integer value of it
$id = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$check = checkItem('id', 'posts', $id);
// If Ther's Such Id show The Form
if ($check > 0) {
$stmt = $con->prepare("DELETE FROM users WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Deleted </div> ';
redirectHome($theMsg);
} else {
$theMsg = "<div class='alert alert-danger'>This id not exist</div>";
redirectHome($theMsg);
}
echo "</div>";
}
include $tpl . 'footer.php';
} else {
header('Location: index.php') ;
exit();
}
from the error, id is the problem.
isset($_GET['id']) && is_numeric($_GET['id'])
i think what u want is
(isset($_GET['id']) && is_numeric($_GET['id']) )//close parantheses in wrong position
Related
My aim is to delete a row whenever I click delete button. My method doing this is by passing the value of ['movies_id'] and storing it inside a hidden input and then passing it when delete button is pressed. The issue is that when I press the delete button it only reads the first id, which in this case is 1. Even though I press the delete button in the 3 card for example. So, my question is how do I pass the correct 'movies_id' stored inside 'keyToDelete' so that it doesn't always read 1?
As you can see in the image below, the id from mysql is being read well inside the card.
function displayMovies()
{
global $dbc;
$movieSelect = "SELECT * FROM movies_tbl";
$query = mysqli_query($dbc, $movieSelect);
if (mysqli_num_rows($query) == 0) {
echo "There is nothing to display.";
} else {
$edit = "";
$delete = "";
if (isset($_SESSION['type'])) {
if ($_SESSION['type'] == "admin") {
$edit = "<a href='#' class='btn btn-cyan align-self-end'>Edit</a>";
$delete = '<input type = "submit" name="delete" value="Delete" form="movieForm" class="btn btn-cyan align-self-end">';
while ($row = mysqli_fetch_assoc($query)) {
movieDesc($row['movies_id'], $row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
} else if ($_SESSION['type'] == "user") {
while ($row = mysqli_fetch_assoc($query)) {
movieDesc($row['movies_id'],$row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
}
} else {
for ($i = 1; $i < 4; $i++) {
$row = mysqli_fetch_assoc($query);
movieDesc($row['movies_id'],$row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
}
}
}
if (isset($_POST['delete'])){
$key = $_POST['keyToDelete'];
echo"<h1>$key</h1>";
}
function movieDesc($movies_id,$movie_title, $main_actor, $movie_length, $average_rating, $release_date, $description, $img_path, $trailer_url, $edit, $delete)
{
echo '<div class="col-md-4 mb-4">
<div class="card">
<img src="images/' . $img_path . '.jpg" class="card-img-top cardImage">
<div class="card-body d-flex flex-column">
<form action="movies.php" id="movieForm" method="post">
<h3 class="card-title text-center fontEDO">' . $movie_title, $movies_id . '</h3>
<div class="row">
<div class="col">
<p class="card-text text-left"><b>Main Actor:</b></p>
<p class="card-text text-left"><b>Movie Length:</b></p>
<p class="card-text text-left"><b>Average Rating:</b></p>
<p class="card-text text-left"><b>Release Date:</b></p>
</div>
<div class="col">
<p class="card-text text-left">' . $main_actor . '</p>
<p class="card-text text-left">' . $movie_length . '</p>
<p class="card-text text-left">' . $average_rating . '</p>
<p class="card-text text-left">' . $release_date . '</p>
</div>
</div>
<p class="card-text text-left description"><br><b>Description:</b> ' . $description . '</p>
<input type="text" name="keyToDelete" value='. $movies_id .'>
</form>
<div class="mt-auto text-center">
Watch Trailer
' . $edit . '
' . $delete . '
</div>
</div>
</div>
</div>';
}
You can't have duplicate id="movieForm". When you use form="movieForm" in the submit button, it submits the first form with that ID, not the one just before the button.
You should move the submit button inside the form, and get rid of form="movieForm" from the button.
Or give each form a unique ID, and use that in the form attribute of the submit button.
I'm looking for a simple solution to inserting multiple checkbox selections into a single database column. If user selects 3 x l_comp checkboxes - the database should reflect "result, result, result".. the commas would be nice but are not neccessary.
As it is, if one checkbox is selected, the information will insert as it should. If multiple are selected, only the last one will be inserted into the DB. Everything else is working fine, but these darned checkboxes!
I know i'm vulnerable to sql-injection
My code:
<?php
// Initialize the session
session_start();
// Include config file
require_once "assets/scripts/config.php";
$param_uniqid = $_SESSION['uniqid'];
$param_company = $_SESSION['company'];
$param_vat = $_SESSION['vat'];
$param_username = $_SESSION['username'];
// Check if the user is logged in, if not then redirect him
to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"]
!== true){
header("location: login.php");
exit;
}
// Define variables and initialize with empty values
$l_comp = $user = $car = $uniqid = $company = $vat =
$username = "";
$l_comp_err = $user_err = $car_err = $uniqid_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate l_comp
$input_l_comp = trim($_POST["l_comp"]);
if(empty($input_l_comp)){
$l_comp_err = "Venligst indtast leasingselskab.";
} elseif(!filter_var($input_l_comp, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[0-9a-åA-Å+&##\/%-?
=~_|!:,.;\s]+$/")))){
$l_comp_err = "Leasingselskab er ikke korrekt.";
} else{
$l_comp = $input_l_comp;
}
// Validate user
$input_user = trim($_POST["user"]);
if(empty($input_user)){
$user_err = "Venligst indtast en bruger.";
} elseif(!filter_var($input_user, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[0-9a-åA-Å\s]+$/")))){
$user_err = "Bruger er ikke korrekt.";
} else{
$user = $input_user;
}
// Validate car
$input_car = trim($_POST["car"]);
if(empty($input_car)){
$car_err = "Venligst indtast bilinformationer.";
} elseif(!filter_var($input_car, FILTER_VALIDATE_REGEXP,
array("options"=>array("regexp"=>"/^[0-9a-åA-Å+&##\/%-?
=~_|!:,.;\s]+$/")))){
$car_err = "Bil er ikke korrekt.";
} else{
$car = $input_car;
}
// Validate uniqid
$input_uniqid = trim($_POST["uniqid"]);
if(empty($input_uniqid)){
$uniqid_err = "Venligst indtast uniqid.";
} elseif(!filter_var($input_uniqid, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[0-9a-åA-Å+&##\/%-?=~_|!:,.;\s]+$/")))){
$uniqid_err = "Uniqid er ikke korrekt.";
} else{
$uniqid = $input_uniqid;
}
// Check input errors before inserting in database
if(empty($l_comp_err) && empty($user_err) && empty($car_err)
&& empty($uniqid_err)){
// Prepare an insert statement
$sql = "INSERT INTO offer_requests_test (l_comp, user,
car, uniqid, company, vat, username) VALUES (?, ?, ?, ?, ?,
?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as
parameters
mysqli_stmt_bind_param($stmt, "sssssss",
$param_l_comp, $param_user, $param_car, $param_uniqid,
$param_company, $param_vat, $param_username);
// Set parameters
$param_l_comp = $l_comp;
$param_user = $user;
$param_car = $car;
$param_uniqid = $uniqid;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records created successfully. Redirect to
landing page
header("location: /offer_requests_test");
exit();
} else{
echo "Something went wrong. Please try again
later.";
}
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Fleets - få op til 3 tilbud på jeres næste
leasingbil</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="assets/css/main.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
</head>
<body class="subpage">
<!-- Header -->
<header id="header">
<div class="logo">Fleets.dk <span>3 tilbud på leasingbil</span></div>
LOG UD
</header>
<!-- content -->
<div class="box">
<div class="inner">
<div class="content">
<h4>Hej, <b><?php echo htmlspecialchars($_SESSION["name"]); ?></b>.</h4>
<hr />
<ul class="nav nav-tabs">
<li role="presentation">Profil</li>
<li role="presentation">Biler</li>
<li role="presentation" class="active">Tilbud</li>
<li role="presentation">Kontakter</li>
</ul>
<div class="table-wrapper">
<h4 class="pull-left">Oprettede tilbud</h4>
<table>
<tbody>
<tr>
<th class="hidden"><b>#</b></th>
<th><b>Bil</b></th>
<th><b>Bruger</b></th>
<?php
// Include config file
require_once "assets/scripts/config.php";
// Attempt select query execution
$sql = "SELECT * FROM offer_requests_test WHERE username = '" . ($_SESSION["username"]) . "'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<th></th>";
echo "<th></th>";
echo "<th></th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<th class='hidden'>" . $row['uniqid'] . "</th>";
echo "<th>" . $row['car'] . "</th>";
echo "<th>" . $row['user'] . "</th>";
echo "<th>";
echo "<a href='read_request.php?uniqid=". $row['uniqid'] ."' title='View Record' data-toggle='tooltip'><span class='glyphicon glyphicon-eye-open'></span></a>";
echo "</th>";
echo "<th>";
echo "<a href='update_request.php?uniqid=". $row['uniqid'] ."' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>";
echo "</th>";
echo "<th>";
echo "<a href='delete_request.php?uniqid=". $row['uniqid'] ."' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>";
echo "</th>";
echo "</tr>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "</br></br><p><b><i>Ingen informationer fundet.</i></b></p>";
}
} else{
echo "ERROR: Was not able to execute $sql. " . mysqli_error($link);
}
echo "</tbody>";
echo "</table>";
?>
<p>
<div href="" class="button alt small" onclick="hideCreate()">OPRET NYT TILBUD</div>
</p>
</div>
</div>
</div>
</div>
<!-- create -->
<div class="box">
<div class="inner">
<div class="content">
<div id="create">
<h4>1 - udfyld formularen</h4>
<form action="" method="post">
<div class="6u 12u$(xsmall) <?php echo (!empty($car_err)) ? 'has-error' : ''; ?>">
<label>Bil</label>
<input type="text" name="car" class="6u 12u$(xsmall)" value="<?php echo $car; ?>">
<span class="help-block"><?php echo $car_err;?></span>
</div>
<div class="6u 12u$(xsmall) <?php echo (!empty($user_err)) ? 'has-error' : ''; ?>">
<label>Bruger</label>
<input type="text" name="user" class="6u 12u$(xsmall)" value="<?php echo $user; ?>">
<span class="help-block"><?php echo $user_err;?></span>
</div>
<input type="hidden" name="company" value="<?php echo $company; ?>">
<input type="hidden" name="vat" value="<?php echo $vat; ?>">
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="hidden" name="uniqid" value="<?php echo uniqid(); ?>" /></input>
</br></br>
</br></br><div class="table-wrapper">
<h4 class="pull-left">2 - vælg op til tre leasingselskaber</h4></br></br>
<table>
<tbody>
<tr>
<th class="hidden"><b>#</b></th>
<th><b>Vælg</b></th>
<?php
// Include config file
require_once "assets/scripts/config.php";
// Attempt select query execution
$sql = "SELECT l_comp FROM l_comp";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<th><b>Leasingselskab</b></th>";
echo "<th></th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<th>";
echo "<div class='6u 12u$(xsmall) <?php echo (!empty(" . $l_comp_err . ")) ? 'has-error' : ''; ?>
<input type='checkbox' id='" . $row['l_comp'] . "' name='l_comp' value='" . $row['l_comp'] . "'>
<label for='" . $row['l_comp'] . "'></label>
<span class='help-block'><?php echo " . $l_comp_err. ";?></span>
";
echo "</th>";
echo "<th>" . $row['l_comp'] . "</th>";
echo "</tr>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "</br></br><p><b><i>Ingen informationer fundet.</i></b></p>";
}
} else{
echo "ERROR: Was not able to execute $sql. " . mysqli_error($link);
}
echo "</tbody>";
echo "</table>";
?>
</br></br>
<input type="submit" class="button alt small" value="OPRET TILBUDSKLADE">
FORTRYD
</form>
</div>
</div>
</div>
</div>
<!-- Footer -->
<footer id="footer" class="wrapper">
<div class="inner">
<div class="copyright">
© Fleets.dk - for virksomheder </br>
KONTAKT OS
</div>
</div>
</footer>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="assets/js/overlay_create.js"></script>
<script src="assets/js/overlay_login.js"></script>
</body>
I'm redoing the whole post since I had hard time explaining the issue or question.
What this code does:
The user can create a new training session. They can name it and if they want to, they can copy the content from previously created session.
I'm using Bootstrap 4 list group items to show the previous sessions. My problem is that I can not catch the user selection to post the data to activateSaveTrainingSession.php, which includes the SQL query to insert the new data to the database.
I can pass the data from the form to the action php file from inputSessionName -input. As you can see, I've also tried using input type="hidden". It kind of works, but it only uses the $sessionId from the first row it fetches, not the user selection. And thats the problem: how do I catch which list item the user selects, so I can post the data to the activateSaveTrainingSession.php?
<div class="row">
<div class="col-lg-12">
<form class="was-validated" action="activateSaveTrainingSession.php" method="post">
<div class="custom-control">
<div class="form-group">
<label for="inputSessionName" class="float-left"><?php echo $lang['TRAINING_SESSIONNAME_HEADER'] ?></label>
<input type="text" class="form-control" id="inputSessionName" name="inputSessionName" placeholder="Example 1" minlength="3" maxLength="128" required>
<small id="inputSessionNameHelp" class="form-text text-muted">
<?php echo $lang['TRAINING_SESSIONNAME_HELPTEXT'] ?>
</small>
</div>
</div>
<h5 class = "mt-3"><?php echo $lang['TRAINING_COPYSESSION_HEADER'] ?></h5>
<div class="row mt-3">
<div class="col-lg-6 mb-3">
<div class="list-group" id="list-tab" role="tablist">
<a class="list-group-item list-group-item-action active" id="list-doNotCopy-list" data-toggle="list" href="#list-doNotCopy" role="tab" aria-controls="list-doNotCopy">Do not copy</a>
<?php
$stmt = $link->prepare('SELECT `id`, `sessionName`, `createDate` FROM `trainingSessions` WHERE `userId` = ? ORDER BY `id` DESC LIMIT 5');
$stmt->bind_param('i', $currentUserId);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $sessionName, $sessionNameDate);
$sessionCounter = 0;
$tabsArray = array();
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$sessionNameDateFixed = date("d.m.Y", strtotime($sessionNameDate));
$sessionCounter += 1;
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
array_push($tabsArray, $sessionId)
?>
<a class="list-group-item list-group-item-action" id="<?php echo $sessionId ?>" data-toggle="list" href="#<?php echo $tabId ?>" role="tab" aria-controls="<?php echo $tabId ?>"><?php echo $sessionName ?><input type='hidden' name='copySession' value='<?php echo $sessionId ?> '/></a>
<?php
}
} else {
echo "No results.";
}
$stmt->close();
echo "Displaying last $sessionCounter records.";
?>
</div>
</div>
<div class="col-lg-6">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-doNotCopy" role="tabpanel" aria-labelledby="list-doNotCopy-list">Do not copy data from previous session.</div>
<?php
foreach ($tabsArray as $session) {
$tabsTextArray = array();
$stmt = $link->prepare('SELECT trainingSessions.id, workouts.workoutName, exercises.setNumber, exercises.reps, exercises.weights FROM workouts INNER JOIN exercises ON workouts.id = exercises.workoutId INNER JOIN trainingSessions on trainingSessions.id = exercises.sessionId WHERE exercises.userId = ? AND trainingSessions.id = ? ORDER BY exercises.id DESC');
$stmt->bind_param('ii', $currentUserId, $session);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $workoutName, $set, $reps, $weights);
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$tabText = "<strong>$workoutName</strong> sarja $set, $reps x $weights kg<br>";
array_push($tabsTextArray, $tabText);
}
}
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
?>
<div class = "tab-pane fade" id="<?php echo $tabId ?>" role = "tabpanel" aria-labelledby = "<?php echo $listId ?>"><?php
foreach ($tabsTextArray as $text) {
echo "$text";
}
?>
</div>
<?php
}
$stmt->close();
?>
</div>
</div>
</div>
<button type="submit" name="buttonSaveTrainingSession" class="btn btn-success float-left">
<i class="fas fa-sd-card"></i>
<?php echo $lang['TRAINING_BTN_SAVE'] ?>
</button>
</form>
</div>
</div>
activateSaveTrainingSession.php
<?php
require_once('config/sql.php');
include_once('config/common.php');
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
$currentUserId = $_SESSION["currentUserId"];
$submitButton = strip_tags(trim($_POST['buttonSaveTrainingSession']));
if (isset($submitButton)) {
$inputSessioName = filter_var(trim($_POST["inputSessionName"]), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$copySessionID = filter_var(trim($_POST["copySession"]), FILTER_SANITIZE_NUMBER_INT);
if (empty($inputSessioName) && strlen($inputSessioName) < 3 && $inputSessioName > 128) {
header("location: training.php?msg=invalidSessionName");
} else {
echo "Name: $inputSessioName <br>";
echo "ID: $copySessionID";
}
} else {
header("location: 404.php");
}
?>
I think I understand your problem.
You send in the form several fields:
<input type = 'hidden' name = 'copySession' ...>
which have the same name and not in table form! so it is normal that when receiving the request:
$_POST["copySession"]
you get only one and therefore the first.
If you want to send them all, you have to do:
<input type = 'hidden' name = 'copySession[]' ...>
and you get the request as an array.
foreach($_POST["copySession"] as $sessionId){ ... }
If you want to send only one field, you must make them disabled with javascript in real time during the selection.
For example you put in all fields copySession disabled and you add a class to them. Then you add the same class on the button as well and when the user clicks on a button, the field concerned removes the disabled.
With jQuery something like:
//Click on button
$('a.specialClass').on('click', function(){
//Disabled all copySession inputs
$('input[name="copySession"]').prop('disabled', true);
//Let the field concerned able to be send
$('input.specialClass[name="copySession"]').prop('disabled', false);
});
Good luck!
I am having the weirdest time with the html output. the first output works fine if you look at //start gallery row that is where my problems begin.
This is how the output should look
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>
<img class='img-responsive' src='cdn/assets/gallery/1.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/3.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/2.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/4.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/5.jpg'>
</div>
</div>
</div>
at the start of // gallery when I view source this is the out put
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>
<img class='img-responsive' src='cdn/assets/gallery/1.jpg'></div>
</div>
</div>
<img class='img-responsive' src='cdn/assets/gallery/3.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/2.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/4.jpg'>
<img class='img-responsive' src='cdn/assets/gallery/5.jpg'>
but no matter where I put the last output DIV it causes issues
<?php
$stmt = $db->prepare("my query");
$stmt->execute();
$result = $stmt->get_result();
$output = "";
$checker = [];
while ($row = mysqli_fetch_assoc($result)) {
$ID = $row['ID'];
$FullName = $row['FullName'];
$Email = $row['Email'];
$JobTitle = $row['JobTitle'];
$Bio = $row['Bio'];
$Photo = $row['Photo'];
$GalleryImage = explode(',', $row['GalleryImage']);
if (isset($Photo) && ! empty($Photo)) {
$ProfileImage = "$Photo";
} else {
$ProfileImage= "avatar.jpg";
}
if(!in_array($row['ID'], $checker)) {
$output .= "
<div class='container yep team-wrap'>
<div class='row'>
<div class='col-md-6'>
<img class='img-responsive' src='cdn/assets/artist/$ProfileImage'>
</div>
<div class='col-md-6'>
<strong>$FullName<br>$JobTitle</strong>
<br>
<p>$Bio</p>
<a href='mailto:$Email' class='btn btn-info'>Contact Me</a>
</div>
</div>";
//End of info row
$output .="<br /><br /><br />";
//Start Gallery Row
$output .= "
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>
";
}
foreach ($GalleryImage as $img){
//Display this row as many times as needed by data in this row.
$output .= "<img class='img-responsive' src='cdn/assets/gallery/$img'>";
}
$output .= "
</div>
</div>
</div>";
// End gallery row
array_push( $checker, $row['ID']);
}
$output .= "</div>";
echo $output;
?>
sql
$stmt = $db->prepare("
SELECT U.ID,
U.FullName,
U.Email,
U.JobTitle,
U.Bio,
U.Photo, G.GalleryImage
FROM users U
LEFT join gallery G
ON U.ID = G.ID
");
$stmt->execute();
$result = $stmt->get_result();
Ok, so I believe the best course of action is to loop through your $result and filter out all the repeated values as well as assigning images to an array with the row['ID'] as the key and then loop through them after CHECK IT!
$checker = array();
$profileArray = array();
while ($row = mysqli_fetch_assoc($result))
{
if($row['GalleryImage'])
{
$profileArray[$row['ID']]['GalleryImages'][] = $row['GalleryImage'];
}
if(!in_array($row['ID'], $checker))
{
while (list ($key, $value) = each($row))
{
if($key != 'GalleryImage')
{
$profileArray[$row['ID']][$key] = $value;
}
}
$checker[] = $row['ID'];
}
}
foreach ($profileArray as $row)
{
$ID = $row['ID'];
$FullName = $row['FullName'];
$Email = $row['Email'];
$JobTitle = $row['JobTitle'];
$Bio = $row['Bio'];
$Photo = $row['Photo'];
$GalleyImages = $row['GalleryImages'];
if (isset($Photo) && !empty($Photo))
{
$ProfileImage = "$Photo";
}
else
{
$ProfileImage = "avatar.jpg";
}
$output .= "
<div class='container yep team-wrap'>
<div class='row'>
<div class='col-md-6'>
<img class='img-responsive' src='cdn/assets/artist/$ProfileImage'>
</div>
<div class='col-md-6'>
<strong>$FullName<br>$JobTitle</strong>
<br>
<p>$Bio</p>
<a href='mailto:$Email' class='btn btn-info'>Contact Me</a>
</div>
</div>";
//End of info row
$output .= "<br /><br /><br />";
//Start Gallery Row
$output .= "
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>";
if(!$GalleyImages)
{
foreach ($GalleyImages as $img)
{
//Display this row as many times as needed by data in this row.
$output .= "<img class='img-responsive' src='cdn/assets/gallery/$img'>";
}
}
else
{
$output .= "HTML THAT YOU WANNA DISPLAY instead of images";
}
$output .= "
</div>
</div>
</div>
</div>";
}
echo $output;
Ok, first of all it is always good to format your code properly so you don't make these mistake.
Your first output is missing a closing div
<div class='container yep team-wrap'>
<div class='row'>
<div class='col-md-6'>
<img class='img-responsive' src='cdn/assets/artist/$ProfileImage'>
</div>
<div class='col-md-6'>
<strong>$FullName<br>$JobTitle</strong>
<br>
<p>$Bio</p>
<a href='mailto:$Email' class='btn btn-info'>Contact Me</a>
</div>
</div>
</div> <!-- This was missing-->
lastly you had close your if statement to quickly around the below code:
//Start Gallery Row
$output .= "
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>
";
} // CLOSED AT THE WRONG SPOT
Try the below:
<?php
$stmt = $db->prepare("my query");
$stmt->execute();
$result = $stmt->get_result();
$output = "";
$checker = [];
while ($row = mysqli_fetch_assoc($result)) {
$ID = $row['ID'];
$FullName = $row['FullName'];
$Email = $row['Email'];
$JobTitle = $row['JobTitle'];
$Bio = $row['Bio'];
$Photo = $row['Photo'];
$GalleryImage = explode(',', $row['GalleryImage']);
if (isset($Photo) && ! empty($Photo)) {
$ProfileImage = "$Photo";
} else {
$ProfileImage= "avatar.jpg";
}
if(!in_array($row['ID'], $checker)) {
$output .= "
<div class='container yep team-wrap'>
<div class='row'>
<div class='col-md-6'>
<img class='img-responsive' src='cdn/assets/artist/$ProfileImage'>
</div>
<div class='col-md-6'>
<strong>$FullName<br>$JobTitle</strong>
<br>
<p>$Bio</p>
<a href='mailto:$Email' class='btn btn-info'>Contact Me</a>
</div>
</div>
</div> <!-- This was missing-->
";
//End of info row
$output .="<br /><br /><br />";
//Start Gallery Row
$output .= "
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>
";
foreach ($GalleryImage as $img) {
//Display this row as many times as needed by data in this row.
$output .= "<img class='img-responsive' src='cdn/assets/gallery/$img'>";
}
$output .= "
</div>
</div>
</div>
";
// End gallery row
array_push( $checker, $row['ID']);
}
}
$output .= "</div>";
echo $output;
?>
Most of the time try to separate your PHP from HTML that you can see errors easily.
$stmt = $db->prepare("query");
$stmt->execute();
$result = $stmt->get_result();
$output = "";
$checker = [];
while ($row = mysqli_fetch_assoc($result)) {
$ID = $row['ID'];
$FullName = $row['FullName'];
$Email = $row['Email'];
$JobTitle = $row['JobTitle'];
$Bio = $row['Bio'];
$Photo = $row['Photo'];
$GalleryImage = explode(',', $row['GalleryImage']);
if (isset($Photo) && !empty($Photo)) {
$ProfileImage = "$Photo";
} else {
$ProfileImage = "avatar.jpg";
}
if (!in_array($row['ID'], $checker)) : ?>
<div class='container yep team-wrap'>
<div class='row'>
<div class='col-md-6'>
<img class='img-responsive' src='cdn/assets/artist/<?php echo $ProfileImage; ?>'>
</div>
<div class='col-md-6'>
<strong><?php echo $FullName; ?><br><?php echo $JobTitle; ?></strong>
<br>
<p><?php echo $Bio; ?></p>
<a href='mailto:$Email' class='btn btn-info'>Contact Me</a>
</div>
</div>
<!-- End of info row-->
<br/><br/><br/>
<!-- Start Gallery Row-->
<div class='row'>
<div class='col-md-12'>
<div id='gallery-slider' class='slider responsive'>
<!-- Display this row as many times as needed by data in this row.-->
<?php foreach ($GalleryImage as $img) : ?>
<img class='img-responsive' src='cdn/assets/gallery/<?php echo $img; ?>'>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
<!-- // End gallery row-->
<?php array_push($checker, $row['ID']); endif;
}
?
Example output
Well i'm trying to make a website as you can see, and i'm having difficulty with the "LOAD MORE" button, what i in-vision is that whenever someone clicks this button it would go through preferably a php code that tells the database to load in 5 more posts.
show_posts.php
<?php
$query = $con->query("SELECT * FROM `posts` ORDER BY `id` DESC LIMIT 5");
if( isset( $_POST['load'] ) ){
//code goes here
}
while($result = mysqli_fetch_assoc($query)){
// if video is empty then echo this line
if($result["video"] == ""){
$account_assoc = $result["account_assoc"];
$result2 = mysqli_fetch_assoc($con->query("SELECT * FROM `Accounts` WHERE username='$account_assoc' OR email='$account_assoc'"));
if($result2["username"] == ""){
$identifier = $result2["firstname"];
}else{
$identifier = $result2["username"];
}
if($result2['image'] == ""){
$image = "http://jnvbaghmara.nic.in/images/staff/Blank.png";
}else{
$image = 'data:image/jpeg;base64,'.base64_encode($result2['image']);
}
if($result['dislikes'] > 1){
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislikes";
}else{
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislike";
}
if($result['likes'] > 1){
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> likes";
}else{
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> like";
}
echo '<li>
<h4><img src="'.$image.'"/> <label>'.$identifier.'</label></h4>
<div class="all-content">
<label style="color: #777;"> '.$like.' </label><label style="color: #777;"> | '.$dislike.'</label><label style="color: #777;"> | 2 comment</label>
<p>'.$result["text"].'</p>
</div></li>';
}
// if video is not empty then echo this line
elseif($result["video"] != ""){
$account_assoc = $result["account_assoc"];
$result2 = mysqli_fetch_assoc($con->query("SELECT * FROM `Accounts` WHERE username='$account_assoc' OR email='$account_assoc'"));
if($result2["username"] == ""){
$identifier = $result2["firstname"];
}else{
$identifier = $result2["username"];
}
if($result2['image'] == ""){
$image = "http://jnvbaghmara.nic.in/images/staff/Blank.png";
}else{
$image = 'data:image/jpeg;base64,'.base64_encode($result2['image']);
}
if($result['dislikes'] > 1){
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislikes";
}else{
$dislike = "<label style='color: red;'>".format_num($result['dislikes'])."</label> Dislike";
}
if($result['likes'] > 1){
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> likes";
}else{
$like = "<label style='color: #0096f3;'>".format_num($result['likes'])."</label> like";
}
echo '<li>
<h4><img src="'.$image.'"/> <label>'.$identifier.'</label></h4>
<div class="all-content">
<iframe width="90%" height="90%" src="https://www.youtube.com/embed/'.$result["video"].'" frameborder="0" allowfullscreen></iframe>
<p>'.$result["text"].'</p>
<label style="color: #777;"> '.$like.' </label><label style="color: #777;"> | '.$dislike.'</label><label style="color: #777;"> | 2 comment</label>
</div>
</li>';
}
}
echo '<li>
<div class="all-content">
<form method="post" action="#">
<input type="submit" name="load" value="LOAD MORE..." class="load_more_button"/>
</form>
</div>
</li>';
?>
profile.php
<?php include('include/header.php'); ?>
<?php
$error = "";
if(isset($_POST['post'])){
$video = substr($_POST["video"], 17);
$text = $_POST['paragraph'];
$account_assoc = "";
if($_SESSION['username'] != ""){
$account_assoc = $_SESSION['username'];
}elseif($_SESSION['email'] != ""){
$account_assoc = $_SESSION['email'];
}
$con->query("INSERT INTO `posts` (`id`, `image`, `video`, `text`, `account_assoc`, `likes`, `dislikes`) VALUES ('', '$image', '$video', '$text', '$account_assoc', '0', '0')");
}
?>
<div class="content">
<div class="actual_content">
<div class="right-content">
<div style="padding: 10px;">
<div id="post">
<h3>Latest News</h3>
<ul class="inner-post">
<?php
$sql = $con->query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 5");
function myTruncate($string, $limit, $break=" ", $pad="..."){
if(strlen($string) <= $limit){
return $string;
}
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))) {
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
while($result = mysqli_fetch_array($sql)){
$header = $result['header'];
$statement = $result['statement'];
$image = $result['image'];
$shortdesc = myTruncate($statement, 300);
echo '<li><h5><img src="#" /><label>'.$header.'</label></h5><p>'.$shortdesc.'</p></li>';
}
?>
</ul>
</div>
</div>
</div>
<div class="left-content">
<div class="post-holder" width="70%" style="padding: 10px;">
<form class="post" method="post" action="#">
<textarea name="paragraph" placeholder="Hey there! Share a game highlight with a photo or video... <?php echo $error; ?>" maxlength="250"></textarea>
<input type="submit" name="post" class="button_post" value="POST" />
<label class="video"><input type="text" name="video" placeholder="Use a YouTube link in order to post video..."/></label><br />
</form>
</div>
<div class="new-posts" style="padding: 10px;">
<ul>
<?php include('show_posts.php')?>
</ul>
</div>
</div>
</div>
</div>
<div class="footer">
</div>
</div>
</body>
</html>
Also if there is anyway to make my code simpler, then i'm open to suggestions.
*I want the code to be php because i understand php more than i do js, jquery etc.
$postsNum = $_GET['num'];
$query = $con->query("SELECT * FROM `posts` ORDER BY `id` DESC LIMIT $postsNum");
The LOAD MORE button with a link: YOURURL?num=n
n can change by your php code.