div class in php echo - php

I would like to put a background on my guestbook messages and the font color should be white. How can I change the echo:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(!isset($_SESSION))
{
session_start();
}
include ('dbconnection.php');
include 'checklogin.php';
include 'head_nav.html';
?>
<!DOCTYPE html5>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="descripion" content="Die offizielle Seite von BestFoto">
<meta name="keywords" content="Foto, Fotografie, BestFoto, Business, Architektur, Fashion, Natur">
<meta name="copyright" content="Copyright 2017 by Sharam Etemadi">
<meta name="author" content="Sharam Etemadi">
<title>BestFoto – Kontakt</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="main-content-container">
<div class="content-header-container">
<header class="content-header">
<h1>Kontakt</h1>
</header>
</div><!-- content-header -->
<div class="content-container">
<section class="content">
<p>
Hier könnt ihr Verbesserungsvorschläge oder sonstiges einreichen.
</p>
</section>
</div><!-- content-container -->
</div><!-- main-content-container -->
<form action="" method="post">
<p>Betreff:</p>
<input type="text" name="betreff" placeholder="Betreff?"><br>
<p>Nachricht:</p>
<textarea name="nachricht" placeholder="Ihre Nachricht!"></textarea><br>
<input type="submit" name="submit" value="Absenden!"><br>
</form>
<?php
array_walk ( $_POST, 'cleanmsg' );
array_walk ( $_GET, 'cleanmsg' );
array_walk ( $_REQUEST, 'cleanmsg' );
function cleanmsg(&$value, $key)
{
// keine HTML-Tags erlaubt, außer p und br
$value = strip_tags($value, '<p><br /><b><strong>');
// HTML-Tags maskieren
$value = htmlspecialchars($value, ENT_QUOTES);
// Leerzeichen am Anfang und Ende beseitigen
$value = trim($value);
}
if(isset($_POST['submit'])):
$betreff = $_POST['betreff'];
$nachricht = $_POST['nachricht'];
$userid = $_SESSION['user'];
$StrSQL = "INSERT INTO kontakt (userid_fk,betreff,nachricht,datum)
VALUES (?,?,?,NOW())";
$absenden = $db->prepare($StrSQL);
$absenden->bind_param('iss', $userid, $betreff, $nachricht);
$absenden->execute();
endif;
$StrSQL2 = "SELECT users.benutzername as bn,
kontakt.betreff, kontakt.nachricht, kontakt.datum
FROM users RIGHT JOIN kontakt
ON users.userid = kontakt.userid_fk ORDER BY datum DESC";
$abfrage = $db->query($StrSQL2);
echo 'Es wurden '.$abfrage->num_rows.' Nachrichten gefunden!<br>';
?>
<?php while ($ausgabe = $abfrage->fetch_object()) { ?>
<div class="test">
<b>user:</b><?=!is_null($ausgabe->bn) ? htmlspecialchars($ausgabe->bn) : 'Guest'?>
<br>
<b>Date:</b><?=$ausgabe->date?>
<br>
<b>subject:</b><?=htmlspecialchars($ausgabe->subject)?>
<br>
<b>message:</b>
<br>
<?=htmlspecialchars($ausgabe->message)?>
<br>
<hr>
</div>
<? } ?>
<?php
// rest of the PHP code
$result_total = mysqli_query($db,'SELECT COUNT(*) as `total` FROM kontakt');
$row_total = mysqli_fetch_assoc($result_total);
$gesamte_anzahl = $row_total['total'];
$ergebnisse_pro_seite = 10;
$gesamt_seiten = ceil($gesamte_anzahl/$ergebnisse_pro_seite);
if (empty($_GET['seite_nr'])) {
$seite = 1;
} else {
$seite = $_GET['seite_nr'];
if ($seite > $gesamt_seiten) {
$seite = 1;
}
}
$limit = ($seite*$ergebnisse_pro_seite)-$ergebnisse_pro_seite;
$result = mysqli_query($db,'SELECT `nachricht` FROM `kontakt` LIMIT '.$limit.', '.$ergebnisse_pro_seite);
while ($row = mysqli_fetch_assoc($result)) {
// Ausgabe deiner Daten
}
for ($i=1; $i<=$gesamt_seiten; ++$i) {
if ($seite == $i) {
echo ''.$i.'';
} else {
echo ''.$i.'';
}
}
include 'footer.html';
?>
</div><!-- container -->
</body>
</html>
now with a div class, so I can write this in my css?
Edit: I have inserted the whole code for you, maybe who can overlook which error is present? After I have inserted the accepted answer, I get a white screen and nothing is displayed anymore. Unfortunately I also don't get an error

Do yourself a favor and ditch those echo garbage. Make the HTML first class citizen and then mix PHP into it:
<?php
// php code
?>
<?php while ($ausgabe = $abfrage->fetch_object()) { ?>
<div class="test">
<b>user:</b><?=!is_null($ausgabe->bn) ? htmlspecialchars($ausgabe->bn) : 'Guest'?>
<br>
<b>Date:</b><?=$ausgabe->date?>
<br>
<b>subject:</b><?=htmlspecialchars($ausgabe->subject)?>
<br>
<b>message:</b>
<br>
<?=htmlspecialchars($ausgabe->message)?>
<br>
<hr>
</div>
<? } ?>
<?php
// rest of the PHP code

Related

mySQL auto-increment + auto adjust id by dynamicly deleting table content via PHP?

I am currently trying to build a "ToDo-App" which lets me INSERT text into a database, which will then be displayed. There is a "feature" to delete content based on their ID.
If I input two tasks into my application, I get two table records with ID 1 and 2. When I delete record 1, the record with ID 2 still exists. Thus, the record with ID 2 is listed as the first item in the to-do list.
I have to enter "2" in the "delete input field" to delete the first item from the list! How can I get this to be in sync? Is the ID field appropriate for maintaining the logical / application level order of the tasks?
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
</head>
<?php
$con = mysqli_connect("","root","","todo");
$sql = "SELECT text FROM work";
$res = mysqli_query($con, $sql);
if(isset($_POST["text"]))
{
$eingabe = $_POST["text"];
$query = "INSERT INTO work(text) VALUES('$eingabe')";
mysqli_query($con, $query);
header("Refresh:0");
}
else
{
echo "";
}
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
else
{
echo "";
}
?>
<body>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<form action="index.php" method="post">
<input class="lil-input" name="text" type="text">
<input type="submit" class="lil-button-green" value="Hinzufügen">
</form>
<ol id="liste" class="lil-list">
<?php
while($dsatz = mysqli_fetch_assoc($res))
{
echo "<li>" .$dsatz["text"] ."</li>";
}
?>
</ol>
<form id="form" action="index.php" method="post">
<input class="lil-input" name="del" type="text">
<input type="submit" class="lil-button-red lil-button-small" value=" Löschen ">
</form>
</div>
</div>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
var anzahl = $("#liste li").length;
if(anzahl < 1)
{
$("#form").hide();
}
else
{
$("form").show();
}
</script>
</body>
</html>
The pictures:
HTML Output
MySQL Dashboard
As discussed in the comment, you can have multiple checkboxes forming an array parameter: <input name="theName[1]"> with explicit key and name="theName[]" with implicit keys.
Further more, you should use prepared statements to prevent SQL injection attacks. Imagine an attacker sends a request with a single quote ' in the field, i.e. he terminates the SQL string delimiter, and adds arbitrary SQL code. Prepared statements use placeholders and the parameters are sent separately.
You should also handle errors. In the code below errors are output as HTML, however, you should define your own logger function rather than just echo into the stream. This can output HTML on development servers but log to disk on production servers.
This is a working example tested on PHP7.3 with MariaDB 10:
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
<style>
#frm-tasks button
{
padding: 0 18px;
}
</style>
</head>
<body>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$con = new mysqli('localhost', 'testuser', 'testpasswd', 'testdb');
$action = $_POST['action'] ?? 'list';
if(!empty($_POST["text"]))
{
$eingabe = $_POST["text"];
try
{
$stmt = $con->prepare('INSERT INTO work(text) VALUES(?)');
$stmt->bind_param('s', $_POST["text"]);
$stmt->execute();
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
if('del' === $action && isset($_POST['rows']) && is_array($_POST['rows']))
{
try{
$stmt = $con->prepare('DELETE FROM `work` WHERE `work`.`id` = ?');
$stmt->bind_param('i', $row);
foreach ($_POST['rows'] as $row)
{
$stmt->execute();
if($e = $stmt->error)
echo "<div>DB Error: $e</div>";
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
?>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<!--form action="index.php" method="post"-->
<form id="frm-tasks" action="" method="post">
<input class="lil-input" name="text" type="text">
<button type="submit" class="lil-button-green" name="action" value="add">Hinzufügen</button>
<?php
try
{
$res = $con->query('SELECT id, text FROM work');
if(0 < $res->num_rows)
{
?>
<table>
<thead>
<tr>
<th></th><th>ID</th> <th>Aufgabe</th>
</tr>
</thead>
<tbody>
<?php
while($dsatz = mysqli_fetch_object($res))
{
?>
<tr>
<td><input type="checkbox" name="rows[]" value="<?php echo $dsatz->id;?>"></td><td><?php echo $dsatz->id;?></td> <td><?php echo $dsatz->text;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<button type="submit" class="lil-button-red lil-button-small" name="action" value="del">Löschen</button>
<?php
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $e->msg;</div>";
}
?>
</form>
</div>
</div>
</div>
<!-- not needed atm script src="js/jquery-3.3.1.min.js"></script-->
<h2>POST</h2>
<?php
var_dump($_POST);
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error connecting DB: $msg;</div>";
}
?>
</body>
</html>
The key of the list is the 'th' in the database so just fixing limits
Replace
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
With
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` LIMIT 1 OFFSET ".array_search($del, mysqli_fetch_assoc($res));
mysqli_query($con, $sql2);
header("Refresh:0");
}

PHP - Search Not Working

I tried to make a search engine in order to search between 2 dates $dateFrom to $dateTo.
Here what i have tried.:
Index.php:
<?php
require_once 'Connection.simple.php';
$tutorialTitle = "Using Ajax to search a Record with PHP, MySQL and jQuery (Look and Feel by Bootstrap)";
$conn = dbConnect();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title><?php echo $tutorialTitle;?></title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta name="copyright" content="BEHSTANT SOFTWARE | Datasoft Engineering 2013"/>
<meta name="author" content="Reedyseth"/>
<meta name="email" content="ibarragan at behstant dot com"/>
<meta name="description" content="<?php echo $tutorialTitle;?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel=stylesheet href="css/style01.css">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="wrapper">
<div class="page-header ">
<div class="panel panel-default">
</div>
</div>
<div class="mainContent">
<form class="form-horizontal" role="form" method="get">
<div class="form-group">
<label class="col-sm-2 control-label" for="minimum date">employee_id</label>
<div class="input-group col-sm-9">
<input id="DateFrom" name="DateFrom" type="date" class="form-control" placeholder="Type the name" />
<input id="DateTo" name="DateTo" type="date" class="form-control" placeholder="Type the name" />
<span class="input-group-btn">
<button type="button" class="btn btn-default btnSearch">
<span class="glyphicon glyphicon-search"> Search</span>
</button>
</span>
</div>
</div>
</form>
<div class="col-sm-2"></div>
<div class="col-sm-8">
<!-- This table is where the data is display. -->
<table id="resultTable" class="table table-striped table-hover">
<tbody></tbody>
</table>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.10.2.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.btnSearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'search.php',
type: 'get',
DateFrom: {DateFrom: $('input#DateFrom').val()},
DateTo: {DateTo: $('input#DateTo').val()},
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
</body>
</html>
Search.php:
<?php
require_once 'Connection.simple.php';
$conn = dbConnect();
$OK = true;
if (isset($_GET['DateFrom']) && isset($_GET['DateTo'])) {
$dateFrom = $_GET['DateFrom'];
$dateTo = $_GET['DateTo'];
$sql = "SELECT * FROM attendance WHERE date >= '". $dateFrom ."' AND date <= '". $dateto ."' ";
}
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['emp_id']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['day']."</td>";
echo "<td>".$row['time_in']."</td>";
echo "<td>".$row['time_out']."</td>";
echo "<td>".$row['worked']."</td>";
echo "<td>".$row['overtime']."</td>";
echo "<td>".$row['less_hours']."</td>";
echo "<td>".$row['transport_in']."</td>";
echo "<td>".$row['Transport_out']."</td>";
echo "</tr>";
}
}
?>
EDIT 1:
$sql = "SELECT * FROM attendance WHERE date >= '". $dateFrom ."' AND date <= '". $dateto ."' ";
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($dateFrom, $dateTo));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
******I added that to make execute the query but still not working******
<?php
function dbConnect (){
$conn = null;
$host = 'localhost';
$db = 'payroll';
$user = 'root';
$pwd = '';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
//echo 'Connected succesfully.<br>';
}
catch (PDOException $e) {
echo '<p>Cannot connect to database !!</p>';
echo '<p>'.$e.'</p>';
exit;
}
return $conn;
}
?>
******* This is my code for DBconnection*******
My database name is payroll and the table is attendance.
You need to name the parameters inside SQL code.
Please, use the correct case for the columns names. You spelled "less_hours", while in your database this column is called "Less_Hours". And this gave a notice: "Undefined index: less_hours".
I put the output code inside the 1-st if, otherwise $rows will always be undefined for the first time.
This code worked for me:
if (isset($_GET['DateFrom']) && isset($_GET['DateTo'])) {
$dateFrom = $_GET['DateFrom'];
$dateTo = $_GET['DateTo'];
$sql = "SELECT * FROM attendance WHERE
date >= :date_from AND date <= :date_to ";
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(
array('date_from' => $dateFrom, 'date_to' => $dateTo));
// Extract the values from $result
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['emp_id']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Day']."</td>";
echo "<td>".$row['Time_In']."</td>";
echo "<td>".$row['Time_Out']."</td>";
echo "<td>".$row['Worked']."</td>";
echo "<td>".$row['Overtime']."</td>";
echo "<td>".$row['Less_Hours']."</td>";
echo "<td>".$row['Transport_In']."</td>";
echo "<td>".$row['Transport_Out']."</td>";
echo "</tr>";
}
}
}

Parse Error: $end

So I'm getting an error:
Parse error: syntax error, unexpected $end in C:\xampp\htdocs\CWoW\add.php on line 97 in my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="default.css">
<link rel="stylesheet" href="cms.css">
<title>ACP</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$mysqli = new mysqli('localhost','root','','meh') or die("Error " . mysqli_error($mysqli));
if(empty($_POST['title'])) {
echo 'The title must not be empty!<br/>';
} else if(empty($_POST['message'])) {
echo 'The message field must not be empty!<br/>';
} else if(empty($_POST['author'])) {
echo 'A poster name is required!<br/>';
} else {
if(! get_magic_quotes_gpc() )
{
$title = addslashes ($_POST['title']);
$message = addslashes ($_POST['message']);
$author = addslashes ($_POST['author']);
}
else
{
$title = $_POST['title'];
$message = $_POST['message'];
$author = $_POST['author'];
}
if ($query = $mysqli->query("INSERT INTO etl_articles (title, message, author) VALUES ('{$title}', '{$message}', '{$author}');")) {
echo "The post has successfully been added! <a href='add.php'>Click Here</a> to go back.";
} else {
echo 'Failed to add the post!';
$query->close;
}
}
}
else
{
?>
<div id="logo_div">
<a id="logo_anch" href="#" title="Project Hysteria">Project Hysteria</a>
</div>
<ul id="top_menu">
<li>Home</li>
</ul>
<div id="main">
<aside id="right">
<div id="main_sep"></div>
<div id="content_ajax">
<form method="post" action="<?php $_PHP_SELF ?>" class="custom2">
<article>
<div class="top"><input name="title" type="text" placeholder="» Title" /></div>
<section class="body">
<div class="clear"></div>
<div class="news_bottom">
<textarea name="message" placeholder="» Message"></textarea><br><br>
<select name="author">
<option value="Admin">Admin</option>
<option value="Moderator">Global Moderator</option>
<option value="Developer">Developer</option>
</select><br><br>
<input name="add" type="submit" value="Submit News" />
</div>
<div class="comments" id="comments_17"></div>
</section>
</article>
</div>
</aside>
<div class="clear"></div>
</div>
</form>
<footer>
<p>© Copyright 2013 Caustic WoW</p>
<p id="design"> <a target="_new" href=""></a></p>
</footer>
</section>
</body>
</html>
I can't seem to find the problem really.
If any of you guys can help me that would be great.
You have a syntax error in your code : there is an opening brace { after else statement but the closing } is missing.
Replace
else
{
?>
with
else;
?>
or
else{}
?>

when I uploaded my php application using Filezilla images are missing

I uploaded my php application using Filezilla and when I checked it online, all of the images are missing and total site get break. I don't understand this because everything works fine offline but when I check through after publishing it online, all the images disapear. I also checked all my links and they're fine.
Here is my code
<html>
<head>
<title> Vatsal Technosoft Messanger </title>
<script type="text/javascript" src="../JavaScript/frmvalidation.js"></script>
<link href="../Stylesheet/style.css" media="all" type="text/css" rel="stylesheet" />
</head>
<body>
<?php include 'connect.php' ?>
<?php include 'functions.php' ?>
<?php include 'header.php' ?>
<div id="outer" style="margin-top:0px;">
<div class="container" style="color:#00C; z-index:1;">
<div class="subcontainer" >
<?php
if(loggedin())
{
?>
<a href='' onclick='addcontact();' id='noti' style='text- decoration:none;margin-bottom:0px;'>
<?php
$my_id = $_SESSION['user_id'];
$notifrnd = mysql_query("SELECT * FROM `frnd_req` WHERE `to` = '$my_id' ");
if(mysql_num_rows($notifrnd))
{
while($arr = mysql_fetch_array($notifrnd))
{
$fid = $arr[1];
$firstname = getfirstname($fid , 'firstname');
$lastname = getlastname($fid , 'lastname');
}
echo "<font style='color:#FFFF00; font-size:11px; margin-left:15px; margin-top:3px; margin-bottom:5px; float:left; font-weight:bold;'>You have Friend request</font>";
}
}
?>
</a>
<?php
?>
<iframe name ='uses' src='../indexus.php' width='185' height='140' style='max-width:185px; background-color:#ccc;'>
</iframe>
<?php
if(adminlogedin())
{
$admin_id = $_SESSION['admin_id'];
eader('location:admindex.php');
}
?>
</div>
</div>
<div class="footer">
<div class="online">
<?php
if(loggedin())
{
echo "<img src='../Images/ym1.png'>";
}
else
{
echo "<img src='../Images/ym2.png'>";
}
?>
</div>
<div class="footertext">
<?php
if(loggedin())
{
$my_id = $_SESSION['user_id'];
$firstname = getfirstname($my_id , 'firstname');
$lastname = getlastname($my_id , 'lastname');
echo " $firstname $lastname ";
}
else
{
}
?>
</div>
</div>
</div>
</body>
</html>

Name being inserted, but file is not being uploaded [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I've an upload input field in a form. the problem that the name of the file is being inserted in the database but the file is not being uploaded to the server, and the same code is working on the same server in a different file in the same directory but in a different query. form is set to enctype="multipart/form-data",
here is the code where its not working
<!DOCTYPE html>
<html lang="en">
<head>
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/dbc.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php confirm_logged_in(); ?>
<?php find_selected_post(); ?>
<?php
$target = "../upload/";
$target = $target . basename( $_FILES['post_photo']['name']);
if (intval($_GET['cat']) == 0) {
redirect_to('cat_posts.php');
}
include_once("includes/form_functions.php");
if (isset($_POST['submit'])) {
$errors = array();
$required_fields = array('post_title', 'position', 'visible', 'post_content');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$fields_with_lengths = array('post_title' => 30);
$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
$category_id = mysql_prep($_GET['cat']);
$post_title = trim(mysql_prep($_POST['post_title']));
$post_content = mysql_prep($_POST['post_content']);
$post_description = mysql_prep($_POST['post_description']);
$post_keywords = mysql_prep($_POST['post_keywords']);
$post_tags = mysql_prep($_POST['post_tags']);
$post_photo =($_FILES['post_photo']['name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
if (empty($errors)) {
$query = "INSERT INTO ss_posts (
post_title, post_content, post_description, post_keywords, post_tags, post_photo, position, visible, category_id
) VALUES (
'{$post_title}', '{$post_content}', '{$post_description}', '{$post_keywords}', '{$post_tags}', '{$post_photo}', {$position}, {$visible}, {$category_id}
)";
if ($result = mysql_query($query, $connection)) {
$message = "Successfully Created.";
$new_post_id = mysql_insert_id();
redirect_to("cat_posts.php?post={$new_post_id}");
} else {
$message = "The Post Could Not Be Created.";
$message .= "<br />" . mysql_error();
}
} else {
if (count($errors) == 1) {
$message = "There was 1 error in the form.";
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
}
?>
<?php
error_reporting(E_ALL);
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo "<br/>target: " . $target;
if (!move_uploaded_file($_FILES['post_photo']['tmp_name'], $target)) {
echo "<br/>Upload failed.";
} else {
echo "<br/>Upload done.";
}
?>
<meta charset="utf-8"/>
<title>New Post - Administration Panel</title>
<script src="js/ckeditor/ckeditor.js" type="text/javascript"></script>
<link rel="stylesheet" href="js/ckeditor/sample.css">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/form.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/button.css" type="text/css" media="screen" /> <!--[if lt IE 9]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="js/hideshow.js" type="text/javascript"></script>
<script src="js/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.equalHeight.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".tablesorter").tablesorter();
}
);
$(document).ready(function() {
//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
return false;
});
});
</script>
<script type="text/javascript">
$(function(){
$('.column').equalHeight();
});
</script>
</head>
<body>
<header id="header">
<hgroup>
<h1 class="site_title">Administration Panel</h1>
<h2 class="section_title">New Post</h2><div class="btn_view_site">
View Site</div>
</hgroup>
</header>
<!-- end of header bar -->
<section id="secondary_bar">
<div class="user">
<p>Hello, <?php echo $_SESSION['username']; ?> (Logout)</p>
</div>
<div class="breadcrumbs_container">
<article class="breadcrumbs">Administration Panel
<div class="breadcrumb_divider"></div>
<a class="current">New Post</a></article>
</div>
</section>
<!-- end of secondary bar -->
<aside id="sidebar" class="column" style="height:160%;">
<hr/>
<h3>Pages</h3>
<ul class="toggle">
<li class="icn_new_article">Add a New Page</li>
<li class="icn_edit_article">Edit/Delete a Page</li>
</ul>
<hr/>
<h3>Users</h3>
<ul class="toggle">
<li class="icn_add_user">Add New User</li>
<li class="icn_view_users">View Users</li>
</ul>
<hr/>
<h3>Blog</h3>
<ul class="toggle">
<li class="icn_categories">Create a Category</li>
<li class="icn_new_article">Create/Edit a Post</li>
<li class="icn_settings">Home Blog Settings</li>
<li class="icn_settings">Blog Settings</li>
</ul>
<hr/>
<h3>Settings</h3>
<ul class="toggle">
<li class="icn_settings">Settings</li>
<li class="icn_settings">Site Logo</li>
<li class="icn_jump_back">Logout</li>
</ul>
<footer>
<hr />
<p><strong>Copyright © 2013 Sky Define</strong></p>
<p>Powered by Sky Define</p>
</br>
</br>
</footer>
</aside><!-- end of sidebar -->
<section id="main" class="column">
<?php
move_uploaded_file($_FILES['post_photo']['tmp_name'], $target);
// output a list of the fields that had errors
if (!empty($errors)) {
echo "<p class=\"errors\">";
echo "Please review the following fields:<br />";
foreach($errors as $error) {
echo " - " . $error . "<br />";
}
echo "</p>";
}
?>
<article class="module width_full">
<header><h3>New Post</h3></header>
<div class="module_content">
<h2>Adding New Post</h2>
<?php if (!empty($message)) {echo "<p class=\"message\">" . $message . "</p>";} ?>
<?php if (!empty($errors)) { display_errors($errors); } ?>
<div class="mws-panel grid_4">
<div class="mws-panel-header">
</div>
<div class="mws-panel-body">
<form class="mws-form" enctype="multipart/form-data" action="new_post.php?cat=<?php echo $sel_category['id']; ?>" method="post">
<div class="mws-form-inline">
<?php $new_post = true; ?>
<?php if (!isset($new_post)) {$new_post = false;} ?>
<div class="mws-form-row">
<label>Post Name:</label>
<div class="mws-form-item large">
<input type="text" name="post_title" id="post_title" class="mws-textinput" placeholder="Post Name Goes Here." />
</div>
</div>
<div class="mws-form-row">
<label>Post Description:</label>
<div class="mws-form-item large">
<input type="text" name="post_description" id="post_description" class="mws-textinput" placeholder="Post Description Goes Here." />
</div>
</div>
<div class="mws-form-row">
<label>Post Keywords:</label>
<div class="mws-form-item large">
<input type="text" name="post_keywords" id="post_keywords" class="mws-textinput" placeholder="Post Keywords Goes Here, Separated By Commas!" />
</div>
</div>
<div class="mws-form-row">
<label>Post Content:</label>
<div class="mws-form-item large">
<textarea name="post_content" id="post_content" class="ckeditor" > </textarea>
</div>
</div>
<div class="mws-form-row">
<label>Post Tags:</label>
<div class="mws-form-item large">
<input type="text" name="post_tags" id="post_tags" class="mws-textinput" placeholder="Post Tags Goes Here, Separated By Commas!" />
</div>
</div>
<div class="mws-form-row">
<label>Edit Post Photo:</label>
<div class="mws-form-item large">
<input type="file" name="post_photo" id="post_photo" />
</div>
</div>
<div class="mws-form-row">
<label>Position:</label>
<div class="mws-form-item large">
<select name="position">
<?php
if (!$new_post) {
$post_set = get_posts_for_category($sel_post['category_id']);
$post_count = mysql_num_rows($post_set);
} else {
$post_set = get_posts_for_category($sel_category['id']);
$post_count = mysql_num_rows($post_set) + 1;
}
for ($count=1; $count <= $post_count; $count++) {
echo "<option value=\"{$count}\"";
if ($sel_post['position'] == $count) { echo " selected"; }
echo ">{$count}</option>";
}
?>
</select>
</div>
</div>
<div class="mws-form-row">
<label>Visible:</label>
<div class="mws-form-item large">
<input type="radio" name="visible" value="0"<?php
if ($sel_post['visible'] == 0) { echo " checked"; }
?> /> No
<input type="radio" name="visible" value="1"<?php
if ($sel_post['visible'] == 1) { echo " checked"; }
?> /> Yes
</div>
</div>
</form>
<div class="mws-button-row">
<input type="submit" name="submit" value="Add Post" class="mws-button green" />
<a class="mws-button red" href="index.php">Cancel</a>
</div>
</div>
</div>
</div>
</article>
<div class="clear"></div>
</div>
</article><!-- end of stats article -->
<div class="spacer"></div>
</section>
</body>
</html>
The way I would try to find the error:
make your errors visible:
<?php error_reporting(E_ALL); ?>
$target should be a full path.
Check your HTML form. Did you add the enctype attribute?
<form enctype="multipart/form-data" method="POST" action="script.php">
Is your Input correct?
<input type="file" name="post_photo"/>
What does the $_FILES array contents?
<?php echo print_r($_FILES); ?>
Edit
Please let us know the data these lines return:
<?php
error_reporting(E_ALL);
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo "<br/>target: " . $target;
if (!move_uploaded_file($_FILES['post_photo']['tmp_name'], $target)) {
echo "<br/>Upload failed.";
} else {
echo "<br/>Upload done."
}
?>
Edit 2 (Solution):
Your submit-button is outside the form-Tag. That's why. Fix it like this:
<form>
<input type="submit" name="submit" value="Add Post" class="mws-button green" />
</form>
Your $target should contain the root path
$target = $_SERVER['DOCUMENT_ROOT']"/upload/";
$target = $target . basename( $_FILES['post_photo']['name']);

Categories