I'm working on this feature in my project where I want to add three(3) images along side other details into my database row and I want this images to be in separate columns in one row.... So far below is my code. the code is not working yet... The images and texts are not uploading to the database....
Please help me out guys. What am I doing wrong. Thanks.
Below is my code sample:
//THE PHP SECTION//
<?php
session_start();
include 'includes/config.php';
if (isset($_POST['post']) && isset($_POST['itemtype'])) {
$title = mysqli_real_escape_string($link, $_POST['title']);
$itemtype = mysqli_real_escape_string($link, $_POST['itemtype']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$image1 = $_FILES['image1']['name'];
$image1_tmp_name = $_FILES['image1']['tmp_name'];
$image2 = $_FILES['image2']['name'];
$image2_tmp_name = $_FILES['image2']['tmp_name'];
$image3 = $_FILES['image3']['name'];
$image3_tmp_name = $_FILES['image3']['tmp_name'];
$price = mysqli_real_escape_string($link, $_POST['price']);
$category = mysqli_real_escape_string($link, $_POST['category']);
$name = mysqli_real_escape_string($link, $_POST['name']);
//image file directory
$target1 = 'images/user_ads/'.basename($image1);
$target2 = 'images/user_ads/'.basename($image2);
$target3 = 'images/user_ads/'.basename($image3);
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
//insert into ost database
$insert = "INSERT INTO products(Title,Product_Type,Description,Image1,Image2,Image3,Price,Category,Name,PostedDate)VALUES('$title','$itemtype','$description','$target1','$target2','$target3','$price','$category','$name',NOW())";
$insertKwary = mysqli_query($link, $insert);
if ($insertKwary) {
$msg = "<div class='alert alert-danger alert-success'>Product Submitted</div>";
}else{
$msg = "<div class='alert alert-danger alert-success'>Product Not Submitted...Try again</div>";
}
}
?>
//THE HTML SECTION//
<div class="col-md-8 col-md-offset-2">
<?php if(isset($msg)) { echo $msg; } ?>
<form action="" method="POST" enctype="multipart/form-data" class="postAdForm" id="postAdForm">
<div class="form-group">
<label for="Ad_title">Item Title</label>
<input type="text" name="title" class="form-control title" id="title" required=""/>
</div>
<div class="form-group">
<label for="itemtype">Item Type</label>
<select class="form-control" name="itemtype" id="itemtype">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="description">Item Description</label>
<textarea name="description" class="form-control description" id="description" rows="7" required=""></textarea>
</div>
<div class="form-group">
<label for="price">First Image</label>
<input type="file" name="image1" class="form-control image1" id="image1" required="" />
</div>
<div class="form-group">
<label for="price">Second Image</label>
<input type="file" name="image2" class="form-control image2" id="image2" required="" />
</div>
<div class="form-group">
<label for="price">Third Image</label>
<input type="file" name="image3" class="form-control image3" id="image3" required="" />
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" name="price" class="form-control price" id="price" required="" />
</div>
<div class="form-group">
<label for="category">Item Category</label>
<select class="form-control" name="category" id="category">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="price">Name</label>
<input type="text" name="name" class="form-control name" id="name" required="" readonly="" />
</div>
<div class="form-group">
<input type="submit" name="post" class="btn btn-post post" id="post" value="POST AD" />
</div>
</form>
</div>
I've also attached an image of the error i'm getting..
image of web page showing thee errors i get..error gotten
The error is due to these lines:
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
You're setting $image1_tmp_name, not $_FILES['image1_tmp_name'].
Try this:
if (move_uploaded_file($image1_tmp_name, $target1)) {
}
if (move_uploaded_file($image2_tmp_name, $target2)) {
}
if (move_uploaded_file($image3_tmp_name, $target3)) {
}
Edit: Using mysqli_error() to print the error helped solve additional issues (Mentioned in comments)
Related
I want only 4 columns from database in below
I have to get only 4 column from database for displaying in textfield please give suggestion for that. The table is shown below thank you
$sql_getnm = "SELECT * FROM util WHERE util_head IN ('wc_email', 'wc_contact_us', 'wc_mobile', 'wc_google_map');";
$result_getnm = $connect->query($sql_getnm);
while($row_getnm = $result_getnm->fetch_array())
$util_value_email_data=?
$util_value_mobile_data=?;
$util_value_map_data=?;
$util_value_data=?;
html form
<form id="submitForm" method="post" role="form" name="hl_form" method="post" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="mobile_number">Email*</label>
<input class="form-control" id="util_value_email" name="util_value_email" value="<?Php echo $util_value_email_data; ?>" maxlength="250" placeholder="Enter Email Address" type="text">
</div>
<div class="form-group">
<label for="mobile_number">Mobile*</label>
<input class="form-control" id="util_value_mobile" name="util_value_mobile" value="<?Php echo $util_value_mobile_data; ?>" maxlength="250" placeholder="Enter Mobile Number" type="text">
</div>
<div class="form-group">
<label for="mobile_number">Map*</label>
<input class="form-control" id="util_value_map" name="util_value_map" value="<?Php echo $util_value_map_data; ?>" maxlength="250" placeholder="Enter Map Address" type="text">
</div>
<div class="form-group">
<label for="description" class="required">Description*</label>
<textarea class="form-control" style="resize: none;" id="util_value" name="util_value" rows="3" placeholder="Enter Description"><?Php echo $util_value_data; ?></textarea>
</div>
<div class="box-footer">
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Below is the code from which you can get all the four data that you want.
$sql_getnm = "SELECT * FROM util WHERE util_head IN ('wc_email', 'wc_contact_us', 'wc_mobile', 'wc_google_map');";
$result_getnm = $connect->query($sql_getnm);
while($row_getnm = $result_getnm->fetch_array()) {
if($row_getnm['util_head'] == 'wc_email'){
$util_value_email_data = $row_getnm['util_value'];
}
if($row_getnm['util_head'] == 'wc_contact_us'){
$util_value_contact_data = $row_getnm['util_value'];
}
if($row_getnm['util_head'] == 'wc_mobile'){
$util_value_mobile_data = $row_getnm['util_value'];
}
if($row_getnm['util_head'] == 'wc_google_map'){
$util_value_map_data = $row_getnm['util_value'];
}
}
You need to replace * with columns name with comma separation.
$sql_getnm = "SELECT Columname1,Columname2,Columname3,Columname4 FROM util WHERE util_head IN ('wc_email', 'wc_contact_us', 'wc_mobile', 'wc_google_map');";
$result_getnm = $connect->query($sql_getnm);
while($row = mysql_fetch_array($result_getnm, MYSQL_ASSOC)
$util_value_email_data= $row['Columname1'];
$util_value_mobile_data= $row['Columname2'];
$util_value_map_data= $row['Columname3'];
$util_value_data= $row['Columname4'];
how do I foreach through html input form and insert multiple rows or one based on a selected date field? in other words when a user enters "name" "description" and "shift" and then selects either one date or more then one. PHP will then enter the same information for either one new row or multiples based on how many dates were selected.
<?php
if(isset($_REQUEST['submit']))
{
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
// Check connection
if($link === false){
die("| ERROR: Could not connect. " . mysqli_connect_error());
}
$name = mysqli_real_escape_string($link, $_REQUEST['name']);
$desc = mysqli_real_escape_string($link, $_REQUEST['description']);
$shift = mysqli_real_escape_string($link, $_REQUEST['shift']);
$date = mysqli_real_escape_string($link, $_REQUEST['daterange']);
$sql = "insert into db (name,description,shift,evdate) values ('$name', ' $desc','$shift','$date')";
$sql2 = "insert into db (name,description,shift,evdate) values ('$name', ' '$desc','$shift','$insert')";
if ($date=0) {
$result = mysqli_query($link, $sql);
}else{
$daterange = explode(',',$date);
foreach($daterange as $insert) {
$result = mysqli_query($link, $sql2);
}
}
if(mysqli_query($link, $sql)){
echo "";
} else{
echo "| ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if ($link->multi_query($sql) === TRUE) {
echo "It Worked..... Maybe!!!!!!";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
}
$link->close();
?>
<form action="test_insert.php" method="post">
<div class="col col-lg-2 col-lg-offset-0">
<div class="form-group col-lg-offset-0 col-lg-12">
<label for="Name">Employee Name:</label>
<input type="text" name="name" placeholder="First & Last Name" id="name" required>
<p class="help-block col-lg-12">First and Last Name Please.</p>
</div>
</div>
<div class="col col-lg-offset-0 col-lg-2">
<div class="form-group col-lg-12">
<label for="description">Description:</label>
<input type="text" name="description" id="description" placeholder="description..." required>
<p class="help-block">For Example: "Vacation Full Day" or "PTO 2 Hours." </p>
</div>
</div>
<div class="col col-lg-offset-0 col-lg-3">
<label for="shift">Shift:</label><br>
<input type="radio" name="shift" value="First Shift" id="shift" checked> First Shift |
<input type="radio" name="shift" value="Second Shift" id="shift"> Second Shift |
<input type="radio" name="shift" value="Third Shift" id="shift"> Third Shift
<p class="help-block">Select Correct Shift Worked.</p>
</div>
<div class="col col-lg-offset-0 col-lg-3">
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker1" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker2" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker3" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker4" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-10">
<label for="date2">Date/Dates:</label>
<input type="text" id="datepicker5" name="daterange" placeholder="Select Your Date" />
</div>
<div class="form-group col-lg-6">
<input type="submit" name="submit" class= "btn btn-primary">
</div>
</div>
</div>
</form>
Think the best way is to use AJAX,
Then with the response as a string you make a table or foreach in php as a string and then use the .html adapter to output the newly made data.
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
$('#showresults').html(result);
});
}
<?php
if(isset($_POST["submit"]))
if (!empty($_FILES["uploadImage"]["name"])) {
//Including dbconfig file.
require 'config.php';
$ImageSavefolder = "images/student/";
move_uploaded_file($_FILES["uploadImage"]["tmp_name"] ,
"$ImageSavefolder".$_FILES["uploadImage"]["name"]);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$fathername = mysqli_real_escape_string($conn, $_POST['fathername']);
$htno = mysqli_real_escape_string($conn, $_POST['htno']);
$phoneno = mysqli_real_escape_string($conn, $_POST['phoneno']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$class = mysqli_real_escape_string($conn, $_POST['class']);
$address = mysqli_real_escape_string($conn, $_POST['address1']);
$address2 = mysqli_real_escape_string($conn, $_POST['address2']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
if(!mysqli_query($conn,$sql))
{
echo "Not Updated";
}
else
{
echo "<br><div class='alert alert-success' role='alert'>Added Sucessfully !</div>";
}
}
?>
This code is not working for adding the following data into database. Did I do anything wrong? Please help me sort the problem.
I already created database with config.php
Form Data
<form method="post" action="" enctype="multipart/form-data">
<div class="form-row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input type="text" class="form-control" placeholder="Please Enter Name" name="name">
</div>
<div class="form-group col-md-6">
<label for="fathername">Father's Name</label>
<input type="text" class="form-control" placeholder="Please Enter Father's Name" name="fathername">
</div>
<div class="form-group col-md-6">
<label for="htno">Hall Ticket/ Roll No.</label>
<input type="text" class="form-control" placeholder="Please Enter Hall Ticket/ Roll No." name="htno">
</div>
<div class="form-group col-md-6">
<label for="phoneno">Phone Number</label>
<input type="text" class="form-control" placeholder="Please Enter Phone No." name="phoneno">
</div>
<div class="form-group col-md-6">
<label for="department">Department</label>
<select class="form-control" name="department">
<option selected="selected">Choose your Department</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM department");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['department_name']."'>".$test['department_name']."</option>";
}
?>
</select>
</div>
<div class="form-group col-md-6">
<label for="class">Class</label>
<select class="form-control" name="class">
<option selected="selected">Choose your Class</option>
<?php
require('config.php');
$result = mysqli_query($conn,"SELECT * FROM class");
while($test= mysqli_fetch_array($result))
{
echo "<option value='".$test['class_name']."'>".$test['class_name']."
</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" placeholder="House No./Flat No." name="address1">
</div>
<div class="form-group">
<label for="address2">Address 2 (Optional)</label>
<input type="text" class="form-control" placeholder="Locality/Area/Street" name="address2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="city">City</label>
<input type="text" class="form-control" name="city">
</div>
<div class="form-group col-md-4">
<label for="state">State</label>
<select class="form-control" name="state">
<option selected="selected"name="bihar">bihar</option>
<option>...</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="zip">Zip</label>
<input type="text" class="form-control" name="zip">
</div>
<div class="form-group col-md-6">
<label for="profile">Profile Pic</label><br>
<input type="file" accept="image/*" onchange="loadFile(event)" name="uploadImage" id="uploadImage">
<img id="output" style="width:20%;"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
</div>
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
you are trying to insert extra value which is not exist in query see here.
your field
(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip)
and your values
('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')
you need to do add image field also
your full query
$sql= "INSERT INTO student_detail(name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,imageFieldName) VALUES ('$name','$fathername','$htno','$phoneno','$department','$class','$address','$address2','$city','$state','$zip','".$_FILES['uploadImage']['name']."')";
<?php
/* dbconnection.php file
$conn = mysqli_connect("localhost","root","12345") or die (mysqli_error());
mysqli_select_db($conn,"student") or die (mysqli_error());
*/
//Including dbconnection file here
include('dbconnection.php');
if(isset($_POST["submit"]))
{
if (!empty($_FILES["uploadImage"]["name"]))
{
$ImageSavefolder = "images/student/";
$name = $_FILES["uploadImage"]["name"];
$tmp_name = $_FILES["uploadImage"]["tmp_name"];
move_uploaded_file(tmp_name, $ImageSavefolder.$name);
$sql = "INSERT INTO students (name,fathername,htno,phoneno,department,class,address1,address2,city,state,zip,image) VALUES ('".$_POST["name"]."','".$_POST["fathername"]."','".$_POST["htno"]."','".$_POST["phoneno"]."','".$_POST["department"]."','".$_POST["class"]."','".$_POST["address1"]."','".$_POST["address2"]."','".$_POST["city"]."','".$_POST["state"]."','".$_POST["zip"]."','".$name."')";
if ($conn->query($sql) === TRUE)
{
echo "<script type= 'text/javascript'>alert('Record Inserted Successfully');</script>";
}
else
{
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
}
?>
I'm trying to insert data into a database, the script executes all the way down and redirect the user to the page but no record gets inserted. I've been trying to figure out why for hours. I keep creating new scripts but i'm missing something apparently.
init.php
<?php
/*for error 1045 config.inc.php*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()){
echo "database failed to connect with following errors:". mysqli_connect_error();
die();
}
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/config.php';
require_once BASEURL.'helpers/helpers.php';
form.php
<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once $_SERVER['DOCUMENT_ROOT'].'/HeleneQuirion/core/init.php';
include 'includes/header.php';
if(isset($_GET['add'])){
$parentQuery = $db->query("SELECT * FROM categories WHERE parent= 0" );
if (isset($_POST['submit'])) {
// prepare and bind
$stmt = $db->prepare("INSERT INTO product (prod_name, categories, list_price, price,prod_width,prod_depth,prod_height,prod_material,quantity,image_1,image_2,image_3,image_4,description,care_instructions) VALUES (?,?, ?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssiiiiisissssss" ,$prod_name, $child,$list_price,$price,$prod_width,$prod_depth,$prod_height,$prod_material,$quantity,$image_1,$image_2,$image_3,$image_4,$description,$care_instructions);
// set parameters and execute
if(isset($_POST['prod_name']))
{
$prod_name = sanitize($_POST)['prod_name'];
}
if(isset($_POST['child']))
{
$categories = sanitize($_POST)['child'];
}
if(isset($_POST['list_price']))
{
$prod_name = sanitize($_POST)['list_price'];
}
if(isset($_POST['price']))
{
$price = sanitize($_POST)['price'];
}
if(isset($_POST['prod_width']))
{
$prod_width = sanitize($_POST)['prod_width'];
}
if(isset($_POST['prod_depth']))
{
$prod_depth = sanitize($_POST)['prod_depth'];
}
if(isset($_POST['prod_height']))
{
$prod_height = sanitize($_POST)['prod_height'];
}
if(isset($_POST['prod_material']))
{
$prod_material = sanitize($_POST)['prod_material'];
}
if(isset($_POST['quantity']))
{
$quantity = sanitize($_POST)['quantity'];
}
if(isset($_POST['care_instructions']))
{
$care_instructions = sanitize($_POST)['care_instructions'];
}
if(isset($_POST['image_1']))
{
$image_1 = $_FILES['image_1'];
}
if(isset($_POST['image_2']))
{
$image_2 = $_FILES['image_2'];
}
if(isset($_POST['image_3']))
{
$image_3 = $_FILES['image_3'];
}
if(isset($_POST['image_4']))
{
$image_4 = $_FILES['image_4'];
}
if(isset($_POST['description']))
{
$description = sanitize($_POST)['description'];
}
$stmt->execute() or die(mysqli_error($db));
header('Location: products.php');
$stmt->close();
$conn->close();
}
?>
<form action="products.php?add=1" method="POST" enctype="multipart/form-data">
<div class='container_12'>
<div class="form-group col-md-3">
<label for="prod_name">Product Name*:</label>
<input type="text" name="prod_name" id="prod_name" class="form-control" value="<?=((isset($_POST['prod_name']))?sanitize($_POST['prod_name']):' ');?>">
</div>
<div class="form-group col-md-3">
<label for="parent">Parent Category*:</label>
<select class="form-control" id="parent" name="parent">
<option value=""<?=((isset($_POST['parent']) && $_POST['parent'] == '')?'selected':'');?>></option>
<?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
<option value=" <?=$parent['id'];?>"<?=((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':'');?>><?=$parent['category_name'];?></option>
<?php endwhile; ?>
</select>
</div>
<div class='form-group col-md-3'>
<label for='child'>Second Category*:</label>
<select id='child' name='child' class='form-control'></select>
</div>
</div>
<div class='container_12'>
<div class='form-group col-md-3'>
<label for='list_price'>List Price(OPTIONAL): </label>
<input type="text" id="list_price" name="list_price" class="form-control" value="<?=((isset($_POST['list_price']))?sanitize($_POST['list_price']):'');?>">
</div>
<div class="form-group col-md-3">
<label for="price">Price*:</label>
<input type="text" id="price" name="price" class="form-control" value="<?=((isset($_POST['price']))?sanitize($_POST['price']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_width'>Width* (in inches):</label>
<input type="text" id="prod_width" name="prod_width" class="form-control" value="<?=((isset($_POST['prod_width']))?sanitize($_POST['prod_width']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_depth'>Height*(in inches):</label>
<input type="text" id="'prod_depth" name="'prod_depth" class="form-control" value="<?=((isset($_POST['prod_depth']))?sanitize($_POST['prod_depth']):'');?>">
</div>
</div>
<div class='container_12'>
<div class='form-group col-md-3'>
<label for='prod_height'>Depth*(in inches):</label>
<input type="text" id="prod_height" name="prod_height" class="form-control" value="<?=((isset($_POST['prod_height']))?sanitize($_POST['prod_height']):'');?>">
</div>
<div class='form-group col-md-3'>
<label for='prod_material'>Construction Material:</label>
<input type="text" id="prod_material" name="prod_material" class="form-control" value="<?=((isset($_POST['prod_material']))?sanitize($_POST['prod_material']):'');?>">
</div>
<div class='form-group col-md-6'>
<label>Quantity * :</label>
<input type="text" id="quantity" name="quantity" class="form-control" value="<?=((isset($_POST['quantity']))?sanitize($_POST['quantity']):'');?>">
</div>
</div>
<div class='container_12'>
<div class="form-group col-md-3"> <label for="image_1">Product Photo #1:</label>
<input type="file" name="image_1" id="image_1" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_2">Product Photo #2:</label>
<input type="file" name="image_2" id="image_2" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_3">Product Photo #3:</label>
<input type="file" name="image_3" id="image_3" class="form-control">
</div>
<div class="form-group col-md-3"> <label for="image_4">Product Photo#4:</label>
<input type="file" name="image_4" id="image_4" class="form-control">
</div>
</div>
<div class='container_12'>
<div class="form-group col-md-6">
<label for="description">Description:</label>
<textarea id="description" name="description" class="form-control" rows="6"><?=((isset($_POST['description']))?sanitize($_POST['description']):'');?></textarea>
</div>
<div class="form-group col-md-6">
<label for="care_instructions">Care Instructions*:</label>
<textarea id="care_instructions" name="care_instructions" class="form-control" rows="6"><?=((isset($_POST['care_instructions']))?sanitize($_POST['care_instructions']):'');?></textarea>
</div></div>
<div class='container_12'>
<div class="form-group pull-right">
<input type='submit' name='submit' value='Add Product' class='form-control btn-success pull-right'>
</div></div>
</form>
This is just to clarify one of the points in the comments above...
So I knocked up some test code to check what is going on...
<?php
$_POST['prod_name'] = 'fred';
function sanitize($thing){
var_dump("Inside Sanitize- ", $thing);
return $thing;
}
// Original Code - sends an array to sanitize
if(isset( $_POST['prod_name'] )) {
$prod_name = sanitize($_POST)['prod_name'];
}
var_dump('Original Version '.$prod_name);
// New Code 1 - Sends a String to sanitize
if(isset( $_POST['prod_name'] )) {
$prod_name = sanitize($_POST['prod_name']);
}
// New Code 2 - Should use this one, or could make this a function.
$prod_name = isset($_POST['prod_name'])? sanitize($_POST['prod_name']):'';
var_dump($prod_name);
I'm having a difficult time understanding the $_SESSION function in PHP. I'm building a multipage form and when it was a single form, everything worked as expected. Now I'm trying to figure out $_SESSION so that data from page1 carries to page2 for the submit.
So here is page 1:
<?php require_once("../tim/includes/validation_functions.php");
include("../tim/includes/session.php");
require_once("../tim/includes/variables.php");
include ("/testing/tim/obervation-upload.php");
?>
<?php
session_start(); // Session starts here.
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
<script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>
<title>Assessment Application</title>
</head>
<body>
<div>
<h2>3SP Assessment</h2>
<span id="error">
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
</span>
<form class="form-horizontal" role="form" name="assessment" action="application_form.php" method="post">
<div class="form-group" style="margin-bottom:10px;">
<label for="company_name" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Company name:</strong></label>
<div class="col-md-2"> <input type="text" id="company_name" name="company_name" class="form-control" required> </div>
<div class="clearfix"></div>
<label for="date" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Date:</strong></label>
<div class="col-md-2"><input type="date" name="date" id="date" class="form-control" required> </div>
<div class="clearfix"></div>
<label for="rsm" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Regional Sales Manager:</strong></label>
<div class="col-md-2"> <input type="text" name="rsm" id="rsm" class="form-control" required></div>
<div class="clearfix"></div>
<label for="agents" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Agents:</strong> </label>
<div class="col-md-2"> <input type="text" name="agents" id="agents" class="form-control" required></div>
<div class="clearfix"></div>
<label for="distributor" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Distributor:</strong> </label>
<div class="col-md-2"><input type="text" name="distributor" class="form-control" required></div>
</div>
<p style="margin-left:5px;"><input class="btn btn-danger" type="reset">
<input style="margin-left:10px;" class="btn btn-success" type="submit" value="Next" /></p>
</form>
<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>
</body>
</html>
page 2:
<?php require_once("../tim/includes/validation_functions.php");
include("../tim/includes/session.php");
require_once("../tim/includes/variables.php");
include ("/testing/tim/obervation-upload.php");
?>
<?php
session_start();
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
<script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>
<title>Assessment Application</title>
</head>
<body>
<div>
<h2>3SP Assessment</h2>
<form name="assessment" action="create_new_record.php" method="POST" enctype="multipart/form-data">
<p>Department name: <input type="text" name="department_name" /> </p>
<p>Participant name: <input type="text" name="participant_name" /> </p>
<p>Activity performed: <textarea cols="25" rows="3" name="activity" ></textarea> </p>
<p>Location: <input type="text" name="location" /> </p>
<p>Conditon: <select class="form-control" name="condition" style="width:20%;">
<option value="dry" id="dry">Dry</option>
<option value="heavy_oil" id="heavy_oil">Heavy Oil/Grease</option>
<option value="light_oil" id="light_oil">Light Oil</option>
<option value="sandy" id="sandy">Sandy/Grit</option>
<option value="wet" id="wet">Slightly Wet</option>
</select></p>
<div class="well">
<p>Avg Number of Recordable Injuries:
<input type="number" name="injuries" />
<select name="injury_time_frame">
<option value="last month">Last month</option>
<option value="last 6 months">Last 6 months</option>
<option value="last 12 months">Last 12 months</option>
</select>
</p>
<h4>Based on the number of Recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
<div class="form-group row">
<div class="col-md-3 col-sm-4"><input class="form-control" id="cuts" name="cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="burns" name="burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="infection" name="infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="dermatitis" name="dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
<div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="puncture" name="puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="sprain" name="sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="impact" name="impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" /> </div>
</div>
</div>
<p id="rec_injuries"></p>
<script>
function percentageTest() {
// Get the value of the input fields
a = document.getElementById("cuts").value;
b = document.getElementById("burns").value;
c = document.getElementById("infection").value;
d = document.getElementById("dermatitis").value;
e = document.getElementById("puncture").value;
f = document.getElementById("sprain").value;
g = document.getElementById("impact").value;
var x = (a + b + c + d + e + f + g);
// grouping together and doing the math
if (x = !100) {
text = "The total percentage must equal 100%";
} else {
text = "Congrats the total = 100%";
}
document.getElementById("rec_injuries").innerHTML = text;
}
</script>
</div>
<div class="well">
<p>Avg Number of Non-recordable Injuries: <input type="number" name="non_rec_injuries" />
<select name="non_rec_injury_timeframe">
<option value="last month">Last month</option>
<option value="last 6 months">Last 6 months</option>
<option value="last 12 months">Last 12 months</option>
</select>
</p>
<h4>Based on the number of Non-recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
<div class="form-group row">
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
<div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" />
</div>
</div>
</div>
</div>
<p>Estimated Cost of Productivity (Downtime)/minute: $ <input type="number" name="cost_of_productivity" /> </p>
<p>Percent of leakage related to uncontrolled dispensing: <input type="number" min="0" max="100" name="leakage" /> % </p>
<p>Which competitor is the participant using? <input type="text" name="competitor" /></p>
<p>Usage Rate per 12 months (pairs): <input type="number" min="0" name="usage_rate" /></p>
<p>Estimated cost per pair: $ <input type="number" min="0" name="cost_per_pair" /></p>
<br />
<div class="container" style="margin-left:0px; padding-left:0px;">
<div class="form-group row" style="margin-left:0px;">
<div class="col-md-3 col-sm-6">
<label for="safetyHazard1_notes"><strong>Safety observation 1:</strong></label> <input type="file" name="safetyHazard1" id="safetyHazard1" value=""><br /> <br />
<textarea cols="25" rows="3" id="safetyHazard1_notes" name="safetyHazard1_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="safetyHazard2_notes"><strong>Safety observation 2:</strong></label> <input type="file" name="safetyHazard2" id="safetyHazard2" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="safetyHazard3_notes"><strong>Safety observation 3:</strong></label> <input type="file" name="safetyHazard3" id="safetyHazard3" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="other_notes"><strong>Other observations:</strong></label> <input type="file" name="otherObservation" id="otherObservation" value=""><br /><br />
<textarea cols="25" rows="3" id="other_notes" name="other_notes" placeholder="Enter notes for this observation" ></textarea> </div>
</div></div>
<br />
<p style="margin-left:5px;"><input class="btn btn-danger" type="reset">
<input style="margin-left:10px;" class="btn btn-primary" type="button" name="new_location" value="Add Additional Location" />
<input style="margin-left:10px;" class="btn btn-success" type="submit" name="submit" value="Create New Assessment" /></p>
</form>
<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>
</body>
</html>
And finally the processing page:
<?php
require_once("../tim/includes/session.php");
require_once ("../tim/includes/functions.php");
require_once("../tim/includes/validation_functions.php");
?>
<?php
if(isset($_POST["submit"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/testing/tim/uploads/';
$target_file = $target_dir . basename($_FILES["safetyHazard1"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["safetyHazard1"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["safetyHazard1"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["safetyHazard1"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["safetyHazard1"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']);
// Process the form
$department_name = ($_POST['department_name']);
$participant_name = ($_POST['participant_name']);
$activity = ($_POST['activity']);
$location = ($_POST['location']);
$rec_injuries = ($_POST['injuries']);
$rec_injuries_timeframe = ($_POST['injury_time_frame']);
$non_rec_injuries = ($_POST['non_rec_injuries']);
$non_rec_injuries_timeframe = ($_POST['non_rec_injury_timeframe']);
$rec_cuts = ($_POST['cuts']);
$rec_burns = ($_POST['burns']);
$rec_infection = ($_POST['infection']);
$rec_dermatitis = ($_POST['dermatitis']);
$rec_puncture = ($_POST['puncture']);
$rec_sprain = ($_POST['sprain']);
$rec_impact = ($_POST['impact']);
$non_rec_cuts = ($_POST['non_rec_cuts']);
$non_rec_burns = ($_POST['non_rec_burns']);
$non_rec_infection = ($_POST['non_rec_infection']);
$non_rec_dermatitis = ($_POST['non_rec_dermatitis']);
$non_rec_puncture = ($_POST['non_rec_puncture']);
$non_rec_sprain = ($_POST['non_rec_sprain']);
$non_rec_impact = ($_POST['non_rec_impact']);
$cost_of_productivity = ($_POST['cost_of_productivity']);
$leakage = (($_POST['leakage']) / 100);
$usage_rate = ($_POST['usage_rate']);
$cost_per_pair = ($_POST['cost_per_pair']);
$condition = ($_POST['condition']);
$safety_hazard_1 = basename( $_FILES["safetyHazard1"]["name"]);
$safety_hazard_2 = ($_POST['safetyHazard2']);
$safety_hazard_3 = ($_POST['safetyHazard3']);
$other_observation = ($_POST['otherObservation']);
$safetyHazard1_notes = ($_POST['safetyHazard1_notes']);
$safetyHazard2_notes = ($_POST['safetyHazard2_notes']);
$safetyHazard3_notes = ($_POST['safetyHazard3_notes']);
$otherNotes = ($_POST['otherNotes']);
$competitor = ($_POST['competitor']);
$company_name = ($_POST['company_name']);
$date = ($_POST['date']);
$rsm = ($_POST['rsm']);
$agents = ($_POST['agents']);
$distributor = ($_POST['distributor']);
print "distributor: " . $distributor;
exit;
// Perform first database insert
$query1 = "INSERT INTO location_info (";
$query1 .= "`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `safety_hazard_1`, `safety_hazard_2`, `safety_hazard_3`, `other_observation`,`safetyHazard1_notes`, `safetyHazard2_notes`, `safetyHazard3_notes`, `otherNotes`";
$query1 .= ") VALUES (";
$query1 .= " '{$department_name}', '{$participant_name}', '{$activity}', '{$location}', '{$rec_injuries}', '{$rec_injuries_timeframe}',
'{$non_rec_injuries}', '{$non_rec_injuries_timeframe}', '{$competitor}', '{$cost_per_pair}', '{$usage_rate}', '{$leakage}', '{$cost_of_productivity}', '{$non_rec_impact}', '{$non_rec_sprain}', '{$non_rec_puncture}', '{$non_rec_dermatitis}', '{$non_rec_infection}', '{$non_rec_burns}', '{$non_rec_cuts}', '{$rec_impact}', '{$rec_sprain}', '{$rec_puncture}', '{$rec_dermatitis}', '{$rec_infection}', '{$rec_burns}', '{$rec_cuts}', '{$condition}', '{$safety_hazard_1}', '{$safety_hazard_2}', '{$safety_hazard_3}', '{$other_observation}','{$safetyHazard1_notes}', '{$safetyHazard2_notes}', '{$safetyHazard3_notes}', '{$otherNotes}'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Assessment created.";
redirect_to("results.php");
} else {
// Failure
$_SESSION["message"] = "Assessment creation failed.";
redirect_to("errors.php");
}
// Perform second database insert
$query2 = "INSERT INTO general_assessment (";
$query2 .= "`company_name`, `date`, `rsm`, `agents`, `distributor`";
$query2 .= ") VALUES (";
$query2 .= " '{$company_name}', '{$date}', '{$rsm}', '{$agents}', '{$distributor}'";
$query2 .= ")";
$result2 = mysqli_query($connection, $query2);
if ($result2) {
// Success
$_SESSION["message"] = "Assessment created.";
redirect_to("results.php");
} else {
// Failure
$_SESSION["message"] = "Assessment creation failed.";
redirect_to("errors.php");
}
}
else {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/errors-inserting.php");
}
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
You'll see on the processing page my little test of
print "distributor: " . $distributor;
exit;
this would obviously be removed when working.
Ok I think I've figured this out. I needed to "recall" the session data when I move to page 2.
So on the top of page 2 the code became:
<?php
session_start();
//store the posted values in the session variables
$_SESSION['company_name'] = $_POST['company_name'];
$_SESSION['date'] = $_POST['date'];
$_SESSION['rsm'] = $_POST['rsm'];
$_SESSION['agents'] = $_POST['agents'];
$_SESSION['distributor'] = $_POST['distributor'];
?>
You have to use line session_start(); on every page that you want to use the session - as the first line on top of the file.
You can set variables:
$_SESSION['username'] = "user";
and then retrieve them:
echo $_SESSION['username'];
You can then use session_destroy() to remove the saved session
To use a session variables for PHP at the many files. Try like this :
page1.php
<?php
session_start();
$_SESSION['name'] = 'Example session';
?>
When you use the session variables at the another page :
page2.php
<?php
include 'page1.php';
echo $_SESSION['name']; //Example session
?>
And to destroy session. Use session_destroy(); unset($_SESSION);