I'm using AngularJs and PHP to try and accomplish this but it doesn't seem to work.
I have created a virtual host with WAMP and inside the folder from which I'm receiving all my content I have created an uploads folder to which I would like to store files I have uploaded via different forms. The problem is that whenever I execute my PHP the folder is still empty. Here is the code I use:
AngularJs
myApp.controller('AdminPromotionsDetailsController', function($scope, $http) {
$scope.msg = '';
$scope.msg_type = 'error';
$scope.savePromotion = function(promotion) {
$scope.promotion.PromotionPhoto = promotion.PromotionPhoto.name;
$http.post('save.php', promotion)
.success(function(data, status, headers, config) {
if (data == 'success') {
$scope.msg = 'Success message';
$scope.msg_type = 'success';
} else {
$scope.msg = 'Error message';
$scope.msg_type = 'error';
}
}).error(function(data, status) {
$scope.msg = 'Error message';
$scope.msg_type = 'error';
});
}
});
PHP
<?php
$con = mysqli_connect('ecommerce', 'root', '', 'my_db');
// Check connection
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($con,"utf8");
$data = json_decode(file_get_contents("php://input"));
$id = '';
if(!empty($data->PromotionId)) {
$id = mysqli_real_escape_string($con, $data->PromotionId);
}
$name = mysqli_real_escape_string($con, $data->PromotionName);
$link = mysqli_real_escape_string($con, $data->PromotionLink);
$cover = mysqli_real_escape_string($con, $data->PromotionPhoto);
$date_start = mysqli_real_escape_string($con, $data->PromotionDateStart);
$date_end = mysqli_real_escape_string($con, $data->PromotionDateEnd);
$folder = 'http://ecommerce/uploads/';
move_uploaded_file($cover, "$folder".$cover);
if(!empty($data->PromotionContent)) {
$content = mysqli_real_escape_string($con, $data->PromotionContent);
} else {
$content = '';
}
if ($id != '') {
$sql = "UPDATE `promotions` SET PromotionName='$name', PromotionLink='$link', PromotionPhoto='$cover', PromotionDateStart='$date_start', PromotionDateEnd='$date_end', PromotionContent='$content' WHERE `PromotionId`='$id'";
$sql_res = mysqli_query($con, $sql) or die(mysqli_error($con));
if ($sql_res) {
print 'success';
} else {
print 'error';
}
} else {
$sql = "INSERT INTO promotions (PromotionName, PromotionLink, PromotionPhoto, PromotionDateStart, PromotionDateEnd, PromotionContent) VALUES ('$name', '$link', '$cover', '$date_start', '$date_end', '$content')";
$sql_res = mysqli_query($con, $sql) or die(mysqli_error($con));
if ($sql_res) {
print 'success';
} else {
print 'error';
}
}
?>
HTML
<form autocomplete="off" name="promotionForm">
<input type="hidden" value="" ng-model="promotion.PromotionId" />
<div class="form-notification form-notification--{{msg_type}}" ng-if="msg != ''">
{{msg}}
</div>
<div class="form-notification form-notification--error" ng-if="promotionForm.file.$error.maxSize">
{{msg}}
</div>
<ul>
<li class="input">
<label for="promotion_name" class="input__label">
Title
</label>
<input type="text" class="input__field" value="" ng-model="promotion.PromotionName" id="promotion_name" required="required" />
</li>
<li class="input">
<label for="promotion_link" class="input__label">
URL
</label>
<input type="text" class="input__field" value="" ng-model="promotion.PromotionLink" id="promotion_link" required="required" />
</li>
<li class="input">
<label for="promotion_link" class="input__label">
Cover
</label>
<input type="file" ngf-select ng-model="promotion.PromotionPhoto" name="file"
accept="image/*" ngf-max-size="10MB" required id="promotion_link"
class="input__field input__field--upload"
ngf-model-invalid="errorFile"
/>
<img ng-show="promotionForm.file.$valid" ngf-thumbnail="promotion.PromotionPhoto" alt="" />
<button ng-click="promotion.PromotionPhoto = null" ng-show="promotion.PromotionPhoto">
Remove
</button>
</li>
<li class="input">
<label for="date_start" class="input__label">
Date
</label>
<ul class="row">
<li class="small-6 columns">
<datepicker ng-model='promotion.PromotionDateStart' date-format='MMMM d, yyyy' disable-timepicker='true' ng-patter='/\d\d/\d\d/\d\d\d\d/' required></datepicker>
</li>
<li class="small-6 columns">
<datepicker ng-model='promotion.PromotionDateEnd' date-format='MMMM d, yyyy' disable-timepicker='true' ng-patter='/\d\d/\d\d/\d\d\d\d/' required></datepicker>
</li>
</ul>
</li>
<li class="input">
<label for="promotion_content" class="input__label">
Content
</label>
<text-angular ng-model="promotion.PromotionContent"></text-angular>
</li>
</ul>
<button type="submit" class="button--big" ng-click="savePromotion(promotion)"
ng-if="promotion.PromotionId != null"
>
Edit
</button>
<button type="submit" class="button--big" ng-click="savePromotion(promotion)"
ng-if="promotion.PromotionId == null"
>
Add
</button>
</form>
I found the answer I had to set the $folder to $_SERVER['DOCUMENT_ROOT'].'/uploads/'
You cannot POST files in JSON. While you use ng-file-upload, you can use the service Upload for your uploads. It takes care of headers and give you the ability to track your progress. Check https://github.com/danialfarid/ng-file-upload#usage
Related
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.
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'];
It doesn't show any error and it doesn't respond when I click Save button. I've tried the PHP insert code in other page without bootstrap and it works I wonder why it's not working in bootstrap modal.
Here's my HTML code:
<div class="modal-content">
<div class="modal-header">
<h4>Add Topic</h4>
</div>
<div class="modal-body">
<form method="POST" action="index.php" role="form">
<div class="form-group">
<label for="cCategory">Category</label>
<input type="text" class="form-control" id="cCategory" name="category" value="<?php if (!empty($categ)) { echo $categ; } ?>">
</div>
<div class="form-group">
<label for="cTitle">Title</label>
<input type="text" class="form-control" id="cTitle" name="topicTitle" value="<?php if (!empty($topicTitle)) { echo $topicTitle; } ?>">
</div>
<div class="form-group">
<label for="cDesc">Description</label>
<textarea class="form-control custom-control" rows="3" style="resize:none" name="desc" value="<?php if (!empty($desc)) { echo $desc; } ?>"> </textarea>
</div>
<div class="form-group">
<label for="cDesc">Created By</label>
<input type="text" class="form-control" id="cDesc" name="createdby" value="<?php if (!empty($created)) { echo $created; } ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
And this my PHP code:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created)) {
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ', '$topicTitle', '$desc', '$created', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
Your button Submit is out of <form></form> tag. Kepp it inside <form></form> tag to submit the form.
And also check this line:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created))
Should be:
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby']))
You are checking variables before declaring it, use $_POST instead.
Your code should look like this:
<?php
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby'])) {
$desc1 = $_POST['desc'];
$categ1 = $_POST['category'];
$topicTitle1 = $_POST['topicTitle'];
$created1 = $_POST['createdby'];
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ1', '$topicTitle1', '$desc1', '$created1', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
i have create a page to add user and i user "insert into" as my sql code, and i want to make validation to add the user, i mean it show the error if curtain column is empty when add user.. this my code
HTML page
adminadduser.html
<body>
<div>
<!--head-->
<div class= "kepala">
<span class="foundicon-smiley"></span>ADMIN
</div>
<div class= "content">
<div class="menu">
<div class="menu_box_list">
<ul>
<li><a action="php/display_user.php" href="adminMuser.php"><span class="foundicon1-person"></span> Manage user <i class="manageuser"> </i><div class="clear"></div></a></li>
<li><span> </span> vehicle manager <i class="vehicle manager"> </i><div class="clear"></div> </li>
<li><span class= "foundicon-page"></span> report <i class="Report"> </i><div class="clear"></div> </li>
<li><span class= "foundicon-settings"></span> log out<i class="settings"> </i><div class="clear"></div> </li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
<div class="1st_menu">
<form id="form1" name="form1" method="POST" action="php/saveuser2.php">
<div class="table5">
<font style="font-weight:bold">REGISTER USER</font>
<ul>
<p>
Nama: <input type="text" name="name" />*
<?php echo $name;?>
</p>
<p>
Matric No: <input type="text" name="matric" />*
<?php echo $matricErr;?>
</p>
<p>
Password: <input type="text" name="pass" />*
<?php echo $passErr;?>
</p>
<p>
User Category: <select name="cat" id="user_category">
<option>Staff</option>
<option>Student</option>
</select>*
<?php echo $catErr;?>
</p>
<div class="buttn1">
<p>
<input name="add" type="submit" onClick="Adduser()" value="Add" />
</p>
</div>
</ul>
</div>
</form>
</div>
<div class= "Bfooter">
<h4></h4>
</div>
</div>
</body>
and this my PHP file
<?php
$con = mysql_connect("localhost","root","1234");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("vronline", $con);
$nameErr = $matricErr = $passErr = $catErr = "";
$name = $matric = $pass = $cat = "";
$sql="INSERT INTO user_information(user_id, user_password, name, user_category)
VALUES
('$_POST[user_id]','$_POST[user_password]','$_POST[name]','$_POST[user_category]')";
if ($sql["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_id"])) {
$matricErr = "Please insert matric no!";
} else {
$matric = $_POST[user_id];
}
if (empty($_POST["user_password"])) {
$passErr = "Please insert password!";
}else {
$pass = $_POST[user_password];
}
if (empty($_POST["name"])) {
$name = "Please insert name!";
}else {
$name = $_POST[name];
}
if (empty($_POST["user_category"])) {
$catErr = "Please choose category";
} else{
$cat = $_POST[user_category];
}
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header("location:../adminMuser.php");
mysql_close($con)
?>
</body>
</html>
i cant make it work to show the error, which part i make it wrong?
Here is an approach, to validate using PHP
session_start();
$is_valid = false;
$error = array();
if (empty($_POST["user_id"]) || !isset($_POST["user_id"])) {
$error[] = "Please insert matric no!";
}
if (empty($_POST["user_password"]) || !isset($_POST["user_password"])) {
$error[] = "Please insert password!";
}
if (empty($_POST["name"]) || !isset($_POST["name"])) {
$error[] = "Please insert name";
}
if (empty($_POST["user_category"]) || !isset($_POST["user_category"])) {
$error[] = "Please choose category";
}
$is_valid = (count($error) == 0);
if($is_valid){
$con = mysql_connect("localhost","root","1234", "vronline");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$sql=sprintf("INSERT INTO user_information(user_id, user_password, name, user_category)
VALUES('%s','%s','%s','%s')",
$_POST['user_id'],$_POST['user_password'],$_POST['name'],$_POST['user_category']);
mysql_query($sql,$con) or die('Error: ' . mysql_error();
mysql_close($con)
header("location:../adminMuser.php");
}else{
$_SESSION['errors'] = $error;
//you can redirect back to the form to here
}
Then on your forms, you should check if the session is set, and print the errors if any:
session_start();
$errors = $_SESSION['errors'];
foreach($errors as $error){
echo "<p> Error = ".$error."</p>";
}
Please note:
While validation using PHP required, but you should validate on the client side as well.
Good practice wants you to validate using javascript or jquery.
It is a waste to send request to your server when they are not valid/complete.
Nowadays it is even easier with HTML5 validation attributes.
For example:
<input type="text" name="username" required>
This is still not working, so I'm posting whole code here now...
<form id="contact-form" action="fileovi/dodaj_novost.php" method="post">
<fieldset>
<div class="coll-1">
<div class="txt-form">Naslov[hr]</div>
<label class="name">
<input type="text" name="naslov_hr">
<br>
</div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Naslov[en]</div>
<label class="name">
<input type="text" name="naslov_en">
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Naslov[de]</div>
<label class="name">
<input type="text" name="naslov_de">
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-1">
<div class="txt-form">Link slike</div>
<label class="name">
<input type="file" name="image[]" enctype="multipart/form-data"/><br />
<input type="file" name="image[]" enctype="multipart/form-data"/><br />
<br>
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[hr]</center></div>
<label class="name">
<textarea id="tekst" name="tekst_hr"></textarea>
<br>
</div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[en]</center></div>
<label class="name">
<textarea id="tekst1" name="tekst_en"></textarea>
<br>
</div>
<div class="clear"></div>
<div class="coll-big">
<div class="txt-form"><center>Tekst[de]</center></div>
<label class="name">
<textarea id="tekst2" name="tekst_de"></textarea>
<br>
</div>
<div class="clear"></div>
Dodaj!
</form>
And here's my php function that I've created...
function dodaj_novost()
{
global $mysqli;
$mysqli->query("SET NAMES utf8");
$mysqli->query("SET CHARACTER SET utf8");
$mysqli->query("SET COLLATION_CONNECTION='utf8_general_ci'");
//sanitize variables
$naslovhr = $_POST['naslov_hr'];
$naslovhr = $mysqli->real_escape_string($naslovhr);
$nasloven = $_POST['naslov_en'];
$nasloven = $mysqli->real_escape_string($nasloven);
$naslovde = $_POST['naslov_de'];
$naslovde = $mysqli->real_escape_string($naslovde);
$teksthr = $_POST['tekst_hr'];
$teksthr = $mysqli->real_escape_string($teksthr);
$teksten = $_POST['tekst_en'];
$teksten = $mysqli->real_escape_string($teksten);
$tekstde = $_POST['tekst_de'];
$tekstde = $mysqli->real_escape_string($tekstde);
//sanitize variables END
$dan = date('d');
$mjesec = date('M');
$godina = date('Y');
$sql="INSERT INTO novosti (naslovhr, nasloven, naslovde, teksthr, teksten, tekstde, dan, mjesec, godina) VALUES ($naslovhr,$nasloven, $naslovde,$teksthr,$teksten,$tekstde,$dan,$mjesec,$godina)";
$query = $mysqli->query("$sql");
//Add picture!
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$filename = uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path.$filename))
{
$status = $path.$filename;
$link = 'http://'.$domena.'/'.$path.'/'.$filename;
$upit = "INSERT INTO slike_novosti (link, id_posta) VALUES ($link, $id_posta)";
$upit = $mysqli->query("$upit");
if ($upit == 'true'){
echo 'Successfull!';
} else {
echo 'Not sucessfull!';
}
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else{
//image is not uploaded!
$status = ' ';
}
echo '<br>'.$status.'<br>';
}
} else {
echo 'Nema slike!';
}
//Add picture END!!
}
And for some reason this code is still not working, If someone can point me in right direction on how to solve this problem.. I would be soo happy! :) Cheers.
At first:
$sql1 = "INSERT INTO slike_novosti (slika, link_slike) VALUES ('$link_slike','$slika')";
check order of your variables? I think, it must be:
$sql1 = "INSERT INTO slike_novosti (slika, link_slike) VALUES ('$slika','$link_slike')";
at second: Use PDO component, you have a very bad code and SQL Injection.
Remove the single qoutes from your $variables. For PHP '$var' is a variable with the value of $var. If you want them qouted, use "$var". See variables
So this wil work
$sql="INSERT INTO novosti (naslovhr, nasloven, naslovde, teksthr, teksten, tekstde,
link_slike, dan, mjesec, godina) VALUES
$naslovhr,$nasloven,$naslovde,$teksthr,
$teksten,$tekstde,$link_slike,$dan,$mjesec,$godina)";