Image isn't updating in mysql database - php

So i have the following scripts:
<?php
//Posts variables
$post_id = 0;
$isEditingPost = false;
$published = 0;
$title = "";
$post_slug = "";
$body = "";
$featured_image = "";
$post_topic = "";
//Get all posts
function getAllPosts(){
global $conn;
if ($_SESSION['user']['role'] == "Admin") {
$sql = "SELECT * FROM posts";
}elseif($_SESSION['user']['role'] == "Author"){
$user_id = $_SESSION['user']['id'];
$sql = "SELECT * FROM posts WHERE user_id=$user_id";
}
$result = mysqli_query($conn,$sql);
$posts = mysqli_fetch_all($result,MYSQLI_ASSOC);
$final_posts = array();
foreach($posts as $post){
$post['author'] = getPostAuthorById($post['user_id']);
array_push($final_posts,$post);
}
return $final_posts;
}
function getPostAuthorById($user_id){
global $conn;
$sql = "SELECT username FROM users WHERE id=$user_id";
$result = mysqli_query($conn,$sql);
if($result){
return mysqli_fetch_assoc($result)['username'];
}else{
return null;
}
}
/* - - - - - - - - - -
- Post actions
- - - - - - - - - - -*/
// if user clicks the create post button
if (isset($_POST['create_post'])) { createPost($_POST); }
// if user clicks the Edit post button
if (isset($_GET['edit-post'])) {
$isEditingPost = true;
$post_id = $_GET['edit-post'];
editPost($post_id);
}
// if user clicks the update post button
if (isset($_POST['update_post'])) {
updatePost($_POST);
}
// if user clicks the Delete post button
if (isset($_GET['delete-post'])) {
$post_id = $_GET['delete-post'];
deletePost($post_id);
}
/* - - - - - - - - - -
- Post functions
- - - - - - - - - - -*/
function createPost($request_values)
{
global $conn,$user_id, $errors, $title, $featured_image, $topic_id, $body, $published;
$user_id = $_SESSION['user']['id'];
$title = esc($request_values['title']);
$body = htmlentities(esc($request_values['body']));
if (isset($request_values['topic_id'])) {
$topic_id = esc($request_values['topic_id']);
}
if (isset($request_values['publish'])) {
$published = esc($request_values['publish']);
}
// create slug: if title is "The Storm Is Over", return "the-storm-is-over" as slug
$post_slug = makeSlug($title);
// validate form
if (empty($title)) { array_push($errors, "Post title is required"); }
if (empty($body)) { array_push($errors, "Post body is required"); }
if (empty($topic_id)) { array_push($errors, "Post topic is required"); }
// Get image name
$featured_image = $_FILES['featured_image']['name'];
if (empty($featured_image)) { array_push($errors, "Featured image is required"); }
// image file directory
$target = "../static/images/" . basename($featured_image);
if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $target)) {
array_push($errors, "Failed to upload image. Please check file settings for your server");
}
// Ensure that no post is saved twice.
$post_check_query = "SELECT * FROM posts WHERE slug='$post_slug' LIMIT 1";
$result = mysqli_query($conn, $post_check_query);
if (mysqli_num_rows($result) > 0) { // if post exists
array_push($errors, "A post already exists with that title.");
}
// create post if there are no errors in the form
if (count($errors) == 0) {
$query = "INSERT INTO posts (user_id, title, slug, image, body, published, created_at, updated_at) VALUES($user_id, '$title', '$post_slug', '$featured_image', '$body', $published, now(), now())";
if(mysqli_query($conn, $query)){ // if post created successfully
$inserted_post_id = mysqli_insert_id($conn);
// create relationship between post and topic
$sql = "INSERT INTO post_topic (post_id, topic_id) VALUES($inserted_post_id, $topic_id)";
mysqli_query($conn, $sql);
$_SESSION['message'] = "Post created successfully";
header('location: posts.php');
exit(0);
}
}
}
/* * * * * * * * * * * * * * * * * * * * *
* - Takes post id as parameter
* - Fetches the post from database
* - sets post fields on form for editing
* * * * * * * * * * * * * * * * * * * * * */
function editPost($role_id)
{
global $conn, $title, $post_slug, $body, $published, $isEditingPost, $post_id;
$sql = "SELECT * FROM posts WHERE id=$role_id LIMIT 1";
$result = mysqli_query($conn, $sql);
$post = mysqli_fetch_assoc($result);
// set form values on the form to be updated
$title = $post['title'];
$body = $post['body'];
$published = $post['published'];
}
function updatePost($request_values)
{
global $conn, $errors, $post_id, $title, $featured_image, $topic_id, $body, $published;
$title = esc($request_values['title']);
$body = esc($request_values['body']);
$post_id = esc($request_values['post_id']);
if (isset($request_values['topic_id'])) {
$topic_id = esc($request_values['topic_id']);
}
// create slug: if title is "The Storm Is Over", return "the-storm-is-over" as slug
$post_slug = makeSlug($title);
if (empty($title)) { array_push($errors, "Post title is required"); }
if (empty($body)) { array_push($errors, "Post body is required"); }
// if new featured image has been provided
if (isset($_POST['featured_image'])) {
// Get image name
$featured_image = $_FILES['featured_image']['name'];
// image file directory
$target = "../static/images/" . basename($featured_image);
if (!move_uploaded_file($_FILES['featured_image']['tmp_name'], $target)) {
array_push($errors, "Failed to upload image. Please check file settings for your server");
}
}
// register topic if there are no errors in the form
if (count($errors) == 0) {
$query = "UPDATE posts SET title='$title', slug='$post_slug', views=0, image='$featured_image', body='$body', published=$published, updated_at=now() WHERE id=$post_id";
// attach topic to post on post_topic table
if(mysqli_query($conn, $query)){ // if post created successfully
if (isset($topic_id)) {
$inserted_post_id = mysqli_insert_id($conn);
// create relationship between post and topic
$sql = "INSERT INTO post_topic (post_id, topic_id) VALUES($inserted_post_id, $topic_id)";
mysqli_query($conn, $sql);
$_SESSION['message'] = "Post created successfully";
header('location: posts.php');
exit(0);
}
}
$_SESSION['message'] = "Post updated successfully";
header('location: posts.php');
exit(0);
}
}
// delete blog post
function deletePost($post_id)
{
global $conn;
$sql = "DELETE FROM posts WHERE id=$post_id";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = "Post successfully deleted";
header("location: posts.php");
exit(0);
}
}
// if user clicks the publish post button
if (isset($_GET['publish']) || isset($_GET['unpublish'])) {
$message = "";
if (isset($_GET['publish'])) {
$message = "Post published successfully";
$post_id = $_GET['publish'];
} else if (isset($_GET['unpublish'])) {
$message = "Post successfully unpublished";
$post_id = $_GET['unpublish'];
}
togglePublishPost($post_id, $message);
}
// delete blog post
function togglePublishPost($post_id, $message)
{
global $conn;
$sql = "UPDATE posts SET published=!published WHERE id=$post_id";
if (mysqli_query($conn, $sql)) {
$_SESSION['message'] = $message;
header("location: posts.php");
exit(0);
}
}
?>
Everything works fine , it updates the topic , the post body,title,published state but the image isn't updating , even tho when i create a new post the image is being inserted in the database , when i try to update , the image column in database remains empty.
Here is the create_post.php
<?php include('../config.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/admin_functions.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/post_functions.php'); ?>
<?php include(ROOT_PATH . '/admin/includes/header.php'); ?>
<!-- Get all topics -->
<?php $topics = getAllTopics(); ?>
<title>Admin | Create Post</title>
</head>
<body>
<!-- admin navbar -->
<?php include(ROOT_PATH . '/admin/includes/navbar.php') ?>
<div class="container content">
<!-- Left side menu -->
<?php include(ROOT_PATH . '/admin/includes/menu.php') ?>
<!-- Middle form - to create and edit -->
<div class="action create-post-div">
<h1 class="page-title">Create/Edit Post</h1>
<form method="post" enctype="multipart/form-data" action="<?php echo BASE_URL . 'admin/create_post.php'?>">
<?php include(ROOT_PATH . '/includes/errors.php') ?>
<?php if($isEditingPost == true):?>
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<?php endif ?>
<input type="text" name="title" value="<?php echo $title; ?>" placeholder="Title">
<label style="float: left; margin: 5px auto 5px;">Featured image</label>
<input type="file" name="featured_image">
<textarea name="body" id="body" cols="30" rows="10"><?php echo $body; ?></textarea>
<select name="topic_id">
<option value="" selected disabled>Choose topic</option>
<?php foreach ($topics as $topic): ?>
<option value="<?php echo $topic['id']; ?>">
<?php echo $topic['name']; ?>
</option>
<?php endforeach ?>
</select>
<?php if($_SESSION['user']['role'] == 'Admin'):?>
<?php if($published == true):?>
<label for="publish">
Publish
<input type="checkbox" value='1' name="publish" checked="checked">
</label>
<?php else:?>
<label for="publish">
Publish
<input type="checkbox" value="1" name="publish">
</label>
<?php endif ?>
<?php endif ?>
<?php if ($isEditingPost === true): ?>
<button type="submit" class="btn" name="update_post">UPDATE</button>
<?php else: ?>
<button type="submit" class="btn" name="create_post">Save Post</button>
<?php endif ?>
</form>
</div>
</body>
</html>
<script>
CKEDITOR.replace('body');
</script>

I think the problem might be with your if statement in updatePost function if (isset($_POST['featured_image'])) {. Change this like in createPost function
$featured_image = $_FILES['featured_image']['name'];
if (empty($featured_image)) {
...
}
Check also https://www.php.net/manual/en/features.file-upload.post-method.php for more information about checking uploaded files.

Related

How to delete image from two different database and folder with PHPMYSQL

// i have two tables like,projects and projectfiles.
projects fields are:
id,name,alice,catg,img;
//insertin the image in the folder 'upload'
projectfiles fields are :
id,name,img
//inserting the image in the folder 'image'
so,how delete the data from projects and projectfiles even from directory.
<?php
include('dbconfig1.php');
if(!$db)
{
die(mysqli_error());
}
$sql = "select * from projects";
$result = $db->query($sql);
if(isset($_GET['id']))
{
$selectSql = "select * from projects where id = ".$_GET['id'];
$rsSelect = mysqli_query($db,$selectSql);
$getRow = mysqli_fetch_assoc($rsSelect);
$getIamgeName = $getRow['img'];
$createDeletePath = "upload/".$getIamgeName;
if(unlink($createDeletePath))
{
$deleteSql = "delete from projects where id = ".$getRow['id'];
$rsDelete = mysqli_query($db, $deleteSql);
if($rsDelete)
{
header('location:projects.php?success=true');
exit();
}
}
else
{
$errorMsg = "Unable to delete Image";
}
}
?>
?>
<?php
if(isset($_GET['success']) && $_GET['success'] == 'true')
{
?>
<div class="alert alert-success">
<?php
echo "Images has been deleted sucessfully";
?>
</div>
<?php
}
?>

Form data doesn't get inserted into database

When I submit my data from the form, it won't insert the form data in to the database. The connection to the databse is set and when I check the connection it always responds that it is connected. The database is correctly setup with all values: id, name, date, emailadress and text. The username, password and database name are correct.
The syntax should be correct. I work with mysql workbench.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<title></title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="input.css">
<header>
<h1></h1>
</header>
<nav>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</nav>
<main>
<form method="post" action="input.php">
<label>Name</label>
<input placeholder="Name" name="name" type="text"><br>
<label>Mailadress</label>
<input placeholder="Emailadress" name="eMail" type="email"><br>
<label>Your comment</label>
<textarea name="comment" placeholder="Text" name="comment"cols="60" rows="15"></textarea>
<input value="Send" type="submit">
</form>
</main>
</body>
</html>
PHP code:
<?php
if($con->connect_error)
{
die("No connection" .$con-> connect_error);
}
echo "Connected";
$guestbook = new GuestbookAccess();
if (isset($_POST['submit'])){
$name = $_POST['name']; $eMail = $_POST['eMail']; $comment = $_POST['comment'];
}
class GuestbookAccess
{
private $db;
/**
* Opens the database.
*/
public function __construct()
{
$username = "tipuser";
$password = "TIP2018_WebEngineering";
$database = "tip";
// Open the database
$this->db = mysqli_connect("localhost", $username, $password);
if ($this->db == false) {
die("Unable to connect to database");
}
// Select database
mysqli_select_db($this->db, $database);
}
/**
* Evaluates current time and adds a new guestbook entry with given name,
* e-Mail and comment.
* #param String $name User name
* #param String $eMail User e-mail address
* #param String $comment The entry text
* #return On success: Integer Index generated by the database for the entry
* On failure: Boolean false
*/
public function addEntry($name, $eMail, $comment)
{
// For security: suppress SQL injection
$name = mysqli_real_escape_string($this->db, $name);
$eMail = mysqli_real_escape_string($this->db, $eMail);
$comment = mysqli_real_escape_string($this->db, $comment);
// Add entry to the database
$result = mysqli_query($this->db, "INSERT INTO guestbook (name, email, comment) VALUES ('$name', '$eMail', '$comment')");
if ($result)
{
$result = mysqli_insert_id($this->db);
}
return $result;
}
/**
* Return in an table (two-dimensional array) all entries of the guest book.
* Each row of the table represents one entry in the guest book.
* #return table[...]["Index"] --> Integer: Index of the entry (for deleting)
* table[...]["Name"] --> String: name of the user
* table[...]["eMail"] --> String: e-Mail of the user
* table[...]["Comment"] --> String: The guest book entry (as text)
* table[...]["Date"] --> String: Date and time of the entry
*/
public function getEntries()
{
// Create query
$result = mysqli_query($this->db, "SELECT * FROM guestbook");
$table = false;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$table[$i]["Index"] = $row["indes"];
$table[$i]["Date"] = $row["date"];
$table[$i]["Name"] = $row["name"];
$table[$i]["eMail"] = $row["email"];
$table[$i]["Comment"] = $row["comment"];
$i++;
}
mysqli_free_result($result);
return $table;
// Get all entries in the guestbook
$table = $guestbook->getEntries();
if ($table) { // Check if there are enrtries
echo "\nThe guestbook contains:\n";
foreach ($table as $row) {
// Output each element
$index = $row["Index"];
$name = $row["Name"];
$date = $row["Date"];
$email = $row["eMail"];
$comment = $row["Comment"];
echo "Index: $index, ";
echo "Name: $name, ";
echo "Date: $date, ";
echo "eMail: $email, ";
echo "Comment: $comment\n";
}
}
else {
echo "\nGuest book is empty\n";
}
/**
* Closes the database.
*/
function __destruct()
{
mysqli_close($this->db);
}
}
}
?>
You should add name as submit for submit type in your input tage so to make the isset($_POST['submit']) work in php
<input value="Send" type="submit" name="submit">

How to INSERT an array of uploaded filenames into a table and later display them?

I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}

direct user to another page using php

what is the best way to direct the user to another page given the IF statement is true. i want the page to direct the user to another page using PHP, when the IF statement is run, i tired this but it doesn't work??
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
Below is the full source code for the page.
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p><span>Room No: </span><?php $room = $_SESSION['g'];
echo $room; // echo's room ?>
</p>
<p><span>Computer No: </span><?php
$select3 = $_POST['bike'];
echo $select3;
?>
</p>
<p><span>Date: </span><?php $date = $_POST['datepicker'];
echo $date; // echo's date
?>
</p>
<p><span>Start Session: </span>
<?php
if(isset($_POST['select1'])) {
$select1 = $_POST['select1'];
echo $select1;
echo "";
}
else{
echo "not set";
}
?>
</p>
<p><span>End Session: </span>
<?php
if(isset($_POST['select2'])) {
$select2 = $_POST['select2'];
echo $select2;
echo "";
}
else{
echo "not set";
}
?>
</p>
</div>
<div id="success">
<?php
$servername = "localhost";
$name = "root";
$password = "root";
$dbname = "my computer";
// Create connection
$conn = mysqli_connect($servername, $name, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `booked` WHERE
`date` = '{$date}' AND
`computer_id` = '{$select3}' AND
`start_time` = '{$select1}' AND
`end_time` = '{$select2}' AND
`room` = '{$room}'
";
$result = mysqli_query($conn, $query);
if ( mysqli_num_rows ( $result ) > 0 )
{
header('Location: exist.php');
die();
}
else
{
$sql = "INSERT INTO booked (date, computer_id, name, start_time, end_time, room)
VALUES ('$date', '$select3', '$username', '$select1', '$select2', '$room')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
</div>
<form action="user.php">
<input type="submit" value="book another" class="bookanother" />
</form>
</div>
</body>
</html>
If the header is sent already, for example you have echo something before then the header will not work, because the header cannot be set after data flow has started, (since php would have already set the default headers for you). So, in this case if that is so, I do the redirect using javascript.
PHP Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
WORK-AROUND: This is a function I have written long back and include in controllers.
/**
* Safely redirect by first trying header method but if headers were
* already sent then use a <script> javascript method to redirect
*
* #param string
* #return null
*/
public function safeRedirect($new_url) {
if (!headers_sent()) {
header("Location: $new_url");
} else {
echo "<script>window.location.href = '$new_url';</script>";
}
exit();
}
add the function and simply call:
safeRedirect('index.php');

Data not being saved in my database

I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}

Categories