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>
Related
I'm not seeing what goes wrong here? I want to allow my users to up the quantity from an item in their shopping cart. when they press enter I want the quantity to change from 1 to the number the use rput in and I want that it calculates everything correctly. but right now it only wants to update the last item that the user changed the quantity from. how do I fix this? I thought of using a $_SESSION but that doesn't make any difference. this is part of the code
<body>
<!--navbar-->
<a class="back" href="index.php"> <i class="bi bi-arrow-left-circle-fill bi-5x"></i></a>
<?php
include "config.php";
?>
<div class="text-center" style="font-size: 100px;">🛍</div>
<h2 class="text-center">Winkelmandje</h2><br>
<section class="container content-section">
<!-- <h2 class="section-header">CART</h2> -->
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-item cart-header cart-column">PRICE</span>
<span class="cart-item cart-header cart-column">QUANTITY</span>
<span class="cart-item cart-header cart-column">berekening</span>
<!-- <span class="cart-item cart-header cart-column">Verwijderen</span> -->
</div>
<?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
if( in_array( $broodjes ,$_SESSION['basket']) )
{
}else{
$_SESSION['basket'][] = $broodjes;
}
}else{
$_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
//echo "Key = $key; value = $value; <br>";
$sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo $row['broodnaam'];
echo '</div>';
echo '<div class="cart-item cart-column">';
echo '€ ' . $row['prijs'];
echo '</div>';
//quantity
echo '<div class="cart-item cart-column">';
echo '<form method="POST" action"">';
echo '<div class="col-xs-4">';
echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" placeholder="1" min="1" max="100" value="1">';
echo '</div>';
echo '</form>';
echo '</div>';
//session for quantity???'
$_SESSION['quantity'] = $_POST['quantity'];
$quantity = 1;
if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
$_SESSION['quantity'] = $_POST['quantity'];
if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
if ($_POST['broodnaam'] == $row['broodnaam']){
$quantity = $_POST['quantity'];
}
}
}
echo '<div class="cart-item cart-column">';
$rowtotaal = $row['prijs'] * $quantity;
$sumtotal += $rowtotaal;
echo $rowtotaal;
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?> <br />
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € <?php echo $sumtotal;?></span>
</div>
<br/>
and this is what it does
now situation:
how do I store the information in a session??
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 want to know how to add the logged in user's id in url (like ?id=")
I have searched a bit on Google, but I couldn't find anything that worked.
Here's the PHP code:
<?php
include("nav.php");
require("app/management/config.php");
session_start();
if(!isset($_SESSION['login_user']))
{
header("Location: index");
}
?>
<!DOCTYPE html>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!--<link rel="stylesheet" href="../css/providers.css">-->
<link rel="stylesheet" href="../css/main.css">
<link rel="stylesheet" href="../css/main2.css">
<meta charset="UTF-8">
<header class="header__wrapper wrapper">
<a href="/" class="header__habbo__logo">
<h1 class="header__habbo__name" id="ga-linkid-habbo-large"></h1>
</a>
</header>
<body>
<?php
include("header.php");
?>
<div class="info-block-homes">
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM `users` WHERE username = '{$_SESSION['login_user']}'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
echo '<h1><font color="Red">Your Public Information:</font></h1>';
echo '<font color="green">' . $motto . '</font><font color="white">' . $row['motto'] . ' </font></br>';
echo '<font color="green">' . $credits . '</font><font color="white">' . $row['credits'] . ' </font></br>';
echo '<font color="green">' . $pixels . '</font><font color="white">' . $row['pixels'] . ' </font></br>';
echo '<font color="green">' . $points . '</font><font color="white">' . $row['points'] . ' </font></br>';
echo '<font color="green">' . $rank . '</font><font color="white">' . $row['rank'] .'</font>';
echo '<div style="margin-top:-130px; margin-left:150px;"><img src="http://www.habbo.com/habbo-imaging/avatarimage?figure='.$row['look'].'\"></div>';
?>
</div>
<div class="badges-block">
<h1><font color="Red">Your Badges:</font></h1>
<?php
$login_session=$_SESSION['login_user'];
$sql = "SELECT
so.*,
sr.*
FROM users AS so
INNER JOIN users_badges AS sr ON so.id = sr.user_id WHERE username = '{$_SESSION['login_user']}';";
$result = $dbconfig->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src='badges/".$row["badge_code"].".gif'>";
}
} else {
echo "0 results";
}
$dbconfig->close();
?>
</div>
<?php
include("footer.php");
?>
<div id="arrow-up-logout-homes" class="mydiv2"><ul><li><font color="white">Log Out</font></li></ul></div>
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online-me" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM `users` WHERE username = '{$_SESSION['login_user']}'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
header('Location: /homes?id='.$row['id']);
exit;
?>
</body>
</head>
</html>
login page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://d3hmp0045zy3cs.cloudfront.net/2.2.21/providers.css">
<?php
require("nav.php");
echo "<title>$title - $desc - $title</title>";
?>
<?php
require("app/management/config.php");
session_start();
if(isset($_SESSION['login_user']))
{
header("Location: me");
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password received from loginform
$username=mysqli_real_escape_string($dbconfig,$_POST['username']);
$password=mysqli_real_escape_string($dbconfig,$_POST['password']);
$securitykey=mysqli_real_escape_string($dbconfig,$_POST['securitykey']);
$sql_query="SELECT * FROM users WHERE username='$username' and password='$password' and securitykey='$securitykey'";
$result=mysqli_query($dbconfig,$sql_query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$count=mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$username;
header("location: me");
}
else {
$result = '<div style="position:absolute; margin-left:400px;">Invalid username or password (do not forget the security key if you got one)</div>';
echo "$result";
}
}
?>
<link rel="stylesheet" href="../css/main.css">
<link rel="stylesheet" href="../css/main2.css">
<head>
<header class="header__wrapper wrapper">
<a href="/" class="header__habbo__logo">
<h1 class="header__habbo__name" id="ga-linkid-habbo-large"></h1>
</a>
</header>
<body>
<div class="login-block">
<form method="post" action="" name="loginform">
<input type="text" value="" placeholder="Username" id="username" name="username" />
<input type="password" value="" placeholder="Password" id="password" name="password" />
<input type="securitykey" value="" placeholder="Security Key" id="securitykey" name="securitykey" />
<button type="submit">Submit</button>
</form>
</div>
<body>
<?php
include("header.php");
?>
<div id="content">
<!--<?php
// Create connection
$sql = "SELECT id, message, username FROM cms_message";
$result = $dbconfig->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<marquee behavior="scroll" direction="left">'.$row['username'].' says: '.$row['message'].'</marquee>';
}
} else {
echo "0 results";
}
$dbconfig->close();
?>-->
<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
<div id="arrow-up" class="mydiv2"><ul><li><font color="white">Register Now!</font></li></ul></div>
</br>
</br>
</br>
</br>
</br>
</br>
<?php
{
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query="SELECT * FROM cms_news WHERE highlighted = '1' AND date IN (SELECT max(date) FROM cms_news)";
$data = mysqli_query($con, $query);
while($row = mysqli_fetch_array($data))
{
echo '<main class="wrapper wrapper--content" ui-view="">
<section>
<h1 translate="NEWS_TITLE">Latest news</h1>
<div class="main main--fixed">
<habbo-compile data="NewsController.promos">
<section>
<article class="news-header news-header--column">
<a href="'.$row["link"].''.$row["room_id"].'" class="news-header__link news-header__banner">
<figure class="news-header__viewport">
<img src="'.$row["image"].'" alt="'.$row["image"].'" class="news-header__image news-header__image--featured">
<img src="'.$row["thumbnail"].'" alt="'.$row["thumbnail"].'" class="news-header__image news-header__image--thumbnail">
</figure>
</a>
<a href="/hotel?room='.$row["room_id"].'" class="news-header__link news-header__wrapper">
<h2 class="news-header__title">'.$row["title"].'</h2>
</a>
<aside class="news-header__wrapper news-header__info">
<time class="news-header__date">'.$row["date"].'</time>
<ul class="news-header__categories">
<li class="news-header__category">
'.$row["category"].'
</li>
</ul>
</aside>
<p class="news-header__wrapper news-header__summary">'.$row["description"].'</p>
</article>
</section>
</main> ';
}
mysqli_close($con);
}
?>
<?php
{
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$query="SELECT * FROM cms_news WHERE highlighted = '0'";
$data = mysqli_query($con, $query);
while($row = mysqli_fetch_array($data))
{
echo '<div style="margin-top:-30px;"><main class="wrapper wrapper--content" ui-view="">
<article class="news-header">
<a href="/community/article/21340/habboxs-summer-weekend-event" class="news-header__link news-header__banner">
<figure class="news-header__viewport">
<img src="'.$row["thumbnail"].'" alt="'.$row["thumbnail"].'" class="news-header__image news-header__image--thumbnail">
</figure>
</a>
<a href="'.$row["link"].''.$row["category"].'" class="news-header__link news-header__wrapper">
<h2 class="news-header__title">'.$row["title"].'</h2>
</a>
<aside class="news-header__wrapper news-header__info">
<time class="news-header__date">'.$row["date"].'</time>
<ul class="news-header__categories">
<li class="news-header__category">
'.$row["category"].'
</li>
</ul>
</aside>
<p class="news-header__wrapper news-header__summary">'.$row["description"].'</p>
</article>
</main>
</div>';
}
mysqli_close($con);
}
?>
</div>
</div>
<?php
include("footer.php");
?>
</body>
</head>
</html>
Try:
header("Location: index?id=".$id);
As php.net says you need to use exit after header
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
so use this code:
header('Location: /index?id='.$row['id']);
exit;
Use this code:
header('Location: index?id='.$row['id']);
exit;
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
}
I've got a problem with a contact form on my webpage.
When someone fills it in, i always got the error message that something isn't filled in right.
It seems to be the telephone number.
The link to the webpage is http://www.tiggelovend-kok.nl/index.php/contact/
<?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class="wider_blog">
<div class="_blog">
<div class="topbar"><div class="row">
<?php
echo beopen_main_title();
if (beopen_get_option('show_breadcrumbs') == '2') {
echo beopen_breadcrumb();
}
?>
</div></div>
<?php
if (beopen_get_option('show_map') != 1) {
?>
<div id="map_canvas_shadow"></div>
<div id="map_canvas"></div>
<?php
}
?>
<div class="row">
<!-- Row for main content area -->
<div id="content" class="eight columns rightfade" role="main">
<div class="post-box">
<article class="contact">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php if (beopen_get_option('show_contact_form') == 2) { ?>
<?php echo beopen_get_option('contact_form_text'); ?>
<form class="beopen-contact-form" action="<?php echo get_permalink(); ?>" method="post">
<?php
require_once(THEME_LIBRARY . '/recaptchalib.php');
$error_contact_name = '';
$error_contact_email = '';
$error_contact_phone = '';
$error_contact_company = '';
$error_contact_message = '';
$contact_name = '';
$contact_email = '';
$contact_company = '';
$contact_phone = '';
$contact_message = '';
$publickey = beopen_get_option('recaptcha_public_key');
$privatekey = beopen_get_option('recaptcha_private_key');
if (isset($_POST['beopen_form'])) {
foreach ($_POST as $key => $val) {
$GLOBALS[$key] = wp_filter_kses($val);
}
$send = 0;
if (beopen_get_option('show_recaptcha') == 2) {
$recaptcha_challenge_field = '';
if (isset($_POST["recaptcha_challenge_field"])) {
$recaptcha_challenge_field = $_POST["recaptcha_challenge_field"];
}
$recaptcha_response_field = '';
if (isset($_POST["recaptcha_response_field"])) {
$recaptcha_response_field = $_POST["recaptcha_response_field"];
}
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $recaptcha_challenge_field, $recaptcha_response_field);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
echo '<div class="alert-box alert">';
echo (__("The reCAPTCHA wasn't entered correctly. Go back and try it again.", 'beopen') .
"(" . __('reCAPTCHA said:', 'beopen') . " " . $resp->error . ")");
echo '</div>';
} else {
// Your code here to handle a successful verification
$send = 1;
}
} else {
$send = 1;
}
if (!(isset($_POST['contact_name']) && ($_POST['contact_name']) != '')) {
$error_contact_name = 'error';
$send = 2;
}
if (!(isset($_POST['contact_message']) && ($_POST['contact_message']) != '')) {
$error_contact_message = 'error';
$send = 2;
}
if ($send == 2) {
echo '<div class="alert-box alert">';
_e('U bent een veld vergeten in te vullen!', 'beopen');
echo '</div>';
} else
if ($send == 1) {
$mail_content = __('Name:', 'beopen') . PHP_EOL . $_POST['contact_name'] . PHP_EOL . PHP_EOL .
__('E-mail:', 'beopen') . PHP_EOL . $_POST['contact_email'] . PHP_EOL . PHP_EOL .
__('Company:', 'beopen') . PHP_EOL . $_POST['contact_company'] . PHP_EOL . PHP_EOL .
__('Phone:', 'beopen') . PHP_EOL . $_POST['contact_phone'] . PHP_EOL . PHP_EOL .
__('Message:', 'beopen') . PHP_EOL . $_POST['contact_message'] . PHP_EOL;
if ($_POST['contact_email'] == '') {
$mail_headers = 'From: ' . beopen_get_option('contact_email_from') . PHP_EOL .
'Reply-To: ' . beopen_get_option('contact_email_from');
} else {
$mail_headers = 'From: ' . $_POST['contact_email'] . PHP_EOL .
'Reply-To: ' . $_POST['contact_email'];
}
if (mail(beopen_get_option('contact_email_to'), beopen_get_option('contact_email_subject'), $mail_content, $mail_headers)) {
echo '<div class="alert-box success">';
_e('Bericht verzonden!', 'beopen');
echo '</div>';
} else {
echo '<div class="alert-box alert">';
_e('Voer de juiste gegevens in!', 'beopen');
echo '</div>';
}
}
}
?>
<div class="row">
<div class="six columns">
<div class="beopen-wrap author-icon <?php echo $error_contact_name; ?>">
<input type="text" name="contact_name" value="<?php echo $contact_name; ?>" placeholder="<?php _e('Uw naam', 'beopen'); ?>" />
</div>
</div>
<div class="six columns">
<div class="beopen-wrap email-icon <?php echo $error_contact_email; ?>">
<input type="text" name="contact_email" value="<?php echo $contact_email; ?>" placeholder="<?php _e('Uw e-mail', 'beopen'); ?>" />
</div>
</div>
</div>
<div class="row">
<div class="six columns">
<div class="beopen-wrap company-icon <?php echo $error_contact_company; ?>">
<input type="text" name="contact_company" value="<?php echo $contact_company; ?>" placeholder="<?php _e('Uw organisatie', 'beopen'); ?>" />
</div>
</div>
<div class="six columns">
<div class="beopen-wrap phone-icon <?php echo $error_contact_phone; ?>">
<input type="text" name="contact_phone" value="<?php echo $contact_phone; ?>" placeholder="<?php _e('Uw telefoonnummer', 'beopen'); ?>" />
</div>
</div>
</div>
<textarea name="contact_message" placeholder="<?php _e('Voer hier uw bericht in', 'beopen'); ?>" <?php if ($error_contact_message) { echo 'class="' . $error_contact_message . '"'; } ?>><?php echo $contact_message; ?></textarea>
<div id="recaptcha_div"></div>
<input type="hidden" name="beopen_form" value="1" />
<button class="button send-message" type="submit"><span class="send-message"></span><?php _e('Verzenden', 'beopen'); ?></button>
</form>
<?php } ?>
</article>
</div>
</div><!-- End Content row -->
<div class="four columns">
<div class="contact-sidebar">
<?php echo wpautop(beopen_get_option('map_address')); ?>
</div>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>