Text Area new lines from mysql database? - php

I'm sending text from a text area which is being sent into a mysql database and then being shown elsewhere on another page.
If i input for example:
text
text
text
into the text area, i simply receive
text text text
I understand i need to create a new line some how between the text, but really unsure on the way to go about it as it is being stored in MySQL as
text||text||text
<div class="panel-heading">Addservices</div>
<div class="panel-body">
<div class="block">
<form method="POST" action="page.php">
<p>Add service title:</p>
<input type="text" class="form-control" name="servicetitle" value=""><br />
</div><div class="block">
<p>Add service content:</p>
<textarea id="b" type="text" class="form-control" name="servicecontent"></textarea>
</div>
<input class="btn btn-primary btn-md" type="submit">
</form>
</div>
Code where it is being pulled from
<?php
$getService = $conn->query("SELECT id, value FROM customerlanding WHERE element = 'service'");
while ($row = $getService->fetch_assoc()) {
$id = $row['id'];
$split = explode("||", $row['value']);
echo'
<div class="col-md-4">
<div class="text-column text-column-centralized tex-column-icon-lg this-animate" data-animate="fadeInLeft">
<div class="text-column-icon">
<span style="background-color:'; echo $result['primarycolour']; echo '"class="fa"></span>
</div>
<h4>';
echo $split[0];
echo '</h4>
<div class="text-column-info">
';
echo $split[1];
echo '
</div>
</div>
</div>';
}
?>
.
if(isset($_POST['servicetitle'])){
$service = $_POST['servicetitle']."||".$_POST['servicecontent'];
$insertservice = $conn->query("INSERT INTO `customer`(`customerid`, `element`, `value`) VALUES ('10','service','$service')");

Solved.
echo nl2br($split[1]);

Related

PHP textarea input multiplies by two and outputs double input

Quick rundown:
Everything ran perfectly as it should when I had my own custom textarea field to send data
I had a custom text editor widget for inputs, but tried to add CKEditor for more functionality
When I added CKEditor package (https://ckeditor.com/ckeditor-4/download/?undefined-addons=) the editor was there, but when I clicked "Add" button and sent data, the input was doubled and there was a space between inputs (for example - input was:"test" and output was "test<br><br>test"), as if I put <br> tag and multiplied my input somewhere.
When I stopped trying with CKEditor, I went back to original code and my own original custom text editor, which before worked perfectly. However, to my surprise, it now still doubles the input string, but it doesn't put a <br> tag in between.
In DB the string value is normal and not doubled.
I have no idea how this happened, I've been going over the code for a hour or so now, trying to see if I overlooked something, but I even created a separate file with functioning code, before I was trying with CKEditor in case something broke and I could just replace it with old code and try tomorrow, but now it's messed up and I have no idea how and where.
notifications.php
<form class="form-inline" action="/action_page.php">
</form>
</nav>
<div class="container-fluid m-0 p-0">
<div class="row justify-content-center">
<div class="col-md-10">
<?php if (isset($_SESSION['response'])) { ?>
<div class="alert alert-<?= $_SESSION['res_type']; ?> alert-dismissible text-center">
<button type="button" class="close" data-dismiss="alert">×</button>
<b><?= $_SESSION['response']; ?></b>
</div>
<?php } unset($_SESSION['response']); ?>
</div>
</div>
<div class="row">
<div class="">
<?php
$query = 'SELECT * FROM crud';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
?>
<table class="table table-hover" id="data-table">
<tbody>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td></td>
<td class="pt-2"><?=
$longString=$row['name'];
$link = $row['id'];
$longStringshortcut = strlen($longString);
//echo substr($longString, 0, 100).'... Read More';
if ($longStringshortcut > 250) {
echo substr($longString, 0, 250).".. <a href='details.php?details=$link'><strong>Preberi več...</strong></a>"; }
else {
echo $longString;
}
?>
Details
Delete
Edit
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="col-md-4 p-0">
<h5 class="">Add notification:</h5>
<form action="action.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $id; ?>">
<div class="form-group">
<textarea name="name" value="<?= $name; ?>" class="form-control" placeholder="This is the default text" required></textarea>
</div>
<div class="form-group">
<?php if ($update == true) { ?>
<input type="submit" name="update" class="btn btn-success btn-block" value="Change notification">
<?php } else { ?>
<input type="submit" name="add" class="btn btn-primary btn-block" value="Add">
<?php } ?>
</div>
<div class="form-group">
<input type="hidden" name="oldimage" value="<?= $photo; ?>">
<input type="file" name="image" class="custom-file">
<img src="<?= $photo; ?>" width="120" class="img-thumbnail">
</div>
</form>
</div>
</div>
</div>
</div>
action.php
<?php
session_start();
include 'config.php';
$update=false;
$id="";
$name="";
$photo="";
if(isset($_POST['add'])){
$name=$_POST['name'];
$photo=$_FILES['image']['name'];
$upload="uploads/".$photo;
$query="INSERT INTO crud(name,photo)VALUES(?,?)";
$stmt=$conn->prepare($query);
$stmt->bind_param("ss",$name,$upload);
$stmt->execute();
move_uploaded_file($_FILES['image']['tmp_name'], $upload);
header('location:index.php');
$_SESSION['response']="Successfully Inserted to the database!";
$_SESSION['res_type']="success";
}
The problem was with the <?= syntax (echoing), <?php solved it.

Getting Select and Option value using PHP

I would like to create a form where I can upload an image and add a Name dropdown field with values coming from a table namely first name and last name using CONCAT to combine them into a complete name.
The dropdown field has the values coming from the table and works just fine.
My only problem is I can't get the value of the dropdown field to store into a variable so I can include it on the insert query.
I tried getting the value of the option tag through the post method by getting it from the select tag using the name property.
<?php
include('adminheader.php');
include('connection.php');
if (isset($_POST["insert"])) {
if (!$_POST['description']) {
$error = "<p>Description field is required</p>";
}
$ownerselected = mysqli_real_escape_string($link, $_POST['owner']);
$ownerselected1 = "hello";
$imagedescription = mysqli_real_escape_string($link, $_POST['description']);
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "INSERT INTO images(name,description,ownerid,uploaderid) VALUES ('$file','$imagedescription','$ownerselected','$userLoggedIn')";
if (mysqli_query($link, $query)) {
$notification = "Image successfully inserted " . $ownerselected1;
}
}
?>
<br/><br/>
<div class="imagecontainer container">
<div class="logincontainer">
<div id="error"><?php echo $error; ?></div>
<div id="error"><?php echo $notification; ?></div>
<div style="width:500px;">
<h3 align="center"><strong>Select an Image to upload</strong></h3>
<br/>
<form method="post" enctype="multipart/form-data">
<?php
$query = "SELECT CONCAT(fname,' ',lname)AS Name FROM person";
$result = mysqli_query($link, $query);
?>
<br/>
<div class="form-group"> <!--Start of image upload -->
<label for="image">Click Browse to locate image</label>
<input type="file" name="image" id="image"/> <!--end of image upload -->
<br/>
<div class="form-group"> <!--Start of image description -->
<label for="description">Image Description</label>
<input type="text" class="form-control" name="description" id="description"
placeholder="Enter txt">
</div> <!--end of image description -->
<div class="form-group"><!--start of owner dropdown -->
<label for="owner">Image Owner</label>
<select class="form-control" id="owner" name="owner">
<?php while ($row1 = mysqli_fetch_array($result)):; ?>
<option value="<?php echo $row1['Name']; ?>">
<?php echo $row1['Name']; ?>
</option>
<?php endwhile; ?>
</select>
</div> <!--end of owner dropdown -->
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info"/>
</form>
<br/>
<br/>
When I run the script, everything looks fine on the front end but when I perform the insert, only the image gets written on the table and imageowner column has no value. Any help is greatly appreciated. Thanks!

PHP post request from HTML page showing blank input fields

Currently looking to implement functionality to edit details in MySQL database via a HTML page. The page itself shows all data in the database which matches the unique id of the user who is is logged in via a PHP session and echos that data to input boxes in a while loop.
When the user makes changes to the input text and hits the save changes link it then calls the edit endpoint which in turn calls the edit SQL function in a functions file.
I'm using an anchor tag wrapped in a button to send the id of the row that is being edited and all this sits inside a POST action form.
However the input texts are only showing as blank as if the endpoint is not receiving the text in the input field, and despite trying quite a few different methods I can't seem to get a result.
Code for Web page (not whole page but only concerned code)
<?php
$connect =mysqli_connect('localhost','root','','micaddy');
$id_query = mysqli_query($connect, "SELECT unique_id FROM users WHERE email = '{$_SESSION['login_user']}'");
$id_array = mysqli_fetch_assoc($id_query);
$uid = $id_array['unique_id'];
$result = mysqli_query($connect, "SELECT * FROM clubs WHERE user_id =
'$uid'");
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading clearfix"><h3 class="panel-title"><strong>Your Golfbag</strong><button type="button" class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#addModal">Add Club</button></h3></div>
<?php while($row=mysqli_fetch_assoc($result)):?>
&nbsp <span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong><?php echo $row['club_type'];?></strong></h3></div>
<div class="panel-body">
<form id="" method="POST" action="editClub.php">
<div class="form-group">
<label for="clubType">Club ID</label>
<input type="text" readonly="" class="form-control" id="inputClubType" value="<?php echo $row['id'];?>" name="clubIdInput">
</div>
<div class="form-group">
<label for="clubBrand">Type</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['club_type'];?>" name="clubTypeInput">
</div>
<div class="form-group">
<label for="clubBrand">Brand</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['brand'];?>" name="clubBrandInput">
</div>
<div class="form-group">
<label for="clubNum">Number or Type</label>
<input type="text" class="form-control" id="inputclubNum" value="<?php echo $row['club_number'];?>" name="clubNumInput">
</div>
<div id="deleteClub">
<button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
<button type="button" class="btn btn-info btn-lg"><?php echo "<a href='editClub.php?id=".$row['id']."'>Save Changes</a>" ?></button>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</form>
</div>
</div>
</div>
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong>Club Image</strong></h3></div>
<div class="panel-body">
<div class="form-group">
<img src="club_images/<?php echo $row['clubImg']; ?>" class="img-rounded" width="250px" height="250px" alt="Image"/>
</div>
</div>
</div>
</div>
</div>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</div>
<?php endwhile;?>
</div>
</div>
</div>
</div>
The edit endpoint:
<?php
session_start();
$error='';
require_once '../include/DB_Functions.php';
$db = new DB_Functions();
if(empty($_POST['clubBrandInput']) || empty($_POST['clubNumInput'])){
$_SESSION['message'] = "Warning: Some fields are blank! Please try again";
header("Location: golfbag.php");
} else{
if(isset($_POST['clubBrandInput']) && isset($_POST['clubTypeInput']) && isset($_POST['clubNumInput'])){
$brand = $_POST['clubBrandInput'];
$type = $_POST['clubTypeInput'];
$num = $_POST['clubNumInput'];
$id = $_GET['id'];
$club = $db->editclub($brand, $type, $num, $id);
if($club) {
header("Location: golfbag.php");
$_SESSION['message'] = "Success! Details edited.";
}else{
header("Location: golfbag.php");
echo $error;
}
}
}
?>
The function method:
public function editClub($brand, $type, $num, $id){
$stmt = $this->conn->prepare("UPDATE clubs SET brand = '$brand', club_type = '$type', club_number = '$num' WHERE id = '$id'");
$result = $stmt->execute();
$stmt->close();
if($result){
$stmt = $this->conn->prepare("SELECT * FROM clubs WHERE user_id = ?");
$stmt->bind_param("s", $uid);
$stmt->execute();
$club = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $club;
}else{
return false;
}
}
You do not have a <form> defined in this HTML.
You are also clicking an anchor link <button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
even though it is in a button.
Therefore you will only pass the id=".$row['id']." parameter to the endpoint and that will be passed in the $_GET array and not the $_POST array

Mysql query succeeds but doesnt reflect in the database

Please guys my code isn't working and i don't know what to do anymore. All i'm trying to accomplish is a simple mysql update using php. The header query value works at the top of my code which i use to insert values in the form, but when i attempt to submit, for some reason unknown to me, my script succeeds but it doesn't update the database. The result of clicking the submit will be my "Javascript success alert" then " all the variables in my page become Undefined. My script is below.
<?php
//Catch the id from the header and query database
if(isset($_GET['id']))
$workID= mysqli_real_escape_string($connection, $_GET['id']);
$query = "SELECT * FROM music WHERE musicID = $workID";
$result= mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$artID = $row['IDartiste'];
$query2 = mysqli_query($connection,"SELECT music.*, artiste.* FROM music INNER JOIN artiste ON music.IDartiste=artiste.artisteID WHERE artiste.artisteID = $artID");
$row2 = mysqli_fetch_array($query2);
?>
**This is the form for editing**
<form role="form" method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!-- Artiste name field--> <div class="form-group">
<span><label for="topic" style="color: #55AAFF">Artiste ID: </span> <span><?php echo $row['IDartiste'];?></span></label>
<!-- Article topic field--> <div class="form-group">
<label for="topic" style="color: #55AAFF">Music title:</label>
<input type="text" class="form-control" name="title" value="<?php echo $row['musicTitle'];?>" autofocus>
</div>
<!--Article textarea--> <div class="form-group">
<label for="body" style="color: #55AAFF">Content (text):</label>
<textarea name="article" class="form-control"><?php echo $row['musicArticle'];?>
</textarea>
</div>
<!-- Upload image start--> <div class="col-ms-6 col-xs-12" >
<div class="panel panel-default">
<div class="panel-heading" style="color: #55AAFF">Upload Image</div>
<div class="panel-body">
<iframe src="fileupload.php" width="100%" style="border:none"></iframe>
</div>
</div>
</div>
<!--Image link field--> <div class="form-group">
<label for="image_link" style="color: #55AAFF">Input image link: </label>
<input type="text" name="image" value="<?php echo $row['musicPhoto'];?>" class="form-control"/>
</div>
<!-- Upload music start--> <div class="col-ms-6 col-xs-12" >
<div class="panel panel-default">
<div class="panel-heading" style="color: #55AAFF">Upload Music</div>
<div class="panel-body">
<iframe src="music_file_upload.php" width="100%" style="border:none"></iframe>
</div>
</div>
</div>
<!--Music link field--> <div class="form-group">
<label for="music_link" style="color: #55AAFF">Input music link: </label>
<input type="text" name="file" class="form-control" value="<?php echo $row['musicFile'];?>"/>
</div>
<center>....<button type="submit" class="btn btn-default" id="btnsubmit" name="btnsubmit" style="color: #55AAFF">Update</button>....</center>
<br />
</form>
This is the update script
<?php
if(isset($_GET['btnsubmit'])){
date_default_timezone_set('Africa/Lagos');
$setdate= date('Y-m-d-h-m-s');
$date= strftime($setdate);
$time= strftime('%X');
$title = $_GET["title"];
$article = $_GET["article"];
$artisteImage = $_GET["image"];
$musicFile = $_GET["file"];
$sql_music = "UPDATE kingdomjoy.music SET musicTitle = '$title',
musicFile = '$musicFile',
musicPhoto = '$artisteImage',
musicArticle = '$article',
entryDate = '$date'
WHERE musicID = '$workID' LIMIT 1";
$musicupdate = $connection->query($sql_music);
if ($musicupdate === FALSE) {
echo "Error: " . die(mysqli_error($connection));}
else {echo"<script>swal('Success! music library updated')</script>";}
}
?>

inserting data into mysql database using php

I have a php order form named (order.php) and when the user clicks the (submit button "Next Step") it takes him to another page called (confirm-order.php)
The (confirm-order.php) shows the information that the user submitted from the (order.php) using the $_POST[] and by assigning each one of these to a variable.
Data showing on the (confirm-order.php) plain text like for example :
$itemName = $_POST['itemName'];
<?php echo $itemName; ?>
at the end of page there is a form contains only one element as (submit button)
How can i insert the $itemName data into mysql database only (after the submit button is clicked and the form actions take me to the confirmation page)?
I know how to insert data into mysql, but it didn't work with the isset() function
Do i have to write the isset function inside the form first? and below it the mysql database code?
order.php page:
<form class="form-horizontal well" action="confirm-order.php" method="POST">
<fieldset>
<legend>Personal Shopper Order Form</legend>
<div class="control-group">
<label class="control-label" for="select01">Choose a plan</label>
<div class="controls">
<select id="select01" name="plan">
<option>Lite Plan $0 per order</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="itemName">Item Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="itemName" name="itemName">
<p class="help-block">Item name exapmle: iPad3 White 32GB wifi & 3G.</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="itemID">Item ID</label>
<div class="controls">
<input type="text" class="input-xlarge" id="itemID" name="itemID">
<p class="help-block">example: Ebay Item ID, Amazon Item ID.</p>
</div><br>
<div class="control-group">
<label class="control-label" for="itemURL">Item URL</label>
<div class="controls">
<input type="text" class="input-xxlarge" id="itemURL" name="itemURL">
<p class="help-block">Direct web link to the item.</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="textarea">Item Details</label>
<div class="controls">
<textarea class="input-xlarge" id="textarea" name="itemDetails" rows="6"></textarea>
<p class="help-block">Item details (name, color, specifications etc...)</p>
</div>
</div>
<li id="li_3" data-pricefield="money_simple" data-pricevalue="0">
<div class="input-prepend input-append">
<label class="control-label" for="element_3_1">Item Price</label>
<div class="controls">
<span class="add-on">$</span>
<input id="element_3_1" data-price-value="10.00" name="element_3" type="text" class="element text large">
<p class="help-block">Item exact price on the US online store.</p>
</div>
</div>
</li>
<li id="li_7" data-pricefield="money_simple" data-pricevalue="0">
<div class="input-prepend input-append">
<label class="control-label" for="element_7_1">Local Shipping Cost</label>
<div class="controls">
<span class="add-on">$</span>
<input id="element_7_1" data-price-value="10.00" name="element_7" type="text" class="element text large">
</div>
<p class="help-block">Local shipping fee from the US Store to Sky2ship (if applicable).</p>
</div>
</li>
<li id="li_8" data-pricefield="radio" data-pricevalue="0">
<div class="control-group">
<div class="controls">
<p class="help-block">Order Processing Service Fee.</p>
<label class="radio">($0) Standard 2-3 days
<input id="element_8_1" data-pricedef="00.00" name="element_8" class="element radio" type="radio" value="$0 Standard 2-3 Day">
</label>
<label class="radio">($10) Express 1 day
<input id="element_8_2" data-pricedef="10.00" name="element_8" class="element radio" type="radio" value="$10 Express Same Day">
</label>
</div>
</div>
</li>
<legend>Personal Information & Shipping Address</legend>
<div class="control-group">
<label class="control-label" for="input04">Full Name</label>
<div class="controls">
<input type="text" class="input-medium" id="fullName" name="fullName">
<p class="help-block">First & last name.</p>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="radio">Male
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
</label>
<label class="radio">
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">Female
</label>
</div>
</div>
<div class="input-prepend">
<label class="control-label" for="prependedInput">Email Address</label>
<div class="controls">
<span class="add-on">#</span>
<input type="text" class="span2" id="prependedInput" name="Email">
<p class="help-block">Your email address.</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="input06">Address</label>
<div class="controls">
<input type="text" class="input-xxlarge" id="input06" name="streetAddress" placeholder="Street Address">
<p class="help-block">Your shipping address.</p>
</div>
</div>
<div class="control-group">
<div class="controls controls-row">
<input type="text" class="span2" id="City" name="City" placeholder="City">
<input type="text" class="span3" id="State" name="State" placeholder="State / Province">
</div>
</div>
<div class="control-group">
<div class="controls controls-row">
<input type="text" class="span2" id="PostalCode" name="PostalCode" placeholder="Postal Code">
<input type="text" class="span3" id="Phone" name="Phone" placeholder="Phone Number">
</div>
</div>
<div class="control-group">
<label class="control-label" for="select01">Country</label>
<div class="controls">
<select id="select02" name="Country">
<option>IRAQ</option>
<option>JORDON</option>
</select>
</div>
</div>
<li class="total_payment" align="right" data-basetotal="0">
<span>
<h3 class="alert-success">$<var>0</var></h3>
<h5>Total</h5>
</span>
</li>
<div class="control-group">
<label class="control-label" for="optionsCheckbox">Read & Agree</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="optionsCheckbox" value="option1">
I agree to the site's Terms of Service & Privacy Policy.
</label>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Confirm Order</button>
<button type="reset" class="btn">Cancel Order</button>
</div>
</fieldset>
</form>
confirm-order.php page:
<?php
$itemName = $_POST['itemName'];
$plan = $_POST['plan'];
$itemID = $_POST['itemID'];
$itemPrice = $_POST['element_3'];
$processService = $_POST['element_8'];
$itemDetails = $_POST['itemDetails'];
$streetAddress = $_POST['streetAddress'];
$City = $_POST['City'];
$State = $_POST['State'];
$PostalCode = $_POST['PostalCode'];
$Phone = $_POST['Phone'];
$Country = $_POST['Country'];
$fullName = $_POST['fullName'];
$Email = $_POST['Email'];
$itemURL = $_POST['itemURL'];
$itemLocalShipCost = $_POST['element_7'];
?>
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "000000";
$db_name = "dbname";
if (isset($_POST['submit'])) {
$db_connect = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql ="INSERT INTO lite_order (lite_plan, lite_item_name)
VALUES
('$plan','$item')";
if (!mysqli_query($db_connect,$sql))
{
die('Error: ' . mysqli_error($db_connect));
}
echo "1 record added";
}
?>
<address>
<strong>Shipping Address.</strong><br>
<?php echo $streetAddress; ?><br>
<?php echo $City; ?>, <?php echo $State; ?>, <?php echo $PostalCode; ?><br><?php echo $Country; ?><br>
<abbr title="Phone">P:</abbr><?php echo $Phone; ?>
</address>
<address>
<strong><?php echo $fullName; ?></strong><br>
<?php echo $Email; ?>
</address>
<table class="table">
<thead>
<tr>
<th>Plan</th>
<th>Item Name</th>
<th>Item ID</th>
<th>Local Shipping Cost</th>
<th>Item Price</th>
<th>Order Processing Fee</th>
</tr>
</thead>
<tbody>
<tr class="success">
<td><?php echo $plan; ?></td>
<td><?php echo $itemName; ?></td>
<td><?php echo $itemID; ?></td>
<td><?php echo "$" . $itemLocalShipCost; ?></td>
<td><?php echo "$" . $itemPrice; ?></td>
<td><?php echo $processService; ?></td
></tr>
</tbody>
</table>
<strong>Item URL</strong><p class="alert alert-info"><?php echo $itemURL; ?></p>
<pre class="pre-scrollable"><?php echo $itemDetails; ?></pre>
<p>Your Total <h3 class="question"><?php echo "$" . $orderTotal; ?></h3></p>
<div class="form-actions"><form action="pending-order.php" method="post" name="confirmed-order">
<button type="submit" name="submit" class="btn btn-primary">Submit Order</button>
<button type="button" class="btn">Previous</button></form>
</div>
</div>
</div>
</div>
</div>
</div>
Whereto insert the mysql database code to insert all the variables into database after the submit button is clicked? where to place the isset() function? i tried it, it didn't insert any data into my table.
EDIT: a simple example
do <form>, validation and inserting in one file, say form.php:
<? // check if FORM has been posted
$posted = isset($_POST['submit']);
if ($posted) { // form has been posted...
// validate input
if (!isset($_POST['item']) || strlen(trim($_POST['item'])) == 0)
$error['item'] = "please insert an item-name!";
if (!isset($_POST['price']) || !is_numeric($_POST['price']))
$error['price'] = "please enter a valid price!";
// ready for input?
if (!isset($error)) { // no $error --> go insert!
// I'll do the db-operation with PDO and a prepared statement.
// this is cool, easy and safe. LEARN IT!
$sql = "INSERT INTO table (item,price) VALUES (:item,:price)";
$insert = $db->prepare($sql);
$insert->execute(array(
':item' => $_POST['item'],
':price' => $_POST['price']
));
} // $error
} // submit
?>
Now, in the <body> of the same page...
<? // check whether to display confirmation or form...
if ($posted && !isset($error)) {
// form was sent AND no error --> confirm
?>
<h1>Confirmed!</h1>
<p>Your data has been sent, thank you very much!</p>
go to somepage
<?
} else {
// form not sent or errors --> display form
?>
<h1>Please enter data</h1>
<? // display error-message, if there's one:
if (isset($error)) {
$output = "";
foreach ($error as $field => $msg)
$output .= (strlen($output) > 0?', ':'') . "[$field]: $msg";
echo "<p>There were errors: $output</p>";
} // $error
?>
<form method="post">
<!-- if the form has been sent, bring back the field's value from $_POST -->
<p>item-name: <input type="text" name="item"
value="<?=($posted?$_POST['item']:'')?>" /></p>
<p>price: <input type="text" name="price"
value="<?=($posted?$_POST['price']:'')?>" /></p>
<p><input type="submit" name="submit" value="submit" /></p>
</form>
<?
} // submit & $error
?>
See the use of a ternary-operator for setting the value-attribute of the <input>-elements:
(<condition>?<what to do if true>:<what to do if false>)
There are two specific things I can contribute.
First, isset tests for null... which is different than empty. If you have a form field that is submitted empty, then set a local variable to that posted value, then test it with isset; isset will return true because the value exists which is different than the variable not having been registered in the page load at all.
Second... ANYTHING can post to your form (think evil autonomous Korean hacker bots). Also, there are many ways a form can get submitted without having activated the submit button itself so there is no guarantee you will even see a submit key in your $_POST vars. What you need to define in your processing script is a "default action". What I mean by that is a very basic and SAFE behavior (like redirecting to a 'something is wrong' page) that kicks off by default such that the only way around it is to submit a correct form with all anticipated values correctly set.
If you do this, you can ignore the value of the submit button itself and instead focus on the contents of the POST. Did I receive everything I expected to receive? Was it all in the correct format? Was the user authenticated correctly? Only after all these questions have been tested to your satisfaction would you switch from the default behavior to a form processing behavior in which the posted data can be inserted into your database.
Example using your 3 page structure:
reference: filter vars
Page 1:
<form action=./page2 method=POST>
<input type=text value=1234 name=numericValue />
<input type=text value="dummytext" name=stringValue />
<input type=submit value=submit name=submit />
</form>
Page 2:
<?php
$args = array('numericValue' => FILTER_VALIDATE_INT
,'stringValue' => FILTER_SANITIZE_STRING);
$clean_data = filter_input_array(INPUT_POST,$args);
if (is_array($clean_data))
{
$_SESSION["saved_clean_data"] = $clean_data;
}
else
{
Header(<something wrong page>);
die();
}
?>
<form action=./page3 method=POST>
<input type=submit name=submit value=No />
<input type=submit name=submit value=Yes />
</form>
Page 3:
<?php
if ($_POST["submit"] === "Yes")
{
$cleanNum = $_SESSION["saved_clean_data"]["numericValue"];
$cleanStr = $_SESSION["saved_clean_data"]["stringValue"];
// DB insert Query, use advice from michi about PDO
// parameterize your queries to help prevent sql injection
}
else
{
Header(<somewhere for declined submits>);
die();
}
?>
Well we can do this in the following ways
You store all the data in session and use it in confirmation page and then on data insertion page. Do remember to update or delete it if user updates or cancel the order.
You can dynamically create the confirm order page using javascript and HTML and when user clicks confirm button then only we post it to the PHP page. This will also reduce a server call.
One other ways is to again send the collected posted values and keep it as hidden fields in the confirmation page and post it when clicked confirm.
create a form and store variables in hidden fields , then create this submit button in the form
So clicking this form will store the info. See the exmple here
<form class="form-horizontal well" action="confirm-order.php" method="POST">
<input type="hidden" value="<?php echo $itemName; ?>" />
<input type="submit" value="Confirm Order" />
</form>
Well there are couple of ways about doing this:
Store all the data from the previous page i.e. from order.php in the $SESSION[] variables:
Explaination: Setting it in Session will enable you to access the same variable from anywhere in the site until the session of the user. Means that after you store it in session you can access it in pending-order.php page.
How to do it: In this page at the top, instead of setting the variables at top write the following:
$SESSION['itemName'] = $_POST['itemName']
then echo it using:
echo $SESSION['itemName']
and then in the pending-order.php you can assign a value to a variable like so:
$itemName = $SESSION['itemName']
and now you can store the variable in the db.
Put hidden fields inside the form of confirm-order.php page:
Explaination: Create hidden input fields in confirm-order.php form and set the values that are in the variables. This way when you click the submit button you can access them in pending-order.php in the same way you are doing on confirm-order.php.
How to do it: Simply put the variables in value attribute of the hidden input like so:
<form action="pending-order.php" method="post" name="confirmed-order">
<input type="hidden" value="<?php $itemID ?>" id="someID">
</form>
Try
<button type="submit" class="btn btn-primary" NAME="submit">Confirm Order</button>
And use
IF (isset($_POST['submit]) {
$itemName = $_POST['itemName'];
$plan = $_POST['plan'];
$itemID = $_POST['itemID'];
$itemPrice = $_POST['element_3'];
$processService = $_POST['element_8'];
$itemDetails = $_POST['itemDetails'];
$streetAddress = $_POST['streetAddress'];
$City = $_POST['City'];
$State = $_POST['State'];
$PostalCode = $_POST['PostalCode'];
$Phone = $_POST['Phone'];
$Country = $_POST['Country'];
$fullName = $_POST['fullName'];
$Email = $_POST['Email'];
$itemURL = $_POST['itemURL'];
$itemLocalShipCost = $_POST['element_7'];
// your mysql INSERT codes here
}
EDIT 1:
change <button type="submit" class="btn btn-primary">Confirm Order</button>
TO <input type="submit" class="btn btn-primary" value="Confirm Order">
isset() function work when the input field type is submit.like
<input type="submit" value="Confirm Order" />
so update the code form
<div class="form-actions">
<button type="submit" class="btn btn-primary">Confirm Order</button>
<button type="reset" class="btn">Cancel Order</button>
</div>
to
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Confirm Order" />
<input class="btn" type="reset" value="Cancel Order" />
</div>

Categories