unable to create new record in database - php

I am trying to create a script which uploads an electronic signature to the customers record, I am getting the ID but am not able to create the entry on the database and there is no error message being produced in the logs, simply refreshes the page.
Here is what I have so far.
Code
<?php
include '../../main.php';
check_loggedin($pdo);
$msg = null;
$date = new DateTime();
$totay_date = $date->format('Y-m-d\TH:i:s');
$folderPath = "upload/";
$image_parts = explode(";base64,", $_POST['signature']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . $name . "_" . uniqid() . '.' . $image_type;
file_put_contents($file, $image_base64);
if (isset($_GET['id'])) {
$stmt = $pdo->prepare('SELECT * FROM contacts WHERE id = ?');
$stmt->execute([$_GET['id']]);
$contact = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare('SELECT id,username FROM accounts');
$stmt->execute();
$all_account_info = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_POST['$name']) == null || isset($_POST['$file'])){
$msg = '';
}else{
$id = isset($_POST['id']) && !empty($_POST['id']) && $_POST['id'] != 'auto' ? $_POST['id'] : auto;
$stmt = $pdo->prepare('INSERT INTO esign VALUES (?, ?, ?, ?)');
$result = $stmt->execute([$id, $_GET['id'], $_POST['name'], $_POST['$file']]);
$msg = "Signature has been recorded.";
}
if (!$contact) {
exit('Help');
}
} else {
exit('No ID specified!');
}
?>
Form
<form action="add-sig.php?id=<?=$contact['id']?>" method="post">
<h1>Signature Pad</h1>
<div class="col-md-12">
<label class="form-label" for="name">Name</label> <input class="form-control" id="name" name="name" required="" type="text">
</div>
<div class="col-md-12">
<label class="" for="">Signature:</label><br>
<div id="sig"></div><br>
<textarea id="signature64" name="signature" style="display: none"></textarea>
<div class="col-12">
<button class="btn btn-sm btn-warning" id="clear">⌫Clear Signature</button>
</div>
</div><br>
<button class="btn btn-success" name="submit" type="submit">Submit</button>
</form>
</div>
Database
`id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`signature_img` varchar(255) NOT NULL
It loads the ID when clicking add signature and the address link looks something like add-sig.php?id=29 when accessing the page from the clients record page.
When I am in the clients record, I would like to be able to view the signature on their record.
The form converts the signature into an image file.

Related

How can I create a post then upload data enteries to a separate table with data entries that include the id of the previously created post at once?

The main idea is to create a post along with multiple pictures that associate with the post but the entries for these posts are on a separate table.
I tried making it into one table to do both stuff, but I couldn't find a way to include more than one location for a file in on column.
HTML
<form action="includes/post.inc.php" method="POST" class="col s12" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="title" name="title" type="text" class="validate" required>
<label for="title">Title</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="body" name="body" class="materialize-textarea" required></textarea>
<label for="body">Body</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select name="category" required>
<option value="" disabled selected>Choose a Category</option>
<option value="programming">Programming</option>
</select>
<label>Categories</label>
</div>
</div>
<div class="row">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" name="file[]" multiple>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more files">
</div>
</div>
</div>
<button class="btn waves-effect waves-light right" type="submit" name="post-submit">Post</button>
</form>
PHP
function reArrayFiles($file_post){
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for($i = 0; $i<$file_count; $i++){
foreach($file_keys as $key){
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
global $idPost;
if (isset($_POST['post-submit'])) {
session_start();
$category = $_POST['category'];
$title = $_POST['title'];
$body = $_POST['body'];
$category = $_POST['category'];
$id = $_SESSION['userId'];
$uid = $_SESSION['userUid'];
$status;
if(empty($title) || empty($body)){
header("Location: ../index.php?error=emptyfields&title=".$title."&mail=".$body);
exit();
}else{
$sql = "INSERT INTO posts (titlePosts, contentPosts, catPosts, timePosts, statusPosts, uidUsers, idUsers) VALUES (?, ?, ?, NOW(), ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}else{
mysqli_stmt_bind_param($stmt, "ssssss", $title, $body, $category, $status, $uid, $id);
mysqli_stmt_execute($stmt);
}
}
$file_array = reArrayFiles($_FILES['file']);
$result = mysqli_query($conn, "SELECT idPosts FROM posts WHERE titlePosts={$title} AND bodyPosts={$body} AND idUsers={$id}");
while($row = mysqli_fetch_assoc($result)){
$idPost = $row['idPosts'];
}
for($i = 0; $i<count($file_array); $i++){
$fileName = $file_array[$i]['name'];
$fileTempName = $file_array[$i]['tmp_name'];
$fileSize = $file_array[$i]['size'];
$fileError = $file_array[$i]['error'];
$fileType = $file_array[$i]['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allow = array('jpg','jpeg','png','JPG','JPEG','PNG');
if(in_array($fileActualExt, $allow)){
if($fileError === 0){
if($fileSize < 100000){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = '../uploads/'.$fileNameNew;
move_uploaded_file($fileTempName,$fileDestination);
mysqli_query($conn, "INSERT INTO post_files (locationFiles, idPosts) VALUES ({$fileNameNew},{$idPost})");
}else{
echo "<script>alert('Your file is too big!');</script>";
}
}else{
echo "<script>alert('There was an error uploading your file!');</script>";
}
}else{
echo "<script>alert('You cannot upload a file of this type!');</script>";
}
}
if(!isset($category)){
header("Location: ../index.php?post=success");
exit();
}else{
header("Location: ../index.php?cat={$category}&post=success");
exit();
}
}else{
header("Location: ../index.php");
exit();
}
post_files Table
|---------------------|------------------|------------------|
| idFiles | locationFiles | idPosts |
|---------------------|------------------|------------------|
| int | varchar(255) | int |
|---------------------|------------------|------------------|
idPosts is linked with the posts table
I expected the program to create a post along with the data from the fields, and for the files to be uploaded to htdocs and the file to be inserted into the data base. However, everything goes well except for entering data into the post_files Table.

How can I save an Image and a text separately in php mysqli

Hi i'm having a hard time in saving a text with an input tag and an image using one button.
here is my form:
<form method = "POST" action = "image_upload_featured.php" enctype = "multipart/form-data">
<label>Drag or click for image</label>
<div id="uploader" onclick="$('#photo').click()">
<img src=""/>
</div>
<input type="file" name="image" id="photo"/>
<div id = "file_name"></div>
<button class = "btn btn-primary" name = "save"><span class = "glyphicon glyphicon-download"></span> Save Image</button>
<input class = "w3-input w3-border" type = "text" name= "fullname" placeholder = "Fullname" style="margin-bottom: 15px;" required>
<input class = "w3-input w3-border" type = "text" name= "lname" placeholder = "Lastname" style="margin-bottom: 15px;" required>
</form>
I have a php file where it can saved the image
<?php
include('db/database_configuration.php');
if(ISSET($_POST['save'])){
if($_FILES['image']['name'] == ""){
echo '<script>alert("Please Select an Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES["image"]["tmp_name"], "featured_image/". $_FILES["image"]["name"]);
$location = $_FILES["image"]["name"];
$stmt = $conn->prepare("INSERT INTO `tblfeatured` (image1) VALUES(?)") or die(mysqli_error());
$stmt->bind_param("s", $location);
if($stmt->execute()){
$stmt->close();
$conn->close();
echo '<script>alert("Successfully Upload Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
echo '<script>alert("Error")</script>';
}
}
}
?>
But this is only for the image, I know also how to save a text using input tag but without image.
I would like to combine both. Can anyone please help me?
I assume that you have fullname and lname fields (columns) are in your Database table along with image1.
Your Html
<form method = "POST" action = "image_upload_featured.php" enctype = "multipart/form-data">
<label>Drag or click for image</label>
<div id="uploader" onclick="$('#photo').click()">
<img src=""/>
</div>
<input type="file" name="image" id="photo"/>
<div id = "file_name"></div>
<input class = "w3-input w3-border" type = "text" name= "fullname" placeholder = "Fullname" style="margin-bottom: 15px;" required >
<input class = "w3-input w3-border" type = "text" name= "lname" placeholder = "Lastname" style="margin-bottom: 15px;" required >
<button type="submit" class = "btn btn-primary" name = "save"><span class = "glyphicon glyphicon-download"></span> Save Image</button>
</form>
PHP
<?php
include('db/database_configuration.php');
if(ISSET($_POST['save'])){
if($_FILES['image']['name'] == ""){
echo '<script>alert("Please Select an Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES["image"]["tmp_name"], "featured_image/". $_FILES["image"]["name"]);
$location = $_FILES["image"]["name"];
//edit.....get input values
$fullname = $_POST['fullname'];
$lname = $_POST['lname'];
$stmt = $conn->prepare("INSERT INTO `tblfeatured` (image1,fullname,lname) VALUES(?,?,?)") or die(mysqli_error($conn));
$stmt->bind_param("sss", $location,$fullname,$lname); //bind to param
//........................................
if($stmt->execute()){
$stmt->close();
$conn->close();
echo '<script>alert("Successfully Upload Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
echo '<script>alert("Error")</script>';
}
}
}
?>
NOTE: This must work except exceptional syntax error. (If your code was previously working then this must also work)
Your DB Table must be something like this
| id | image1 | fullname | lname |

The Uploaded Image doesn't Save on the database

I'am having a button to upload a image and Every time I upload an Image the images doesn't saves on the database and there is no error given,
Here is my Code:
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
<?php
if(isset($_POST['files']))
{
$userid = $row['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
if($sql){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}
?>
</td>
I Figured it out my self,
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<input type="hidden" name="stall_id" value="<?php echo $value['stall_id']?>">
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
<?php
if(isset($_POST['files']))
{
$userid = $_POST['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
if($sql2){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}
?>
</td>
Please Bind Parameter After Prepare statement. check docs- http://php.net/manual/en/mysqli.prepare.php
in if condition put $update(return value of execution) instead of sql
close </form> tag.
check all variables having data. check with var_dump(), print_r() or echo() methods.
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
</form>
</td>
<?php
if(isset($_POST['files']))
{
$userid = $row['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
if( $sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?"))
{
$sql2->bindParam(1, $location, PDO::PARAM_STR);
$sql2->bindParam(2, $userid, PDO::PARAM_INT);
$update=$sql2->execute();
if($update){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}else{
echo 'sql prepare failed';
}
}
?>
change from
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
to
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->bindParam(1, $location, PDO::PARAM_STR);
$sql2->bindParam(2, $userid, PDO::PARAM_INT);
$sql2->execute();

Insert data into separate tables related by foreign keys

I have a database with two tables:
posts: id(primary key, autoincrement), title_bg, title_en, body_bg, body_en, status, created, updated
postimage: id(primary key, auto increment), post_id, name
When I'm not using a foreign key, the form with multiple elements is working fine. It fills all the details for the post into the posts table and the multiple images are uploading into the postimage table, but they're not related, so the post_id field shows 0 value.
When I set the foreign key on phpMyAdmin with this query:
ALTER TABLE `postimage` ADD FOREIGN KEY ( `post_id` ) REFERENCES `database_name`.`posts` ( `id` ) ON DELETE RESTRICT ON UPDATE RESTRICT ;
and when I create a new post, all the values are saved into the posts table, except the images into the second table. The postimage table is empty.
Here's my code:
<?php
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(name) ";
$query .= "VALUES('$name')";
$upload_images = mysqli_query($connection, $query);
}
}
$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
header("Location: posts.php");
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title_bg">Post title BG</label>
<input type="text" name="title_bg">
</div>
<div class="form-item">
<label for="title_en">Post title EN</label>
<input type="text" name="title_en">
</div>
<div class="form-item">
<label for="body_bg">Post body BG</label>
<textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="body_en">Post body EN</label>
<textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="published">published</option>
<option value="draft">draft</option>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Submit">
</div>
</form>
I've also created a two new tables as a test:
teachers: id, name, content_area, room
students: id, name, homeroom_teacher
When I set the foreign key on students field homeroom_teacher and insert the data manually from phpMyAdmin, they become related and the id on students table becomes clickable and it shows the relation with the teacher. So manually it's working great and the problem is in the PHP code.
What query do I need to change, so to make the connection with post id from the posts table and post_id from the postimage table?
I know that I'm missing the id from the $_FILES query, but I don't know how to get it, because it's already automatic auto increment field.
Thanks.
<?php
if(isset($_POST['status'])) {
$status = $_POST['status'];
}
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
$connection = new mysqli("localhost", "USER_XY", "PASSWD","DB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die ("<h1>can't use Database !</h1>");
exit();
}
/* change character set to utf8 */
if (!$connection->set_charset("utf8")) {
printf("Error while loading 'character set utf8' : %s\n", $connection->error);
die();
}
/**
* First save the Post
**/
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$result=$connection->query($query);
// verify results
if(!$result) {
$message = "ERROR SAVING POST : ".$connection->error . "\n";
$connection->close();
echo ($message);
return false;
}
/**
* get the last inster id of the Post
**/
$post_id = $connection->insert_id;
echo "Post id=".$post_id ."<br>\n";
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, './uploads/' . $name);
/**
* now insert the image with the post_id
**/
$query = "INSERT INTO `postimage` (`id`, `post_id`, `name`) ";
$query .= "VALUES (NULL, '".$post_id."', '".$name."');";
$result=$connection->query($query);
// verify results
if(!$result) {
$message = "ERROR INSERT IMAGE : ".$connection->error . "\n";
$connection->close();
echo ($message);
return false;
}
}
}
header("Location: upload_posts.php");
}
?>
<form action="upload_posts.php" method="post" enctype="multipart/form-data">
<div class="form-item">
<label for="title_bg">Post title BG</label>
<input type="text" name="title_bg">
</div>
<div class="form-item">
<label for="title_en">Post title EN</label>
<input type="text" name="title_en">
</div>
<div class="form-item">
<label for="body_bg">Post body BG</label>
<textarea id="editor" name="body_bg" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="body_en">Post body EN</label>
<textarea id="editor2" name="body_en" rows="10" cols="30"></textarea>
</div>
<div class="form-item">
<label for="image">Image</label>
<input type="file" name="image[]" multiple>
</div>
<div class="form-item">
<label for="status">Post status</label>
<select name="status">
<option value="published">published</option>
<option value="draft">draft</option>
</select>
</div>
<div class="form-item">
<input type="submit" class="form-submit" name="submit" value="Submit">
</div>
</form>
autoincrement id's can be obtained with $mysqli->insert_id;
see for furter details : https://php.net/manual/mysqli.insert-id.php
:-)
I think it's problem because you add data first in postimage and after that add data in post so post_id is not found in postimage try to change postion of query like: `$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(name) ";
$query .= "VALUES('$name')";
$upload_images = mysqli_query($connection, $query);
}
}
use this: $last_id = mysqli_insert_id($conn); to get the last inserted id.
<?php
if(isset($_POST['submit'])) {
$title_bg = $_POST['title_bg'];
$title_en = $_POST['title_en'];
$body_bg = $_POST['body_bg'];
$body_en = $_POST['body_en'];
$status = $_POST['status'];
$query = "INSERT INTO posts(title_bg, title_en, body_bg, body_en, status, created) ";
$query .= "VALUES('$title_bg', '$title_en', '$body_bg', '$body_en', '$status', now())";
$create_post = mysqli_query($connection, $query);
$last_id = mysqli_insert_id($connection);
if(isset($_FILES['image'])) {
foreach($_FILES['image']['name'] as $key => $name) {
$image_tmp = $_FILES['image']['tmp_name'][$key];
move_uploaded_file($image_tmp, '../uploads/' . $name);
$query = "INSERT INTO postimage(post_id, name) ";
$query .= "VALUES('$last_id', '$name')";
$upload_images = mysqli_query($connection, $query);
}
}
header("Location: posts.php");
}
?>

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.

Categories