New Post form wont write to DB - php

I got this form for adding new posts and i can't get it to write to DB. I debugged it as much as i can and when i try to add i don't get any errors but also i don't see the post stored in my DB. Am i missing something? Code:
-This is the form
<form method = "post" action = "vpost.php" enctype="multipart/form-data">
<label>
<h5>Наслов</h5>
<input type="text" name="title" placeholder="Enter title" value = "<?php if(isset($_POST['title'])) { echo $post_title; } ?>">
</label>
<label>
<h5>Адреса</h5>
<input type="text" name="address" placeholder="Enter address" value = "<?php if(isset($_POST['address'])) { echo $post_address; } ?>">
</label>
<hr>
<label>
<h5>Цена</h5>
<input type="number" name="price" placeholder="Enter price" value = "<?php if(isset($_POST['price'])) { echo $post_price; } ?>">
</label>
<hr>
<label>
<h5>Тип</h5>
<input type="text" name="type" placeholder="Enter type" value = "<?php if(isset($_POST['type'])) { echo $post_type; } ?>">
</label>
</div>
<hr>
<div class="user-information-second">
<label>
<h5>Година на градба</h5>
<input type="number" name="year_built" placeholder="Year Built" <?php if(isset($_POST['year_built'])) { echo $post_yearbt; } ?>>
</label>
<hr>
<label>
<h5>Паркинг</h5>
<input type="text" name="parking" placeholder="parking" value = "<?php if(isset($_POST['parking'])) { echo $post_parking; } ?>">
</label>
<hr>
<label>
<h5>Квадратура</h5>
<input type="number" name="sqmeter" placeholder="sqmeter" value = "<?php if(isset($_POST['sqmeter'])) { echo $post_sqmeter; } ?>">
</label>
<br>
<hr>
<label>
<h5>Греење/Ладење</h5>
<input type="text" name="heat" placeholder="Heating" value = "<?php if(isset($_POST['heat'])) { echo $post_heat; } ?>">
</label>
<br>
<hr>
<label>
<h5>Галерија</h5>
<div class="file">
<input type="file" name="image" enctype="multipart/form-data" placeholder="Upload Image">
</div>
</label>
<br>
<hr>
<label>
<button type="submit" id="submit">Внеси Оглас</button>
</label>
</form>
-This is the validation and writing to base file
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image'])) {
require("GUMP-master/gump.class.php");
$gump = new GUMP();
$_POST = $gump->sanitize($_POST);
$gump->validation_rules(array(
'title' => 'required|max_len,120|min_len,15',
'address' => 'required|max_len,100|min_len,3',
'price' => 'required',
'type' => 'required',
'year_built' => 'required',
'parking' => 'required',
'sqmeter' => 'required',
'heat' => 'required',
));
$gump->filter_rules(array(
'title' => 'trim|sanitize_string',
'address' => 'trim|sanitize_string',
));
$validated_data = $gump->run($_POST);
if($validated_data === false) {
?>
<center><font color="red" > <?php echo $gump->get_readable_errors(true); ?> </font></center>
<?php
$post_title = $_POST['title'];
$post_address = $_POST['address'];
$post_price = $_POST['price'];
$post_type = $_POST['type'];
$post_yearbt = $_POST['year_built'];
$post_parking = $_POST['parking'];
$post_sqmeter = $_POST['sqmeter'];
$post_heat = $_POST['heat'];
}
else {
$post_title = $validated_data['title'];
$post_address = $validated_data['address'];
$post_price = $validated_data['price'];
$post_type = $validated_data['type'];
$post_yearbt = $validated_data['year_built'];
$post_parking = $validated_data['parking'];
$post_sqmeter = $validated_data['sqmeter'];
$post_heat = $validated_data['heat'];
if (isset($_SESSION['firstname'])) {
$post_author = $_SESSION['firstname'];
}
$post_date = date('Y-m-d');
$image = $_FILES['image']['name'];
$ext = $_FILES['image']['type'];
$validExt = array ("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/jpg");
if (empty($image)) {
echo "<script>alert('Attach an image');</script>";
}
else if ($_FILES['image']['size'] <= 0 || $_FILES['image']['size'] > 1024000 )
{
echo "<script>alert('Image size is not proper');</script>";
}
else if (!in_array($ext, $validExt)){
echo "<script>alert('Not a valid image');</script>";
}
else {
$folder = 'postpics/';
$imgext = strtolower(pathinfo($image, PATHINFO_EXTENSION) );
$picture = rand(1000 , 1000000) .'.'.$imgext;
if(move_uploaded_file($_FILES['image']['tmp_name'], $folder.$picture)) {
$query = "INSERT INTO posts (title,address,price,type,year_built,parking,sqmeter,heat,date,image) VALUES ('$post_title' , '$post_address' , '$post_price' , '$post_type' , '$post_yearbt' , '$post_parking', '$post_sqmeter','$post_heat','$post_date','$picture')";
$result = mysqli_query($conn , $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn) > 0) {
echo "<script> alert('Posted!');
window.location.href='index.php';</script>";
}
else {
"<script> alert('Error while posting..try again');</script>";
}
}
}
}
}
?>
First i thought that i might be missing a field in my DB but i rechecked and i created the table again. If needed i will post a picture of my posts table and the columns.

Your issue I suspect is you are checking if your image file has been uploaded with $_POST['image']. This isn't how PHP handles file uploads - they are stored in $_FILES instead so your isset($_POST['image'] == false.
This should work:
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image']) && count($_FILES) > 0)
{
//Properly sanitise and validate your inputs and do what else you need to do
}
Tip: if you ever find a PHP file just isn't doing what it should be, a conditional statement you're using to validate data is a very likely culprit. Try debugging by putting die('OK up to here'); within your if blocks to pinpoint whether code is being executed.
For example, in your code if you had debugged with:
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image'])) {
die('OK up to here');
//Your code
}
Then the OK up to here message wouldn't have been displayed in your output and you would know there was a problem with the conditional statement.

Related

$_GET value do not work in if loop

If I echo $codeee outside of the if loop, the value shows, but the value does not exist inside the loop which causes the UPDATE query to fail. How can I use the variable inside the loop?
PHP Code
require('connect.php');
$codeee = htmlspecialchars($_GET["recov"]);
echo $codeee;
$paso = $confpaso = "";
$pasoErr = $confpasoErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["paso"])) {
$pasoErr = "Password is required";
} else {
$paso = md5(test_inputing($_POST["paso"]));
}
$confpaso = md5(test_inputing($_POST["confpaso"]));
if ($confpaso != $paso) {
$confpasoErr = "Passwords do not match";
}
$emailing = test_inputing($_POST["emailing"]);
if ($pasoErr == $confpasoErr && $confpasoErr == "") {
$changepaso = "UPDATE users SET password='$paso' WHERE forgotcode = '$codeee'";
if ($conn->query($changepaso) === TRUE) {
$tellthem = "Your password was changed";
} else {
$tellthem = "Something Happened, the password was not changed";
}
}
}
HTML CODE
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?> method="post">
<div class="register-top-grid">
<h3>FILL OUT YOUR INFORMATION TO CHANGE YOUR PASSWORD</h3>
<div>
<span>Email<label>*</label></span>
<input type="text" name="emailing" >
</div>
<div>
<span>Password<label>*</label><p style="color:red"><?php echo $pasoErr ?></p></span>
<input type="password" name="paso" >
</div>
<div>
<span>Confirm Password<label>*</label><p style="color:red"><?php echo $confpasoErr ?></p></span>
<input type="password" name="confpaso" >
</div>
</div></br></br>
<input type="submit" value="submit">
<p><?php echo $tellthem ?></p>
</form>

My GET statements work correctly but my POST statements don't

I've been fiddling with this for hours and cant figure out why the $_GET statements perform correctly, but the $_POST statements don't.
IF $stock is in dB, show values in the form, and if the form is submitted submit UPDATE those values, IF $stock is NOT in dB and the form is submitted INSERT into table. Neither $_POST statement seems to work, yet are not throwing any errors, just redirecting back to the same page when you hit the submit button.
include_once ('../helper_content/sql_Connect.php');
$error = array();
$KBB_Low = "";
$KBB_High = "";
$KBB_Fair = "";
$KBB_Retail = "";
$KBB_URL = "";
$TrueCar_Great = "";
$TrueCar_Average = "";
$TrueCar_Above = "";
$TrueCar_URL = "";
$NADA_Trade = "";
$NADA_Loan = "";
$NADA_Retail = "";
# Was the form submitted via POST?
if(isset($_POST['Submit'])) {
# Yes
# Is this a new stock item?
if(empty($_POST['stock'])) {
# Yes - insert
$kbb_low = filter_var($_POST['kbb_low'], FILTER_SANITIZE_STRING);
$kbb_high = filter_var($_POST['kbb_high'], FILTER_SANITIZE_STRING);
$kbb_fair = filter_var($_POST['kbb_fair'], FILTER_SANITIZE_STRING);
$kbb_retail = filter_var($_POST['kbb_retail'], FILTER_SANITIZE_STRING);
$kbb_url = filter_var($_POST['kbb_url'], FILTER_SANITIZE_STRING);
$truecar_great = filter_var($_POST['truecar_great'], FILTER_SANITIZE_STRING);
$truecar_average = filter_var($_POST['truecar_average'], FILTER_SANITIZE_STRING);
$truecar_above = filter_var($_POST['truecar_above'], FILTER_SANITIZE_STRING);
$truecar_url = filter_var($_POST['truecar_url'], FILTER_SANITIZE_STRING);
$nada_trade = filter_var($_POST['nada_trade'], FILTER_SANITIZE_STRING);
$nada_loan = filter_var($_POST['nada_loan'], FILTER_SANITIZE_STRING);
$nada_retail = filter_var($_POST['nada_retail'], FILTER_SANITIZE_STRING);
if ($stmt = $conn->prepare("INSERT INTO `Inventory_Valuations` (`stock`,
`kbb_low`, `kbb_high`, `kbb_fair`, `kbb_retail`, `kbb_url`,
`truecar_great`, `truecar_average`, `truecar_above`, `truecar_url`,
`nada_trade`, `nada_loan`, `nada_retail`
) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param('iiiisiiisiii', $stock,
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail
);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?inserted=true');
exit();
} else {
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
} else {
# No - update
$stock = $_POST['stock'];
$kbb_low = $_POST['kbb_low'];
$kbb_high = $_POST['kbb_high'];
$kbb_fair = $_POST['kbb_fair'];
$kbb_retail = $_POST['kbb_retail'];
$kbb_url = $_POST['kbb_url'];
$truecar_great = $_POST['truecar_great'];
$truecar_average = $_POST['truecar_average'];
$truecar_above = $_POST['truecar_above'];
$truecar_url = $_POST['truecar_url'];
$nada_trade = $_POST['nada_trade'];
$nada_loan = $_POST['nada_loan'];
$nada_retail = $_POST['nada_retail'];
/*... get variables from the $_POST array */
if ($stmt = $conn->prepare("UPDATE `Inventory_Valuations` SET
kbb_low=?, kbb_high=?, kbb_fair=?, kbb_retail=?, kbb_url=?,
truecar_great=?, truecar_average=?, truecar_above=?, truecar_url=?,
nada_trade=?, nada_loan=?, nada_retail=?
WHERE stock=?")) {
$stmt->bind_param('iiiisiiisiii',
$kbb_low, $kbb_high, $kbb_fair, $kbb_retail, $kbb_url,
$truecar_great, $truecar_average, $truecar_above, $truecar_url,
$nada_trade, $nada_loan, $nada_retail,
$stock);
if ($stmt->execute()) {
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else {
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated'])) {
$message = "Record updated";
}
else if(isset($_GET['inserted'])) {
$message = "Record added into database";
}
if($stock != "") {
# Load the item?
$query = "SELECT * FROM `Inventory_Valuations` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $stock);
if($stmt->execute()) {
$result = $stmt->get_result();
if($result) {
$row = $result->fetch_assoc();
$KBB_Low = $row['kbb_low'];
$KBB_High = $row['kbb_high'];
$KBB_Fair = $row['kbb_fair'];
$KBB_Retail = $row['kbb_retail'];
$KBB_URL = $row['kbb_url'];
$TrueCar_Great = $row['truecar_great'];
$TrueCar_Average = $row['truecar_average'];
$TrueCar_Above = $row['truecar_above'];
$TrueCar_URL = $row['truecar_url'];
$NADA_Trade = $row['nada_trade'];
$NADA_Loan = $row['nada_loan'];
$NADA_Retail = $row['nada_retail'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>?cat=Sales&stock=<?= $stock; ?>">
<section class="valuations">
<h3>Valuations</h3>
<input type="hidden" name="stock" value="<?= $stock; ?>">
<div>
<a target="_blank" href="<?=$KBB_Link; ?>"><img src="images/logos/KBB.png"></a>
<p>
<label for="kbb_low">Fair Market Range</label>
<input type="number" class="dollars" id="kbb_low" name="kbb_low" placeholder="Low" value="<?= $KBB_Low; ?>"> -
<input type="number" class="dollars" id="kbb_high" name="kbb_high" placeholder="High" value="<?= $KBB_High; ?>">
</p>
<p>
<label for="kbb_fair">Fair Price</label>
<input type="number" class="dollars" id="kbb_fair" name="kbb_fair" placeholder="Fair" value="<?= $KBB_Fair; ?>">
</p>
<p>
<label for="kbb_retail">Sug. Retail</label>
<input type="number" class="dollars" id="kbb_retail" name="kbb_retail" placeholder="Retail" value="<?= $KBB_Retail; ?>">
</p>
<p class="clear">
<label for="kbb_url">Report URL</label>
<input type="url" id="kbb_url" name="kbb_url" size="20" spellcheck="false" placeholder="www.kbb.com/" value="<?= $KBB_URL; ?>">
<i title="Copy KBB URL" data-clipboard-target="#kbb_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<img src="images/logos/TrueCar.png">
<p><label for="truecar_great">Great Price</label> <input type="number" class="dollars" id="truecar_great" name="truecar_great" placeholder="Great" value="<?= $TrueCar_Great; ?>"></p>
<p><label for="truecar_average">Average Price</label> <input type="number" class="dollars" id="truecar_average" name="truecar_average" placeholder="Average" value="<?= $TrueCar_Average; ?>"></p>
<p><label for="truecar_above">High Price</label> <input type="number" class="dollars" id="truecar_above" name="truecar_above" placeholder="Above" value="<?= $TrueCar_Above; ?>"></p>
<p class="clear">
<label for="truecar_url">Report URL</label> <input type="url" id="truecar_url" name="truecar_url" size="20" spellcheck="false" placeholder="www.truecar.com/" value="<?= $TrueCar_URL; ?>">
<i title="Copy TrueCar URL" data-clipboard-target="#truecar_url" data-clipboard-action="copy" class="fa fa-clipboard" aria-hidden="true"></i>
</p>
</div>
<div>
<a target="_blank" href="http://www.nadaguides.com/Cars/<?= $year; ?>/<?= $make; ?>/<?= $model; ?>"><img src="images/logos/NADA.png"></a>
<p><label for="nada_trade">Trade</label> <input type="number" class="dollars" id="nada_trade" name="nada_trade" placeholder="Trade" value="<?= $NADA_Trade; ?>"></p>
<p><label for="nada_loan">Loan</label> <input type="number" class="dollars" id="nada_loan" name="nada_loan" placeholder="Loan" value="<?= $NADA_Loan; ?>"></p>
<p><label for="nada_retail">Retail</label> <input type="number" class="dollars" id="nada_retail" name="nada_retail" placeholder="Retail" value="<?= $NADA_Retail; ?>"></p>
</div>
<input type="submit" id="Submit" value="Submit">
</form>
<script src="include/js/clipboard.min.js"></script>
<script>
var clipboard = new Clipboard('.fa-clipboard');
clipboard.on('success', function(e) {console.log(e);});
clipboard.on('error', function(e) {console.log(e);});
</script>
Replace
if(isset($_POST['Submit']))
with
if (!empty($_POST))
this checks in general if anything has been posted (if the POST request is not empty -> do this)
Please verify your submit have this ...
<input type="submit" value="Submit" name="submit" />
and your form method is
<form method="POST" action="xyz"> ...
Your code is a bit off.
You're checking
if(isset($_POST['Submit'])) {
Which is not being posted at all. This is why, the if part never gets executed.
You can try to check if it is POST request by
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
maybe this helps.
You should use filter_input to handle POST and GET params. Using $_POST or $_GET is deprecated.

Carrying a variable via session to another file

I have searched through numerous posts on this site to figure out why my session variable is not being recognized, but I haven't been able to figure out a solution.
It is really simply what I am trying to do. I have two PHP files. The first one I have the following code. I HAVE started a session.
PHP file 1
$profile_viewer = $_GET['user'];
$_SESSION['viewer'] = $profile_viewer;
PHP file 2
$_SESSION['viewer'] = $profile_viewer;
I keep getting the error : Notice: Undefined variable: profile_viewer
What am I doing wrong with putting $profile_viewer in the session and then calling for it?
EDIT:
File 1
$profile_user = $_GET['user'];
$_SESSION['viewer'] = $profile_user;
File 2
$user = new User();
//$profile_user = $_GET['user'];
$profile_user = $_SESSION['viewer'];
echo $profile_user;
$friend_status = $_POST['friend_status'];
$okay = true;
if ( $okay ) {
$add_friend_sql = "
INSERT INTO friends
(friend_one, friend_two, date)
VALUES(?, ?, NOW())
";
$add_friend_stmt = $con->prepare($add_friend_sql);
$add_friend_stmt->execute(array($user_id, $profile_user));
}
Full code for file 1
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once '../core/init_account.php';
if(Session::exists('home')) {
echo '<p>' . Session::flash('home') . '</p>';
}
if(!$user->isLoggedIn()) {
Redirect::to('../index');
}
$profile_user = $_GET['user'];
$_SESSION['viewer'] = $profile_user;
// If you make a file function, you can change where things are saved
// You can also change the destination (for portability)
function UploadFile($fileArray = array(), $destinationFolder = 'profile_images/') {
$filename = $fileArray['file']['name'];
$tmp_name = $fileArray['file']['tmp_name'];
$filesize = $fileArray['file']['size'];
$file_error = $fileArray['file']['error'];
$file = $fileArray['file'];
// Save all the default data.
// Success and error should be set by default to fail
$return['error'] = true;
$return['success'] = false;
$return['file']['dest'] = $destinationFolder.$filename;
$return['file']['size'] = $filesize;
if($file_error == 0)
$return['error'] = false;
// I added a directory creation function so you don't have to
// manually make folders. This will do it for you.
if(!is_dir($destinationFolder))
mkdir($destinationFolder,0755,true);
// If your filename is not empty, return success or fail of upload
if (!empty($filename))
$return['success'] = (move_uploaded_file($tmp_name, $destinationFolder.$filename));
return $return;
}
// Create a save-to-database function so it's easier and reusable
function SaveToDb($con,$filename = false) {
// Return fail immediately if the connection is false or image is invalid
if(empty($filename) || !$con)
return false;
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$img_insert_sql = "
INSERT INTO profile_img
(user_id, img)
VALUES (?, ?)
";
if($img_insert_stmt = $con->prepare($img_insert_sql)) {
$img_insert_stmt->execute(array($user_id, $filename));
return true;
}
return false;
}
// Get current profile img
function getPhoto($con) {
$user_id = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$profile_viewer = $_GET['user'];
if ($profile_viewer == $user_id) {
/*$img_select_sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC
LIMIT 1
";*/
$img_select_sql = "
SELECT i.*
FROM profile_img i
WHERE user_id IN (?, ?)
ORDER BY id DESC
LIMIT 1;
";
}
else {
//echo "This is not your image";
echo $profile_viewer;
$img_select_sql = "
SELECT i.*
FROM profile_img i
WHERE user_id IN (?, ?)
ORDER BY id DESC
LIMIT 1;
";
}
if ($select_img_stmt = $con->prepare($img_select_sql)) {
$select_img_stmt->execute(array($user_id, $profile_user));
$rows = $select_img_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
//$status = $row['status'];
return $row;
}
}
}
// Make sure all functions above are include here. Checks for post
if(isset($_POST['create'])) {
// Try uploading
$upload = UploadFile($_FILES);
// If upload fails
if(!$upload['success']) {
echo '<h3>Sorry, an error occurred</h3>';
}
else {
// You could add error handling here based on the results of
// each function's success or failure below.
// Try to save it
$saveToDb = SaveToDb($con,$upload['file']['dest']);
// Get the profile from image name
$profPic = ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;
}
}
$profPic = getPhoto($con);
?>
</head>
<body>
<?php
include_once("../analyticstracking.php");
if($user->hasPermission('User')) {
include 'nav/navUser.php';
}
?>
<div id="main">
<?php
$profile_viewer_message = null;
if($profile_user == $user_id) {
echo $profile_viewer_message = "This is your profile.";
} else {
echo $profile_viewer_message = "You are viewing someone elses profile.";
echo '<div id="add-friend"><img src="../icons/collection/add.png" alt="Add Friend">' . "Add Friend" . '</div>';
}
?>
<div id="profile-pic-container">
<img id="profile-pic" src="<?php echo (!empty($profPic) && $profPic != 0)? $profPic['img'] : "profile_images/default.jpg"; ?>" alt="<?php echo (!empty($profPic) && $profPic != 0)? "Profile Picture" : "No Picture"; ?>" />
<img src="../icons/photo-camera.png" id="change-picture" alt="Profile Picture">
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-profile-pic" name="file" class="file-input">
<div id="profile-pic-change">Change profile pic</div>
</div>
<!-- <img width="300px" height="200px" class="none" id="file" src="#" alt="your image">
<input type="submit" class="none" name="create" value="Upload Profile Picture">
</form> -->
<div id="new-profile-pic-preview">
<div id="pic-preview-container"><img class="none pic-preview total-center" id="file" src="#" alt="your image"></div>
<input type="submit" class="none" name="create" value="Upload Profile Picture">
</form>
<a class="popup-close" data-popup-close="popup-1" href="#">Close</a>
</div>
<!-- <form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-profile-pic" name="file" class="file-input">
<img width="300px" height="200px" class="none" id="file" src="#" alt="your image">
<input type="submit" class="none" name="create" value="Upload Profile Picture">
</form> -->
<form action="profile.php" method="POST">
<div class="field">
<label for="streetline1">First Name</label>
<input type="text" class="inputbar" name="streetline1" value="<?php echo escape($user->data()->firstname); ?>">
</div>
<div class="field">
<label for="streetline2">Last Name</label>
<input type="text" class="inputbar" name="streetline2" value="<?php echo escape($user->data()->lastname); ?>">
</div>
<div class="field">
<label for="city">Email</label>
<input type="text" class="inputbar" name="city" value="<?php echo escape($user->data()->email); ?>">
</div>
<div class="field">
<label for="state">Phone</label>
<input type="text" class="inputbar" name="state" value="<?php echo escape($user->data()->phone); ?>">
</div>
<div class="field">
<label for="zipcode">Phone Network</label>
<input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->network); ?>">
</div>
<div class="field">
<label for="zipcode">Birthday</label>
<input type="text" class="inputbar" name="zipcode" value="<?php echo escape($user->data()->birthday); ?>">
</div>
<label for="submit">
<input id="signinButton" name="submit" type="submit" value="Submit">
</label>
</form>
</div>
</body>
</html>
Session class
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function flash($name, $string = '') {
if(self::exists($name)) {
$session = self::get($name);
self::delete($name);
return $session;
} else {
self::put($name, $string);
}
}
}
The only variables that get carried between scripts are $_SESSION['xxx']. Ordinary variables like $profile_user don't persist. The assignment
$_SESSION['viewer'] = $profile_user;
doesn't make $profile_user get copied, it copies its value into $_SESSION, and you have to pull it out of there in the other script. So script 2 should start with:
session_start();
$profile_user = $_SESSION['viewer'];

Unable to insert image to database

I have a problem inserting images in my database with a basic form. There is two forms, one inserts categories (an image and a name) and the other inserts a location(Name, Address, image, etc). The add_category function works fine it's the add_location that doesn't and specifically inserting the image. And I believe it's inserting the image that is problematic.
The problem is that this if statement in the insert image never get executed and I don't know why. It's in the function add_location(..) under the check image if statement.
if ($result = $this->mysqli->query($query)) {
$error['result'] = $this->succAddLoc;
}
I removed unnecessary functions in the file:
<?php
class pongodev {
var $mysqli;
// Error handling variables
var $errCatName;
var $errLatitude;
var $errLongitude;
var $errImage;
var $errPhone;
var $errWebsite;
var $succAddLoc;
var $succAddCat;
var $errEmail;
var $errPass;
var $succPass;
var $succEmail;
var $succEmailPass;
var $succResetPass;
var $errResetPass;
var $errUsername;
// Email configuration variables
var $emailSubject;
var $resetMessage;
var $from;
var $adminEmail;
// Connect to database
function __construct($host, $user, $pass, $database){
// Connect to database
$this->mysqli = new mysqli($host, $user, $pass, $database);
if(mysqli_connect_errno($this->mysqli)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
// Close database
function close_database(){
$this->mysqli->close();
}
// Validate username and password
function validate_user($username, $password){
......
}
// Error handling label for reset password form
function fill_error_pass($succResetPass, $errResetPass, $errUsername){
......
}
// Email message configuration
function email_configuration($emailSubject, $resetMessage, $from, $adminEmail){
.....
}
// Reset password
function reset_password($username){
.....
}
// Error handling label for add new location form
function fill_error_location_data($errLatitude, $errLongitude, $errPhone, $errWebsite,
$errImage, $succAddLoc){
$this->errLatitude = $errLatitude;
$this->errLongitude = $errLongitude;
$this->errPhone = $errPhone;
$this->errWebsite = $errWebsite;
$this->errImage = $errImage;
$this->succAddLoc = $succAddLoc;
}
// Add new location
function add_location($locationName, $address, $category,
$locImage, $lat, $lng, $tel, $url, $desc){
// Create array variables to store multiple error
$error = array();
// Check if latitude is float
$floatLat = floatVal($lat);
if(!($floatLat && intVal($floatLat) != $floatLat)){
$error['latitude'] = $this->errLatitude;
}
// Check if Longitude is float
$floatLng = floatVal($lng);
if(!($floatLng && intVal($floatLng) != $floatLng)){
$error['longitude'] = $this->errLongitude;
}
// Validate phone number
if(empty($tel) || ($tel == "-")){
$tel = "-";
}else{
$phonePattern = "/^[0-9()-]+$/";
if(!preg_match($phonePattern, $tel)){
$error['phone'] = $this->errPhone;
}
}
// Validate website
if(empty($url) || ($url == "-")){
$url = "-";
}else{
$urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i";
if (!preg_match($urlPattern, $url)){
$error['website'] = $this->errWebsite;
}
}
// Check image file
$allowedExts = array("jpeg", "jpg");
$temp = explode(".", $locImage["name"]);
$extension = end($temp);
if (((($locImage["type"] == "image/jpeg")
|| ($locImage["type"] == "image/jpg"))
|| ($locImage["type"] == "image/pjpeg"))
&& ($locImage["size"] < 700000)
&& in_array($extension, $allowedExts)
&& !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){
// Create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $locImage['name']);
$imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
// Copy file to server directory
move_uploaded_file($locImage["tmp_name"],
"upload/images/" . $imageUpload);
$imageUpload = "upload/images/". $imageUpload;
$locationDate = date("Y-m-d");
// Add location data to tbl_location
$query = "INSERT INTO tbl_location
(location_date, location_name, category_id, address, location_image,
latitude, longitude, phone, website, description)
VALUES ('$locationDate','$locationName', '$category', '$address', '$imageUpload',
$lat, $lng, '$tel', '$url', '$desc')";
if($result = $this->mysqli->query($query)){
$error['result'] = $this->succAddLoc;
}
}else{
$error['image'] = $this->errImage;
}
return $error;
}
// Get all locations data
function get_all_locations(){
.....
}
// Get all locations data for map
function get_all_locations_map(){
.....
}
// Get location data by id
function get_location_by_id($id, $tag){
.....
}
// Get location data to be displayed on location view page
function get_location_view($id){
// Get all locations data from tbl_location
$query = "SELECT location_name, category_name, category_marker, address, location_image, latitude, longitude, phone, website, description
FROM tbl_location l, tbl_categories c
WHERE (l.category_id = c.category_id) AND (l.location_id = ?)";
$stmt = $this->mysqli->stmt_init();
if($stmt->prepare($query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $id);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($data['location_name'],
$data['category_name'],
$data['category_marker'],
$data['address'],
$data['location_image'],
$data['latitude'],
$data['longitude'],
$data['phone'],
$data['website'],
$data['description']
);
$stmt->fetch();
$stmt->close();
}
return $data;
}
// Delete location data
function delete_location($id){
......
}
// Add new location
function update_location($id, $locationName, $address, $category,
$locImage, $lat, $lng, $tel, $url, $desc, $previousImage){
// Create array variables to handle multiple errors
$error = array();
// Check if latitude is float
$floatLat = floatVal($lat);
if(!($floatLat && intVal($floatLat) != $floatLat)){
$error['latitude'] = $this->errLatitude;
}
// Check if Longitude is float
$floatLng = floatVal($lng);
if(!($floatLng && intVal($floatLng) != $floatLng)){
$error['longitude'] = $this->errLongitude;
}
// Validate phone number
if(empty($tel) || ($tel == "-")){
$tel = "-";
}else{
$phonePattern = "/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/";
if(!preg_match($phonePattern, $tel)){
$error['phone'] = $this->errPhone;
}
}
// Validate url
if(empty($url) || ($url == "-")){
$url = "-";
}else{
$urlPattern = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i";
if (!preg_match($urlPattern, $url)){
$error['website'] = $this->errWebsite;
}
}
// Check image location
if(empty($locImage['name'])){
if(!isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){
// Add location data to database
$query = "UPDATE tbl_location
SET location_name = '$locationName',
category_id = '$category',
address = '$address',
latitude = '$lat',
longitude = '$lng',
phone = '$tel',
website = '$url',
description = '$desc'
WHERE location_id = '$id'";
if($result = $this->mysqli->query($query)){
$error['result'] = $this->succAddLoc;
}
}
}else{
// Check image file
$allowedExts = array("jpeg", "jpg");
$temp = explode(".", $locImage["name"]);
$extension = end($temp);
if (((($locImage["type"] == "image/jpeg")
|| ($locImage["type"] == "image/jpg"))
|| ($locImage["type"] == "image/pjpeg"))
&& ($locImage["size"] < 700000)
&& in_array($extension, $allowedExts)
&& !isset($error['latitude']) && !isset($error['longitude']) && !isset($error['phone']) && !isset($error['website'])){
// Create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $locImage['name']);
$imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
// Copy file to server directory
move_uploaded_file($locImage["tmp_name"],
"upload/images/" . $imageUpload);
$imageUpload = "upload/images/". $imageUpload;
// Delete previous image
$delete = unlink("$previousImage");
// Add location data to database
$query = "UPDATE tbl_location
SET location_name = '$locationName',
category_id = '$category',
address = '$address',
location_image = '$imageUpload',
latitude = '$lat',
longitude = '$lng',
phone = '$tel',
website = '$url',
description = '$desc'
WHERE location_id = '$id'";
if($result = $this->mysqli->query($query)){
$error['result'] = $this->succAddLoc;
}
}else{
$error['image'] = $this->errImage;
}
}
return $error;
}
// Error handling label
function fill_error_category_data($errCatName, $errImage, $succAddCat){
$this->errImage = $errImage;
$this->errCatName = $errCatName;
$this->succAddCat = $succAddCat;
}
// Delete category
function delete_category($id){
......
}
// Add new category
function add_category($categoryName, $markerImage){
// Get category data from tbl_categories
$query = "SELECT * FROM tbl_categories
WHERE category_name = '$categoryName'";
if($result = $this->mysqli->query($query)){
$row = $result->num_rows;
$result->close();
}
// Create array variables to handle multiple array
$error = array();
// If category already exist in tbl_categories set the error
if($row > 0){
$error['name'] = $this->errCatName;
}
list($width, $height, $type, $attr) = getimagesize($markerImage["tmp_name"]);
$allowedExts = array("png");
$temp = explode(".", $markerImage["name"]);
$extension = end($temp);
if ((($markerImage["type"] == "image/x-png")
|| ($markerImage["type"] == "image/png"))
&& ($markerImage["size"] < 100000)
&& in_array($extension, $allowedExts)
&& (($width == 64) && ($height == 64))
&& !isset($error['name']) ){
// Create random image file name
$string = '0123456789';
$file = preg_replace("/\s+/", "_", $markerImage['name']);
$imageUpload = date("Y-m-d")."-".$this->get_random_string($string, 4).".".$extension;
// Copy image to server directory
move_uploaded_file($markerImage["tmp_name"],
"upload/markers/" . $imageUpload);
$imageUpload = "upload/markers/". $imageUpload;
// Add category to database
$query = "INSERT INTO tbl_categories
(category_name, category_marker)
VALUES ('$categoryName', '$imageUpload')";
if($result = $this->mysqli->query($query)){
debug_to_console( $query);
$error['result'] = $this->succAddCat;
}
}else{
$error['marker'] = $this->errImage;
}
return $error;
}
// Get all categories data
function get_all_categories(){
// Get categories data from database
$query = "SELECT * FROM tbl_categories
ORDER BY category_id";
$result = $this->mysqli->query($query);
return $result;
}
// Get category data
function get_category_by_id($id){
.....
}
// Update category data
function update_category($id, $previousName, $categoryName, $categoryMarker, $previousMarker){
.......
}
// Create random name for image file
function get_random_string($valid_chars, $length){
$random_string = "";
$num_valid_chars = strlen($valid_chars);
for ($i = 0; $i < $length; $i++){
$random_pick = mt_rand(1, $num_valid_chars);
$random_char = $valid_chars[$random_pick-1];
$random_string .= $random_char;
}
return $random_string;
}
// Error handling label
function fill_error_settings($errEmail, $errPass, $succPass, $succEmail, $succEmailPass){
$this->errEmail = $errEmail;
$this->errPass = $errPass;
$this->succPass = $succPass;
$this->succEmail = $succEmail;
$this->succEmailPass = $succEmailPass;
}
// Settings
function settings($user, $email, $newPass, $confirmPass){
.....
}
}
?>
Here is add_location_form.php
<?php
include('variables/variables.php');
include('libs/pongodev.php');
// Create object of pongodev class
$objMap = new pongodev($host, $userdb, $passdb, $database);
$result = 9999;
// Get all category name
$resultCategory = $objMap->get_all_categories();
// Initialize location data
$locationName = '';
$address = '';
$category = '';
$image = '';
$latitude = '';
$longitude = '';
$phone = '';
$website = '';
$description = '';
// When user click on Submit button
if(isset($_POST['btnSubmit'])){
// Get location data
$locationName = $_POST['locationName'];
$address = $_POST['address'];
$category = $_POST['category'];
$image = $_FILES['image'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$phone = $_POST['phone'];
$website = $_POST['website'];
$description = $_POST['description'];
// Create array variables
$result = array();
// Fill error label
$objMap->fill_error_location_data($lblErrLatitude, $lblErrLongitude, $lblErrPhone, $lblErrWebsite, $lblErrImage, $lblAddLocSuccess);
// Add location data to database
$result = $objMap->add_location($locationName, $address, $category,
$image, $latitude, $longitude,
$phone, $website, $description);
}
?>
<div class="content-container">
<div class="row heading-container">
<div class="col-xs* col-md-9">
<h1><?php echo $lblAddNewLocation; ?></h1>
</div>
</div><!--/heading-container-->
<div class="clear"></div>
<form class="form-horizontal" role="form" method="post" enctype="multipart/form-data">
<!-- Location name form -->
<div class="form-group">
<label for="inputLocationName" class="col-sm-2 control-label"><?php echo $lblName; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLocationName" name="locationName" placeholder="<?php echo $lblName; ?>" value="<?php echo $locationName; ?>" required focus>
</div><!--/span-->
</div><!--/form-group-->
<!--/Location name form -->
<!-- Address form -->
<div class="form-group">
<label for="inputAddress" class="col-sm-2 control-label"><?php echo $lblAddress; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputAddress3" name="address" placeholder="<?php echo $lblAddress; ?>" value="<?php echo $address; ?>" required>
</div><!--/span-->
</div><!--/form-group-->
<!--/Address form -->
<!-- Category form -->
<div class="form-group">
<label for="inputCategory" class="col-sm-2 control-label"><?php echo $lblCategory; ?></label>
<div class="col-sm-10">
<select class="form-control" id="inputCategory" name="category" required>
<?php while($data = mysqli_fetch_array($resultCategory)){
if($data['category_id'] == $category){?>
<option value="<?php echo $data['category_id']; ?>" selected><?php echo $data['category_name']; ?></option>
<?php }else{ ?>
<option value="<?php echo $data['category_id']; ?>"><?php echo $data['category_name']; ?></option>
<?php }
}?>
</select>
</div><!--/span-->
</div><!--/form-group-->
<!--/Category form -->
<!-- Latitude form -->
<?php echo isset($result['latitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputLatitude" class="col-sm-2 control-label"><?php echo $lblLatitude; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLatitude" name="latitude" placeholder="<?php echo $lblLatitude; ?>" value="<?php echo $latitude; ?>" required>
<span class="help-block"><em><?php echo isset($result['latitude']) ? $result['latitude']." ".$lblLatitudeHelp : $lblLatitudeHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Latitude form -->
<!-- Longitude form -->
<?php echo isset($result['longitude']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputLongitude" class="col-sm-2 control-label"><?php echo $lblLongitude; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLongitude" name="longitude" placeholder="<?php echo $lblLongitude; ?>" value="<?php echo $longitude; ?>" required>
<span class="help-block"><em><?php echo isset($result['longitude']) ? $result['longitude']." ".$lblLongitudeHelp : $lblLongitudeHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Longitude form -->
<!-- Image form -->
<?php echo isset($result['image']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputImage" class="col-sm-2 control-label"><?php echo $lblImage; ?></label>
<div class="col-sm-10">
<input type="file" class="form-control" id="inputImage" name="image" required>
<span class="help-block"><em><?php echo isset($result['image']) ? $result['image']." ".$lblImageHelp : $lblImageHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Image form -->
<!-- Phone form -->
<?php echo isset($result['phone']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputPhone" class="col-sm-2 control-label"><?php echo $lblPhone; ?></label>
<div class="col-sm-10">
<input type="tel" class="form-control" id="inputPhone" name="phone" placeholder="<?php echo $lblPhone; ?>" value="<?php echo $phone; ?>">
<span class="help-block"><em><?php echo isset($result['phone']) ? $result['phone']." ".$lblPhoneHelp : $lblPhoneHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Phone form -->
<!-- Website form -->
<?php echo isset($result['website']) ? '<div class="form-group has-error">' : '<div class="form-group">'; ?>
<label for="inputWebsite" class="col-sm-2 control-label"><?php echo $lblWebsite; ?></label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputWebsite" name="website" placeholder="<?php echo $lblWebsite; ?>" value="<?php echo $website; ?>">
<span class="help-block"><em><?php echo isset($result['website']) ? $result['website']." ".$lblWebsiteHelp : $lblWebsiteHelp; ?></em></span>
</div><!--/span-->
</div><!--/form-group-->
<!--/Website form -->
<!-- Description -->
<div class="form-group">
<label for="inputDescription" class="col-sm-2 control-label"><?php echo $lblDescription; ?></label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="inputDescription" name="description" placeholder="Description" required><?php echo $description; ?></textarea>
</div><!--/span-->
</div><!--/form-group-->
<!--/Description -->
<!-- if add data success show success alert, otherwise display error alert -->
<?php if($result != 9999){
if(isset($result['result'])){ ?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<p><?php echo $result['result']; ?></p>
</div>
<?php }else{ ?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<p><?php echo $lblErrData; ?></p>
</div>
<?php }} ?>
<!--/Adding result -->
<!-- Submit button -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="reset" class="btn btn-default"><?php echo $lblReset; ?></button>
<button type="submit" class="btn btn-primary" name="btnSubmit"><?php echo $lblSubmit; ?></button>
</div><!--/span-->
</div><!--/form-group-->
<!--/Submit button -->
</form>
</div><!--/contain-container-->
<?php $objMap->close_database(); ?>
Replace :
$image = $_FILES['image'];
with
$image = $_FILES['image']['name'];
if you want the image nameor : with :
$image = $_FILES['image']['tmp_name'];
if you mean the file
try this $image = $_FILES['image']['name']; instead of $image = $_FILES['image'];
$_FILES['image'] contains array of all related information of uploaded file like name, type,size,error,tmp_name, so whatever datat you want you need to call like:
$_FILES['image']['name']
$_FILES['image']['type'] etc.
Hope this helps you...:)
Inserting Images into your database is not a good idea. It is advisable to rather move your uploaded images into a given directory and save the path to the image in to your database.
just do the following..
$image=$_FILES['image']['name'];
take the values in the $image variable in the above way, m sure your problem will be solved.

PHP issue with submitting form and storing in the Database, small issue giving me strife

I am trying to store information sent via a form into a MySQL DB. It doesn't load the next page nor does it store the information.
My header requires init.php which I can confirm has the correct database connection credentials.
The following is my HTML and "uploader" script - I know it must be something silly but this is where the issue lies, in the html and/or the uploader.php.
If someone could run through my code and point out each issue (and possibly a re-work of my code) it would be very much appreciated! Thank you!!
HTML (I've reduced the Date of Birth options so there's less code here)
<h2>Choose Your File</h2>
<form id="submit-photo" action="index.php?p=uploader" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<div id="FileUpload">
<input type="file" name="photo" id="BrowserHidden" onchange="getElementById('FileField').value = getElementById('BrowserHidden').value;" />
<div id="BrowserVisible"><input type="text" id="FileField" /></div>
<span class="error"><?php if(isset($_SESSION['flash_message']['photo'])) echo $_SESSION['flash_message']['photo'] ?>
</span></div>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name">
</fieldset>
<fieldset>
<label for="dob">DOB</label>
<div class="dob-select">
<select name="dob_day" id="dob_day">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
</select>
</div>
<div class="dob-select">
<select name="dob_month" id="dob_month">
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
</select>
</div>
<div class="dob-select">
<select name="dob_year" id="dob_year">
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
</select>
</div>
</fieldset>
<fieldset>
<label for="postcode">Postcode</label>
<input type="text" class="short" name="postcode" id="postcode">
</fieldset>
<fieldset>
<label for="email">Email</label>
<input type="email" name="email" id="email">
</fieldset>
<fieldset>
<label for="subscribe"><input type="checkbox" class="left" id="subscribe"> <p class="left">subscribe</p></label>
<input type="submit" name="submit">
</fieldset>
</form>
DB Columns
id (auto-incremented)
name
photo (path to file)
email
date (date of birth: day, month, year to be combined to form this)
postcode
subscribe (should be 0 or 1)
approve
created (timestamp)
Uploader PHP
<?php $error = array();
require_once 'init.php';
//Is request?
if(strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
//$friend = ( $_POST['friend'] == 'true' ) ? 1 : 0;
$required_array = array(
'name' => 'Name',
'dob_day' => 'Day',
'dob_month' => 'Month',
'dob_year' => 'Year',
'postcode' => 'Postcode',
'email' => 'Email Address',
'subscribe' => 'subscribe'
);
$required_error = array();
foreach( $required_array as $field_name => $field ) {
if(!isset($_POST[$field_name]) OR empty($_POST[$field_name]) OR $_POST[$field_name] == '') {
$required_error[$field_name] = 'Please insert your '. $field;
}
}
$_POST['email'] = verify_email($_POST['email']);
if($_POST['email'] == FALSE && !isset($error['email']))
$error['email'] = 'Please use a valid email address';
//Validate the form key
if(!isset($_POST['form_key']) || !$formKey->validate()) {
//Form key is invalid, show an error
$error['general'] = 'Use the real form!';
} else {
if((!empty($_FILES["photo"])) && ($_FILES['photo']['error'] == 0)) {
$filename = basename($_FILES['photo']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
//Check if the file is JPEG image and it's size is less than 1Mb
if ( ($ext == "jpg") && ($_FILES["photo"]["type"] == "image/jpeg") && ($_FILES["photo"]["size"] <= 5242880) ) {
//Determine the path to which we want to save this file
$newname = str_replace( ' ', '_', trim( strip_tags( $_POST['name'] ) ) ) . _ . $formKey->generateKey() . '_' . time() . '.jpg';
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
if (sizeof($required_error) == 0) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['photo']['tmp_name'], './photos/'. $newname))) {
$move_status = 'done';
} else {
$error['photo'] = "A problem occurred during file upload!";
}
}
} else {
$error['photo'] = "File ".$_FILES["photo"]["name"]." already exists";
}
} else {
$error['photo'] = "Only .jpg images under 5Mb are accepted for upload". $_FILES["photo"]["size"] . $_FILES["photo"]["type"] . '====' . $ext;
}
} else {
$error['photo'] = "No photo uploaded";
}
}
$error = $error + $required_error;
if (sizeof($error) == 0 AND $move_status == 'done') {
$_POST['date'] = $_POST['dob_day'].'-'.$_POST['dob_month'].'-'.$_POST['dob_year'];
$query = sprintf("INSERT INTO `$db_name`.`submissionform` (`id` , `name` , `photo` , `email` , `date` , `postcode` , `subscribe` , `approve` , `created` )
VALUES ( NULL , '%s', '%s', '%s', '%s', '%s', '%s', '0', CURRENT_TIMESTAMP );",
mysql_real_escape_string($_POST['name']),
mysql_real_escape_string($newname),
mysql_real_escape_string($_POST['email']),
mysql_real_escape_string($_POST['date']),
mysql_real_escape_string($_POST['postcode']),
mysql_real_escape_string($_POST['subscribe']),
mysql_real_escape_string($_POST['approve']),
mysql_real_escape_string($_POST['message'])
);
mysql_query('SET AUTOCOMMIT=0');
$result1 = mysql_query($query);
$last_id = mysql_insert_id();
if ($result1)
$success = 'Done';
else
$error['general'] = 'Error when submitting your form, please try again.';
//mysql_free_result($result);
mysql_close();
}
}
if ($success == 'Done') {
$page = 'uploader';
include 'header.php';
echo '<img height="782" style="float:left;" src="./assets/img/success.png" />';
include 'footer.php';
} else {
$_SESSION['flash_message'] = $error;
$_SESSION['recent_field'] = $_POST;
header('Location: ./index.php');
}
?>
edit: I did some debugging- by placing ini_set('display_errors', 'On'); error_reporting(E_ALL); at the top of uploader.php
Errors are:
Notice: Undefined variable: success in ..../uploader.php on line 100
Warning: Cannot modify header information - headers already sent by (output started at..../uploader.php:100) in ....uploader.php on line 110
checkbox subscribe doesn't have a name field, in these lines,
<fieldset>
<label for="subscribe"><input type="checkbox" class="left" id="subscribe"> <p class="left">subscribe</p></label>
<input type="submit" name="submit">
</fieldset>
So the check inside foreach won't pass through.
foreach( $required_array as $field_name => $field ) {
if(!isset($_POST[$field_name]) OR empty($_POST[$field_name]) OR $_POST[$field_name] == '') {
$required_error[$field_name] = 'Please insert your '. $field;
}
}
Also, $_POST['form_key'] is not being set, which wouldn't pass this line,
//and subsequently have an $error and not execute the query.
if(!isset($_POST['form_key']) || !$formKey->validate()) {
Is id a primary key? you're inserting a NULL value to it, in the query. It won't auto-increment if you pass an id value in the query.

Categories