Let me start by apologizing for the information overload. I have no idea what is not working, so I included a little of everything here.
I have a page named jobs.php that shows a table of open 'jobs' on the left side. When the add job button is clicked, the form to add a new job is loaded into the div on the right side of the page using this:
//Get Next Job
$query = "SELECT * FROM jobs WHERE job_id = (SELECT MAX(job_id) FROM jobs)";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
$topjob = $result->fetch_assoc();
$nxtjob = $topjob['job_id'] + 1;
<button class="btn btn-primary pull-right ajaxCall" id="addJobBtn" onclick="nxtJob('<?php echo $nxtjob; ?>')">Add Job</button>
function nxtJob(job) {
var nxtjob = job;
$("#jobDetails").html("Loading...");
$.ajax({
type: "GET",
data: {'id':nxtjob},
url: "addjob.php",
async: true,
success: function(data) {
$("#jobDetails").html(data);
}
});
}
The reasoning behind the get variable is that I need the next job # to be used as a value in the form.
The form itself is on addjob.php, and the very simplified version is this:
<?php
require 'database.php';
if (isset($_POST['addNewJob'])) {
$error = '';
//Check Job # for duplicate if manually changed
$job = $_POST['addjob'];
$query = "SELECT job_id from jobs WHERE job_id = '$job'";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if (mysqli_num_rows($result) > 0) {
$error .= '<br/>Job # already exists.'
}
if ($error == '') {
//Set variables for insert
$job = $mysqli->real_escape_string($_POST['addjob']);
$status = $mysqli->real_escape_string($_POST['addstatus']);
$sql = "INSERT INTO jobs (job_id, status)
VALUES ('$job', '$status')";
if (mysqli_query($mysqli, $sql)) {
$validation = '< div class="alert alert-success" > Job ' . $job . ' Successfully Added </div >';
} else {
$validation = '<div class="alert alert-danger" > "ERROR: Could not able to execute' . $sql . mysqli_error($mysqli);
}
} else {
$validation = ' <div class="alert alert - danger">Job Not Added:' . $error . '</div>';
}
?>
<form class="form - horizontal" method="post" id="addJobForm">
<div class="form - group">
<label for="addjob" class="col - sm - 2 control - label">Job #</label>
<div class="col - sm - 4">
<input type="text" class="form - control" name="addjob"
value=" <?php echo $nxtjob; ?>">
</div>
<label for="addstatus" class="col-sm-2 control-label">Status</label>
<div class="col-sm-4">
<?php
$options = array("New", "In Progress", "Waiting for Parts", "Ready for Customer", "Completed");
?>
<select class="form-control" name="addstatus">
<?php foreach ($options as $option): ?>
<option>
<?php echo $option; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<button type="submit" name="addNewJob" id="addNewJob" class="btn btn-primary pull-right">Submit New
Job
</button>
</form>
<?php echo $validation; ?>
When the add job button is clicked on jobs.php (below), the form loads beautifully, but it doesn't work.
<div class="row">
<div class="col-md-4">
<table class="table table-hover" id="jobTable" data-link="row">
<thead>
<tr>
<th class="col-md-2">Job #</th>
<th class="col-md-4">Customer Name</th>
<th class="col-md-6">Description</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($jobs)) {
// Print out the contents of the entry
date_default_timezone_set('America/Los_Angeles');
$startdate = date("m/d/Y", strtotime($row['started']));
echo '<tr>';
echo '<td><a class="ajaxCall" href="#" rel="' . $row['job_id'] . '"></a>' . $row['job_id'] . '</td>';
echo '<td>' . $row['cust_name'] . '</td>';
echo '<td class="col-lg-2">' . $row['description'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class="col-md-8">
<div id='jobDetails'></div>
</div>
</div>
When I click Submit New Job, the right side of the page simply goes blank. The form disappears, and no new entry is created in the sql table. However, the form works just fine if I use it directly from addjob.php.
I've read about binding after an AJAX call, and I'm guessing it has something to do with that, but I can't seem to get it working. This is my first attempt at AJAX, so any help is appreciated.
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 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 about to make a note system in procedural PHP and AJAX, which should allow me to both display new notes without refreshing and to load more notes without refreshing.
In my current case both works, but not together. If no notes to show from the database, then my site will display a text saying "There is no notes to display". If I then make a note, it still won't display the note, until I load it in via a click on the loading notes button.
I've tried to add in following to my success function:
if(res.indexOf("success")!=-1) {
location.reload(true);
}
Without any luck, even I could read on the internet, that it somehow worked out for other people.
Here is my ajax functions:
$(document).ready(function() {
var noteCount = 2;
$("#loadMore").click(function() {
noteCount = noteCount + 2;
$("#notes").load("load-notes.php", {
noteNewCount: noteCount
});
});
$("#noteform").on("submit", function(event) {
event.preventDefault();
noteCount = noteCount + 1;
var form_data = $(this).serialize();
$.ajax({
url: "add-notes.php",
method: "POST",
noteNewCount: noteCount,
data: form_data,
dataType: "JSON",
success: function(data) {
if(res.indexOf("success")!=-1) {
location.reload(true);
}
}
});
});
});
My add-notes.php
<?php
session_start();
require_once "../inc/core/config.php";
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit;
$subject = mysqli_real_escape_string($dbconn, $_POST['subject']);
$note = mysqli_real_escape_string($dbconn, $_POST['note']);
$my_date = date("Y-m-d H:i:s");
$author = $_SESSION['u_firstname'];
$noteNewCount = $_POST['noteNewCount'];
$sql = "INSERT INTO notes(author, subject, note, created_at) VALUES ('$author', '$subject', '$note', '$my_date')";
mysqli_query($dbconn, $sql);
$sql = "SELECT * FROM notes LIMIT $noteNewCount";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
The note div where my notes are displayed and the form where they are created:
<form id="noteform" action="add-notes.php" method="POST" >
<div class="form-group">
<label for="usr">Titel:</label>
<input type="text" class="form-control" name="subject">
</div>
<div class="form-group">
<label for="pwd">Note:</label>
<textarea class="form-control" rows="5" name="note"></textarea>
</div>
<button class="btn btn-outline-success my-2 my-sm-0" name="submit" type="submit">Opret note</button>
</form>
<div id="notes">
<?php
$sql = "SELECT * FROM notes LIMIT 2";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
?>
</div>
So to sum up, I am looking for a way to display a new note made, without having to load it in via my load button. What can I do?
Instead of location.reload, you can just replace the HTML in #notes. Also, in add-notes.php you are echoing HTML but in your ajax, you are expecting dataType: json. Also, not sure what is noteNewCount being passed to AJAX.
$.ajax({
url: "add-notes.php",
method: "POST",
data: form_data,
success: function(data) {
$("#notes").html(data);
}
});
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
I have three different div's that contain the checkout information.
Shipping info
Billing Info
Order confirmation
The shipping information and billing information is obtained by the customer entering that information in manually, but the order confirmation, that contains what they are ordering, the quantity, and pertinent information to that order resides there. That information is obtained from a foreach loop I have in place that displays the information based on the product's ID.
I am trying to figure out how I am going to INSERT the string that displays from my foreach loop into my database. I have an order report page that I want to display what was ordered.
For the shipping information, I validate it and then send my query in with that information. Like this...
<?php
if(Input::exists()) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'fullname' => array(
'required' => true,
'min' => 2,
'max' => 50
)
if($validation->passed()) {
if(isset($_POST['create'])){
$fullname = trim( $_POST['customer_name'] );
?>
<div class="field">
<label class="paddingleft" for="fullname">Full Name</label>
<div class="center"><input type="text" class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required></div>
</div>
The part that I am really confused with is how to INSERT the actual string this foreach loop displays. If the result of my foreach loop was:
2 balls
4 shoes.
I want that information to send in with my query.
This is how I have the Order confirmation section as of now..
<div class="checkoutconfirmationcontainer">
<?php foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
?>
<span class="tealmedium"><?php echo $product['quantity'] . " - " . $products[$product_id]['name'] . $message; ?></span><br><br><br>
<div class="floatleft"><div class="smallerimgcontainer">
<?php
$result = mysqli_query($con,"SELECT * FROM products");
if($row = mysqli_fetch_array($result)) {
$products[$row['product_id']] = $row;
if($row['image'] == ""){
echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
} else {
echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
}
echo "<br><br><br><br>";
}
?>
</div></div>
<div class="checkoutitemsummary">
<?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
<p><span class="redprice"><?php echo '$' . $products[$product_id]['price'] . "<br />"; }?></span></p>
</div>
How can I get the results of my foreach loop to be inserted into my database with my query?
Shopping Cart
<tr>
<th class="cartth">Name</th>
<th class="cartth">Price</th>
<th class="cartth">Category</th>
<th class="cartth">Quantity</th>
</tr>
<?php
$base_price = 0;
foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
$base_price += $products[$product_id]['price'] * $product['quantity'];
$shipping_price += $products[$product_id]['shippingprice'] * $product['quantity'];
?>
<tr>
<td class="carttd"><?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
</td>
<td class="carttd"><?php echo '$' . $products[$product_id]['price']; ?></td>
<td class="carttd"><?php echo $products[$product_id]['category']; ?></td>
<td class="carttd">
<?php echo "<input type='text' name='quantity[$product_id]' value='" . $product['quantity'] . "' />"; ?> </td>
</tr>
<?php
}
Javascript/Jquery that produces my div transition:
$('.checkoutmenu>li').on('click',function(e){
$('.checkoutprocess>.'+ e.target.classList[0]).show().siblings().hide();
});
<script>
$('.paymentinfocontainer').hide();
$('.confirmationinfocontainer').hide();
</script>
<script>
$('#button2').click(function () {
$(".checkoutprocess > div").hide();
$('.paymentinfocontainer').show("slow");
});
</script>
<script>
$('#button3 ').click(function () {
$(".checkoutprocess > div").hide();
$('.confirmationinfocontainer').show("slow");
});
</script>
<script>
/*
$('#button1').click(function () {
$(".checkoutprocess > div").hide();
$('.shippinginfocontainer').show("slow");
});
</script>
<script>
$('#button2 ').click(function () {
$(".checkoutprocess > div").hide();
$('.paymentinfocontainer').show("slow");
});
</script>
<script>
$('#button3 ').click(function () {
$(".checkoutprocess > div").hide();
$('.confirmationinfocontainer').show("slow");
});
*/
</script>
Ok, when I clicked on "3. Order Confirmation", I got the following HTML:
<div class="confirmationinfocontainer" style="display: block;">
<span class="summarytitle"><p>Order Confirmation</p></span>
<br>
<div class="floatrightinline">
<div class="confirmshippinginfo">
<p>Shipping to:</p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
</div>
<div class="checkoutconfirmationcontainer">
<div name="product_id"></div>
<span class="tealmedium">1 - Lakers Hat</span>
<br>
<br>
<br>
<div class="floatleft">
<div class="smallerimgcontainer">
<img alt="Coming Soon" src="/productpics/coming_soon.png" class="sizedimg">
<br>
<br>
<br>
<br>
</div>
</div>
<div class="checkoutitemsummary">
Lakers Hat
<p><span class="redprice">$25<br></span></p>
</div>
<input type="hidden" value="405bb6b2b562b4f00dac620d3f68620f" name="token">
<input type="submit" value="Place Your Order" class="widebutton">
<br>
</div>
</div>
So I see you're already making use of a hidden field. So when a users clicks the "Place Your Order" button, you want the details to be passed along. You can simply add these details back to the form via a hidden field. Like so:
<div class="checkoutconfirmationcontainer">
<?php
foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
?>
<input type="hidden" name="product_quantity[<?php echo $id; ?>]" value="<?php echo $product['quantity']; ?>" />
<span class="tealmedium"><?php echo $product['quantity'] . " - " . $products[$product_id]['name'] . $message; ?></span><br><br><br>
<div class="floatleft"><div class="smallerimgcontainer">
<?php
$result = mysqli_query($con,"SELECT * FROM products");
if($row = mysqli_fetch_array($result)) {
$products[$row['product_id']] = $row;
if($row['image'] == ""){
echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
} else {
echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
}
echo "<br><br><br><br>";
}
?>
</div></div>
<div class="checkoutitemsummary">
<?php echo "<a href='./viewProduct.php?view_product=$id'>{$product['name']} {$products[$product_id]['name']}</a>"; ?>
<p><span class="redprice"><?php echo '${$products[$product_id]['price']}<br />"; }?></span></p>
</div>
<input type="hidden" name="token" value="405bb6b2b562b4f00dac620d3f68620f">
<input class="widebutton" type="submit" value="Place Your Order">
<br />
</div>
Looking over this, I see no <form> for this. So I suspect JQuery is handling this somewhere else. So my fix may not really get read if your JQuery or app does not now what to look for, or does not hook onto that hidden field. If this is a framework that you're using or Catalog that you're modifying, check their support. I would say you have a lot more work ahead of you.