PHP - Foreach via Certain active Sessions - php

I'm currently working on a super simple Online shop idea with a shopping cart. At the end i want to print out a table with the products you ordered. Currently using a foreach but i have no idea how to solve this. I tried to use sessions as a way to give the loop an idea how many different products are ordered. But it seems like the $_SESSION way will take all the current active sessions. And using a simple variable f.e. $piano will make it print 2 rows ( using 2 piano's in my shop, tried to solve it with a if (session active) $piano1 = active. But it seems the foreach statement doesn't give a whoop about that and will print 2 rows anyways.
Sorry for the long block of text. Here's my page. Again apologies. I just started php.
Variable names are dutch but that shouldn't really matter for you guys i think.
Starting from line 103.
Thanks in advance!
<div class="logincontainer"><!-- Php Session Script Actief? -->
<?php
session_start();
if(isset($_SESSION['naam'])) :
echo "<div class='content_login'>";
echo "Hallo " . $_SESSION['naam'] . ". Welkom bij de Pianoshop.</br></br>";?>
<form method='post' action='uitlog.php'>
<input type='submit' name='loguit' Value='Loguit!'></form><br />
<form action='winkelmand.php' class="left">
<input type='image' src='images/winkelwagen-knop.png'/>
</form><br />
<form method='post' name='emptycart' action='emptycart.php' class="right">
<input type="submit" id="submitpic" name="leegwinkelmand" value="">
<?php
if(isset($_SESSION['winkelmand'])) {
echo $_SESSION['aantalproducten'] . " Item(s) - €" . $_SESSION['totaalprijs'] . ",-";
} else {
echo "Jouw winkelwagen is leeg.";
}?>
</form>
</div>
<?php else :?>
<div class='content_login'>
<form method='post' action='checklogin.php'>
<p><input type='text' name='gebruikersnaam' required='required' value='' placeholder='Gebruikersnaam'></p>
<p><input type='password' name='password' required='required' value='' placeholder='Wachtwoord'></p>
<font color="red"><p class='submit'>
<input type='submit' name='login' value='Login'>
<?php if(isset($_SESSION['logged_in'])) :?>
Verkeerd wachtwoord.
<?php session_destroy();
endif; ?>
</p></font>
<p>Nog niet geregistreerd? Doe dat hier!.</p>
</form>
</div>
<?php endif; ?></div>
<div id="site">
<div id="menubar">
<div id="logo">
<img src="images/pianotoetsen.png" >
</div>
<div id="menu_items">
<ul id="menu">
<li>Home</li>
<li>Toetsinstrumenten</li>
<li>Jouw account</li>
<li class="current">Winkelmand</li>
<li>Contact</li>
</ul>
</div></div>
<div id="site_content">
<div class="sidebar_container">
<div class="sidebar">
<h2>Sale!</h2>
<div id="thumbnail"><img src="images/piano1.jpg"></div>
<p>Yamaha CLP-575 voor maar €2599,- !</p>
<div id="thumbnail"><img src="images/piano2.jpg"></div>
<p>Ritmuller 120SL €4999,- !</p>
</div>
<div class="sidebar">
<h2>Laatste Updates</h2>
<h3>Juni 2015</h3>
<p>Site in constructie.</p>
</div>
<div class="sidebar">
<h3>Wij zijn op Facebook</h3>
<p>Klik hier.</p>
</div>
</div>
<div id="content">
<div id="wallpaperbanner">
<img src="images/banner.jpg">
</div>
<div class="content_item">
<h1>Winkelmand</h1>
<?php
$user = 'root';
$pass = '';
$db = 'online shop';
$conn = mysql_connect('localhost', $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(isset($_SESSION['winkelmand'])) {
echo "Deze producten staan in je winkelwagen</br></br>";
if(isset($_SESSION['totaalprijs2']) == 0) {
// Do nothing?
} else {
mysql_select_db($db);
$query = mysql_query("SELECT * FROM product WHERE productnummer='2'");
$productgegevens = mysql_fetch_row($query);
$piano["piano2"] = "ritmuller";
$pianoarray[1] = $productgegevens['1'];
$pianoarray[2] = $productgegevens['2'];
$pianoarray[3] = $productgegevens['4'];
$pianoarray[5] = $productgegevens['3'];
$pianoarray[4] = $_SESSION['aantal_prod2'];
}
if(isset($_SESSION['totaalprijs1']))
{
mysql_select_db($db);
$query = mysql_query("SELECT * FROM product WHERE productnummer='1'");
$productgegevens = mysql_fetch_row($query);
$piano["piano1"] = "yamaha";
$pianoarray[4] = $_SESSION['aantal_prod1'];
$pianoarray[1] = $productgegevens['1'];
$pianoarray[2] = $productgegevens['2'];
$pianoarray[3] = $productgegevens['4'];
$pianoarray[5] = $productgegevens['3'];
$pianoarray[4] = $_SESSION['aantal_prod2'];
}
echo "<br />
<table width='80%' >
<thead>
<tr><th>Productnaam</th><th>Merk</th>
<th>Voorraad</th><th>Aantal</th><th>Prijs</th>
</tr>
</thead>
<tbody>";
foreach($piano as $key => $value) {
echo $key . "</br>" . $value . "<br />";
$row = "<tr>";
for ($x=1; $x<=sizeof($pianoarray); $x++){
$row = $row . "<td>" . $pianoarray[$x] . "</td>";
}
$row = $row . "</tr>";
echo $row;
}
echo "<tr><td></td><td></td><td></td><td></td><td>" . '€' . $_SESSION['totaalprijs'] . ',-' . "</td></tr></tbody></table>";
}
else {
echo "Jouw winkelwagen is leeg. <br />" . "Klik <a href='toetsinstrumenten.php'>Hier</a> om wat items toe te voegen.";
}?>
</div>
</div>
</div>
</div>

Create an array variable in the $_SESSION array and do a foreach loop on that
$_SESSION['cart']['piano1'] = 'piano1';
$_SESSION['cart']['piano2'] = 'piano2';
$cart = $_SESSION['cart'];
foreach ($cart as $key => $item) {
//do something with $item or $key
}

Related

multiple checkbox values into same sql column?

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>

How Do I Create a Vanity URL After Submit

Hello so I have a site setup to where users can submit projects and it adds it to a upload folder and the database for user download anyway I want to have it so once a user submits a new project it creates a URL like “sitename.com/projects.html?projectname” or something like that. My code is below.
P.S Everything on my site works just need to learn how to create the url.
projects.html: Mainly used to display the recent projects.
<?php include("includes/header.php"); ?>
<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename, title, description from tbl_files LIMIT 4";
$result = mysqli_query($con, $sql);
?>
<div id="container">
<div class="wrapper">
<div id="content">
<h2>Recent Projects <button style="float: right;">New Project</button></h2>
<p><table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>File Name</th>
<th>Description</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><a href="uploads/<?php echo $row['filename']; ?>" download>Download</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</p>
<div id="column">
<div class="holder">
<h2>Welcome!</h2>
<ul id="latestnews">
<li class="last"> <p><?php
session_start();
include_once "vendor/autoload.php";
$page = new membership\Page(1);
if ($page->isValid() == true){
echo "Hello " . $_SESSION["username"] . "!<br /><br />
<a href='logout.html'>Logout</a>\n";
} elseif ($page->isValid() == false) { echo "<center>Please <a href='login.php'>Log in</a> to share projects.<br /> <a href='register.php'>Need A Account?</a></center>";}
?><br />
</p>
<br /></p>
</li>
</ul>
</div>
</div>
<br class="clear" />
</div>
</div>
<?php
error_reporting(E_ALL & ~E_NOTICE);
include('includes/memberlistconfig.php');
// call this file only after database connection
require_once 'functions.php';
?>
<div id="container">
<div class="wrapper">
<div id="content">
<h2>Categories</h2>
<p>
<div class="height20"></div>
<?php echo $emsg; ?>
<article>
Click on one of the categories to see what’s inside.
<ul>
<?php
$res = fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
}
?>
</ul>
</article>
</div></p>
<br class="clear" />
</div>
</div>
<?php include("includes/footer.php"); ?>
new-project.html: Allows used to upload a new project.
<?php
include_once('includes/header.php'); ?>
<?php
include_once 'dbconnect.php';
// fetch files
$sql = "select filename from tbl_files";
$result = mysqli_query($con, $sql);
?>
<?php
session_start();
include_once "vendor/autoload.php";
$page = new membership\Page(1);
if ($page->isValid() == true) {
?>
<div id="container">
<div class="wrapper">
<div id="content">
<h2>New Project</h2>
<p><center>
<form action='upload.php' method='post' enctype='multipart/form-data'>
<legend>Select File to Upload:</legend>
<div class='form-group'>
Title: <br /><input type='text' name='title' maxlength="255"/><br /><br />
Description: <br /><textarea type='text' name='description' maxlength="2000"></textarea><br /><br />
<input type='file' name='file1' />
</div>
<div class='form-group'><br />
<input type='submit' name='submit' value='Upload' class='btn btn-info'/>
</div>
<?php if (isset($_GET['st'])) { ?>
<div class='alert alert-danger text-center'>
<?php
if ($_GET['st'] == "success") {
echo "File Uploaded Successfully!";
} else {
echo 'Invalid File Extension!';
}
?>
</div>
<?php } ?>
</form></center>
</p><?php } ?>
<br /></div>
</p>
<div id="column">
<div class="holder">
<h2>Project Upload Rules</h2>
<ul id="latestnews">
This is this rules you must follow for uploading a project.<br /><br />
- You must own the project / script.<br />
- Must be 100% clean / safe.<br />
- Code must be easy to read.<br />
- No outdated code.<br />
<br />
If you don’t follow the rules your account who be banned.
<br />
</p>
<br /></p>
</li>
</ul>
</div>
</div>
<br class="clear" />
</div>
</div>
<?php include_once('includes/footer.php'); ?>
upload.php: This file uploads the info to the database.
<?php include('dbconnect.php'); ?>
<?php
//check if form is submitted
if (isset($_POST['submit']))
{
$filename = $_FILES['file1']['name'];
//upload file
if($filename != '')
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = ['zip', 'rar', 'php', 'html', 'sql'];
//check if file type is valid
if (in_array($ext, $allowed))
{
// get last record id
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
if (count($result) > 0)
{
$row = mysqli_fetch_array($result);
$filename = ($row['id']+1) . '-' . $filename;
}
else
$filename = '1' . '-' . $filename;
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H:i:s');
move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename));
$title = '';
if(!empty($_POST['title']))
{
$title = mysqli_real_escape_string($con, $_POST['title']);
}
$description = '';
if(!empty($_POST['description']))
{
$description = mysqli_real_escape_string($con, $_POST['description']);
}
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created, title, description) VALUES('$filename', '$created', '$title', '$description')";
mysqli_query($con, $sql);
header("Location: new-project.html?st=success");
}
else
{
header("Location: new-project.html?st=error");
}
}
else
header("Location: new-project.html");
}
?>

php get info from mysql

So by the way i want to get the nickname of member by faction id. but its not printing name. whats wrong with my code? when i print $nickname its not giving me anything too.
<?php
require 'db.php';
session_start();
$result = $mysqli->query("SELECT nickname FROM members WHERE fraction='3'");
print($result->num_rows);
?>
<div class="form">
<ul class="tab-group">
<li class="tab">LS-PD</li>
<li class="tab active">BALLAS</li>
</ul>
<div class="tab-content">
<div id="ballas">
<h1>Ballas</h1>
<form action="index.php" method="post" autocomplete="off">
<div class="top-row">
<div class="field-wrap">
<label>
Name<span class="req">*</span>
</label>
</div>
</div>
<?php
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "<p class='monitoring-name'>" . $row['nickname'] . "</p><br>";
}
}
?>
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
This may help you. Add a check to make sure that your query is right, so if it is then it will run the code, else it will generate an error:
$query = "SELECT nickname FROM members WHERE fraction = 3";
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "<p class='monitoring-name'>" . $row['nickname'] . "</p><br>";
}
}
else
{
echo "No results found"; // pretty clear?
}
}
else
{
// if there's an error with your query it will display this message:
echo "There was a problem with your query";
}

Comment system issue

I have a problem with my comment system. At the moment it is just simple adding to database sorting and showing under right post on the blog. I am creating, I will implement ajax etc later.
The issue I am having right now is that it shows the last comment on the post below the one I added comment on. So lets say I am adding comment on post 10, it will show comment on post 10 and 11. It sorts correctly, but it duplicates to the post below too. (It doesn't duplicate in database just the way it displays.)
<?php
// Connect to the database
include('../acp/db/db.php');
$link = mysql_connect($dbhost, $dbuser, $dbpassword, $dbname);
mysql_select_db($dbname);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id_post = $row['id'];
echo " <!-- Blog Post Content Column -->
<h1> " . $row['post_title'] . " </h1><p class='lead'>
by <a href='#'>Matt</a></p> <hr>
<p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
<img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
<p class='lead'>" . $row['post_first'] . "</p>
<p>" . $row['post_second'] . "</p> <hr>
<!-- Comments Form -->
<div class='well'>
<h4>Leave a Comment:</h4>
<form id='form'method='POST'action='php/insert-comment.php'>
<input type='hidden' name='post_id' value='$id_post'>
<input type='text' id='comment-name' name='name' placeholder='Your name' />
<input type='text' id='comment-mail' name='mail' placeholder='Your e-mail adress' />
<textarea type='text' name='comment' class='the-new-com' rows='3'></textarea>
<input type='submit' id='submit' class='bt-add-com' value='Submit Comment'></input>
</form>
</div>
<hr>
<div class='media comment-block'>
<a class='pull-left' href='#'>
<img class='media-object' src=' $grav_url' >
</a>
<div class='media-body'>$name
<h4 class='media-heading'>
<small>$date</small>
</h4>
$comment
</div>
</div>";
$resultcomments = mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post'") or die(mysql_error());
while($affcom = mysql_fetch_assoc($resultcomments)){
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
echo"
<!-- Posted Comments -->
<!-- Comment -->
<div class='media comment-block'>
<a class='pull-left' href='#'>
<img class='media-object' src=' $grav_url' >
</a>
<div class='media-body'>$name
<h4 class='media-heading'>
<small>$date</small>
</h4>
$comment
</div>
</div>";
}
}
?>
I am slowly learning PHP so be easy on me. I feel like the issue is easy to fix, and it is right there I just cannot work out what it is.

foreach loop results to INSERT into database

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.

Categories