PHP textarea input multiplies by two and outputs double input - php

Quick rundown:
Everything ran perfectly as it should when I had my own custom textarea field to send data
I had a custom text editor widget for inputs, but tried to add CKEditor for more functionality
When I added CKEditor package (https://ckeditor.com/ckeditor-4/download/?undefined-addons=) the editor was there, but when I clicked "Add" button and sent data, the input was doubled and there was a space between inputs (for example - input was:"test" and output was "test<br><br>test"), as if I put <br> tag and multiplied my input somewhere.
When I stopped trying with CKEditor, I went back to original code and my own original custom text editor, which before worked perfectly. However, to my surprise, it now still doubles the input string, but it doesn't put a <br> tag in between.
In DB the string value is normal and not doubled.
I have no idea how this happened, I've been going over the code for a hour or so now, trying to see if I overlooked something, but I even created a separate file with functioning code, before I was trying with CKEditor in case something broke and I could just replace it with old code and try tomorrow, but now it's messed up and I have no idea how and where.
notifications.php
<form class="form-inline" action="/action_page.php">
</form>
</nav>
<div class="container-fluid m-0 p-0">
<div class="row justify-content-center">
<div class="col-md-10">
<?php if (isset($_SESSION['response'])) { ?>
<div class="alert alert-<?= $_SESSION['res_type']; ?> alert-dismissible text-center">
<button type="button" class="close" data-dismiss="alert">×</button>
<b><?= $_SESSION['response']; ?></b>
</div>
<?php } unset($_SESSION['response']); ?>
</div>
</div>
<div class="row">
<div class="">
<?php
$query = 'SELECT * FROM crud';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
?>
<table class="table table-hover" id="data-table">
<tbody>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td></td>
<td class="pt-2"><?=
$longString=$row['name'];
$link = $row['id'];
$longStringshortcut = strlen($longString);
//echo substr($longString, 0, 100).'... Read More';
if ($longStringshortcut > 250) {
echo substr($longString, 0, 250).".. <a href='details.php?details=$link'><strong>Preberi več...</strong></a>"; }
else {
echo $longString;
}
?>
Details
Delete
Edit
</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="col-md-4 p-0">
<h5 class="">Add notification:</h5>
<form action="action.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $id; ?>">
<div class="form-group">
<textarea name="name" value="<?= $name; ?>" class="form-control" placeholder="This is the default text" required></textarea>
</div>
<div class="form-group">
<?php if ($update == true) { ?>
<input type="submit" name="update" class="btn btn-success btn-block" value="Change notification">
<?php } else { ?>
<input type="submit" name="add" class="btn btn-primary btn-block" value="Add">
<?php } ?>
</div>
<div class="form-group">
<input type="hidden" name="oldimage" value="<?= $photo; ?>">
<input type="file" name="image" class="custom-file">
<img src="<?= $photo; ?>" width="120" class="img-thumbnail">
</div>
</form>
</div>
</div>
</div>
</div>
action.php
<?php
session_start();
include 'config.php';
$update=false;
$id="";
$name="";
$photo="";
if(isset($_POST['add'])){
$name=$_POST['name'];
$photo=$_FILES['image']['name'];
$upload="uploads/".$photo;
$query="INSERT INTO crud(name,photo)VALUES(?,?)";
$stmt=$conn->prepare($query);
$stmt->bind_param("ss",$name,$upload);
$stmt->execute();
move_uploaded_file($_FILES['image']['tmp_name'], $upload);
header('location:index.php');
$_SESSION['response']="Successfully Inserted to the database!";
$_SESSION['res_type']="success";
}

The problem was with the <?= syntax (echoing), <?php solved it.

Related

How to fix 'If(isset($_POST['Id'])) error' while editing the form in a PHP based CRUD application?

The "if(isset($_POST["titleId"]) && !empty($_POST["titleId"])" in my code is returning false value.
I'm working on a CRUD application, the insert modal is working fine, now I'm stuck at the update part of it. So when you click on the update icon it does fetch the right titleId in the URL but the first 'if' condition returns false and hence the update isn't working.
Here's what I've tried so far.
admin.php
<?php
$typeId = filter_input(INPUT_GET, "type");
$titleId = filter_input(INPUT_GET, "titleId");
$active = "admin" . $typeId;
require_once './pages/header.php';
require_once './functions/queries.php';
$getAll = Queries::getAllTitle($typeId);
?>
<div class="container">
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header clearfix">
<h2 class="pull-left"></h2>
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
</div>
<!--<div class="container">
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#facultyAddModal">Add Title</button>
<br><br>-->
<div class="panel-group" id="titleAccordion">
<?php
for ($i = 0; $i < count($getAll); $i++) {
echo <<<HTML
<div class="panel panel-default">
<div class="panel-heading"><h4 class="panel-title">
<a data-toggle="collapse" data-parent="#titleAccordion" href="#collapseF{$i}">{$getAll[$i]['title']}</a></h4>
</div>
<div id="collapseF{$i}" class="panel-collapse collapse" >
<div class="panel-body">
<div class="table-responsive">
<table class="table table-condensed"><tbody>
<tr><td>Title:</td><td>{$getAll[$i]['title']}</td></tr>
<tr><td>Units:</td><td>{$getAll[$i]['units']}</td></tr>
<tr><td>Category:</td><td>{$getAll[$i]['category']}</td></tr>
<tr><td>
<tr><td><input type="hidden" id="titleId" name="titleId" value="{$getAll[$i]['titleId']}"> </tr><td>
<a href='edit.php?titleId={$getAll[$i]['titleId']}' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>
<a href='delete.php?titleId={$getAll[$i]['titleId']}' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-trash'></span></a>
</tr></td>
</tbody></table>
</div>
</div>
</div>
</div>
HTML;
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Title Add Modal-->
<div class="modal fade" id="facultyAddModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Title</h4>
</div>
<div class="modal-body">
<div id="adminResult" class="hide" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="resultAdminContent"></div>
</div>
<form class="cmxform" id="adminForm" method="post">
<label for="Activity">ActivityAttended (required)</label>
<input class="form-control" id="adminTitle" name="title" type="text" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" name="category">
<br>
<?php echo
'<input type="hidden" id="addadminTypeId" value="'.$typeId.'">';
?>
<?php echo
'<input type="hidden" id="titleId" name="titleId" value="'.$titleId.'">';
?>
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</div>
</div>
</div>
update.php
<?php
require_once 'functions/db_connection.php';
$conn = DB::databaseConnection();
$title = $units = $category = "";
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
$titleId = $_POST['titleId'];
$sql = "UPDATE title SET title = :title, units = :units, category = :category WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
// Bind variables to the prepared statement as parameters
$stmt->bindParam(':titleId', $titleId);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':units', $units);
$stmt->bindParam(':category', $category);
if ($stmt->execute()) {
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
unset($stmt);
}
unset($conn);
} else{
if(isset($_GET["titleId"]) && !empty(trim($_GET["titleId"]))){
$titleId = trim($_GET["titleId"]);
$sql = "SELECT * FROM title WHERE titleId = :titleId";
if($stmt = $conn->prepare($sql))
{
$stmt->bindParam(':titleId', $titleId);
if ($stmt->execute()){
if($stmt->rowCount() == 1){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Retrieve individual field value
$title = $result["title"];
$units = $result["units"];
$category = $result["category"];
} else{
echo"error1";
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
unset($stmt);
unset($conn);
} else{
// URL doesn't contain id parameter. Redirect to error page
echo"error2";
exit();
}
}
?>
<!--<!DOCTYPE html>-->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>Update Record</h2>
</div>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<label for="Activity">Title</label>
<input class="form-control" id="adminTitle" name="title" type="text" value="<?php echo $title; ?>" required>
<br>
<label for="units">Units (required)</label>
<input class="form-control" id="adminUnits" type="number" name="units" value="<?php echo $units; ?>" required>
<br>
<label for="Category">Category (Optional)</label>
<input class="form-control" id="adminCategory" type="text" value="<?php echo $category; ?>" name="category">
<br>
<input type="hidden" name="titleId" value="<?php echo $titleId; ?>">
<button class="btn btn-info btn-primary" type="submit">Submit</button>
<br>
<br>
</form>
</div>
</<div>
</div>
</div>
</div>
</body>
</html>
The only goal here is to get the update form working, the user should be able to update the records of the respective title being selected.
I don't know crud but I think there is a way to debug a little:
e.g. try this:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// test if you are here:
echo 'hi, yeah I am here!';
}
or this
echo '<pre>';
var_dump($_POST);
echo '</pre>';
// before:
if(isset($_POST["titleId"]) && !empty($_POST["titleId"])){
// ...
}
also, take a look at
error_get_last()['message']

Retaining Older Uploaded Image In Db

I have a page in my clients dashboard for editing his about content.
Once i click on edit button it redirects to another page and there is an option for uploading new image and also content.
Problem :If no new image is uploaded suppose only some text fields are changed and clicked on update the text content changes and redirects to main page but image is deleted from db,but i don't want image to be deleted from the db if no new picture is uploaded.
Two Files Are there
1)index.php
2)editabout.php
index.php
<div class="main-container">
<div class="row">
<div class="container">
<div class="col-lg-12">
<div class="row">
<?php include('db.php'); $select=mysql_query("SELECT * FROM `about`"); while($row=mysql_fetch_array($select)){?>
<div class="col-md-3"><img id="profileimage" src="about/<?php echo $row['image']; ?>" style="width:100%;height:200px;" class="img-thumbnail img-responsive" required>
<div class="row">
<div class="col-md-6"> <input style="width:100%;" class="btn btn-info btn-lg mb-3 mr-3" type="submit" value="Edit"></div>
</div>
</div>
<?php}?>
</div>
</div>
</div>
</div>
editabout.php
<div class="row">
<div class="col-lg-4">
<form action="" method="post" enctype="multipart/form-data">
<div class="main-container file-upload">
<div class="file-upload__dropzone">
<?php
include('db.php');
$select=mysql_query("SELECT * FROM `about` where `sl.no`='$bid' ");
while($row=mysql_fetch_array($select)){
?>
<img id="profileimage" src="about/<?php echo $row['image']; ?>" value="<?php echo $row['image']; ?>" class="img-thumbnail img-responsive" style="width:100%;height:200px;">
<?php } ?>
<div class="file-upload__browse-files">
<button class="btn btn-outline-info btn-lg btn-block btn-rounded file-upload__browse-btn">Browse files</button>
<input id="upload-files-default" name="img" type="file" multiple class="upload" onchange="readURL(this);">
</div><br>
<button class="btn btn-success btn-lg mb-2 mr-3" name="ok" type="submit">Update</button>
</div>
</div>
</form>
</div>
Php code for uploading
include('db.php');
if(isset($_POST['ok']))
{
$photo=$_FILES['img']['name'];
$target_dir = "about/";
$location = $target_dir .$_FILES["img"]["name"];
move_uploaded_file($_FILES['img']['tmp_name'],$location);
$query1="UPDATE `about` SET `image`='$photo',
`up_date`=now()
WHERE `about`.`sl.no` ='$bid'";
mysql_query($query1);
You have to check does the file exist/uploaded or not before executing any query. As an example below:
if(is_uploaded_file($_FILES["img"]["tmp_name"] && file_exists($_FILES["img"]["tmp_name"])){
//update query with picture
//move_uploaded_file here
}else{
//Only query updating does details without move_uploaded_file
}
Above code must be put in the if(isset($_POST["ok"])) code block.

Why does the value of the hidden input filed gives me the same result alwayes?

First I'm beginner in php, second I'm trying to trace the value of the hidden input which is " the ID of the image in table products ", but whenever I click the delete button of any image, it always gives me the last id of the last image in my products table , and when I changed the input into text it prints the correct id but if I used it with POST it will not work .
Here is the codes :
<?php
if(isset($_POST['delete'])){
$dataBase = mysql_connect("localhost","root","");
mysql_select_db('HouseOfCake');
$PID = $_POST['PID'];
echo $PID ;
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<form method="POST" action="Delete.php">
<div class="container">
<?php
$dataBase = mysqli_connect("localhost","root","" , "HouseOfCake");
?>
<div class="row text-center">
<?php
$r=mysqli_query($dataBase,"SELECT*FROM Products");
while($Products=mysqli_fetch_array($r, MYSQLI_ASSOC)){
?>
<div class="col-lg-3 col-md-6 mb-4">
<div class="card" name= <?php $Products['CakeID']; ?>>
<image src = <?php echo
'data:image/jpg;base64,'.base64_encode($Products['Image']).'' ; ?> />
<div class="card-body">
<h4 class="card-title"> <?php echo $Products['Price']; ?> SR. </h4>
<p class="card-text"> Details.</p>
</div>
<div class="card-footer">
<input type="text" value= "<?php echo $Products['CakeID'] ?>" name="PID" >
<input type = "submit" name="delete" value=" Delete Item."
style="width:250px" >
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</form>
</body>
</html>
To clean up what you are doing, so its easier to understand, you have this in a nutshell:
<form>
while {
<inputs>
}
</form>
What this will do is submit ALL those inputs to PHP. And since each one of the inputs in the while have the same name, PHP will only use the 'last one received'.
You want to have your flow like this:
while {
<form>
<inputs>
</form>
}
That way each form only submits the inputs defined inside of it (not all of them on the page).
So to recap with your code, you would want to have multiple forms on the page as such:
<?php while($Products=mysqli_fetch_array($r, MYSQLI_ASSOC)){ ?>
<form method="POST" action="Delete.php">
<input type="text" value="<?php echo $Products['CakeID'];?>" name="PID">
<input type="submit" name="delete" value="Delete Item." style="width:250px">
</form>
<?php }?>

Text Area new lines from mysql database?

I'm sending text from a text area which is being sent into a mysql database and then being shown elsewhere on another page.
If i input for example:
text
text
text
into the text area, i simply receive
text text text
I understand i need to create a new line some how between the text, but really unsure on the way to go about it as it is being stored in MySQL as
text||text||text
<div class="panel-heading">Addservices</div>
<div class="panel-body">
<div class="block">
<form method="POST" action="page.php">
<p>Add service title:</p>
<input type="text" class="form-control" name="servicetitle" value=""><br />
</div><div class="block">
<p>Add service content:</p>
<textarea id="b" type="text" class="form-control" name="servicecontent"></textarea>
</div>
<input class="btn btn-primary btn-md" type="submit">
</form>
</div>
Code where it is being pulled from
<?php
$getService = $conn->query("SELECT id, value FROM customerlanding WHERE element = 'service'");
while ($row = $getService->fetch_assoc()) {
$id = $row['id'];
$split = explode("||", $row['value']);
echo'
<div class="col-md-4">
<div class="text-column text-column-centralized tex-column-icon-lg this-animate" data-animate="fadeInLeft">
<div class="text-column-icon">
<span style="background-color:'; echo $result['primarycolour']; echo '"class="fa"></span>
</div>
<h4>';
echo $split[0];
echo '</h4>
<div class="text-column-info">
';
echo $split[1];
echo '
</div>
</div>
</div>';
}
?>
.
if(isset($_POST['servicetitle'])){
$service = $_POST['servicetitle']."||".$_POST['servicecontent'];
$insertservice = $conn->query("INSERT INTO `customer`(`customerid`, `element`, `value`) VALUES ('10','service','$service')");
Solved.
echo nl2br($split[1]);

PHP post request from HTML page showing blank input fields

Currently looking to implement functionality to edit details in MySQL database via a HTML page. The page itself shows all data in the database which matches the unique id of the user who is is logged in via a PHP session and echos that data to input boxes in a while loop.
When the user makes changes to the input text and hits the save changes link it then calls the edit endpoint which in turn calls the edit SQL function in a functions file.
I'm using an anchor tag wrapped in a button to send the id of the row that is being edited and all this sits inside a POST action form.
However the input texts are only showing as blank as if the endpoint is not receiving the text in the input field, and despite trying quite a few different methods I can't seem to get a result.
Code for Web page (not whole page but only concerned code)
<?php
$connect =mysqli_connect('localhost','root','','micaddy');
$id_query = mysqli_query($connect, "SELECT unique_id FROM users WHERE email = '{$_SESSION['login_user']}'");
$id_array = mysqli_fetch_assoc($id_query);
$uid = $id_array['unique_id'];
$result = mysqli_query($connect, "SELECT * FROM clubs WHERE user_id =
'$uid'");
?>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading clearfix"><h3 class="panel-title"><strong>Your Golfbag</strong><button type="button" class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#addModal">Add Club</button></h3></div>
<?php while($row=mysqli_fetch_assoc($result)):?>
&nbsp <span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong><?php echo $row['club_type'];?></strong></h3></div>
<div class="panel-body">
<form id="" method="POST" action="editClub.php">
<div class="form-group">
<label for="clubType">Club ID</label>
<input type="text" readonly="" class="form-control" id="inputClubType" value="<?php echo $row['id'];?>" name="clubIdInput">
</div>
<div class="form-group">
<label for="clubBrand">Type</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['club_type'];?>" name="clubTypeInput">
</div>
<div class="form-group">
<label for="clubBrand">Brand</label>
<input type="text" class="form-control" id="inputclubBrand" value="<?php echo $row['brand'];?>" name="clubBrandInput">
</div>
<div class="form-group">
<label for="clubNum">Number or Type</label>
<input type="text" class="form-control" id="inputclubNum" value="<?php echo $row['club_number'];?>" name="clubNumInput">
</div>
<div id="deleteClub">
<button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
<button type="button" class="btn btn-info btn-lg"><?php echo "<a href='editClub.php?id=".$row['id']."'>Save Changes</a>" ?></button>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</form>
</div>
</div>
</div>
<div class="col-md-5">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title"><strong>Club Image</strong></h3></div>
<div class="panel-body">
<div class="form-group">
<img src="club_images/<?php echo $row['clubImg']; ?>" class="img-rounded" width="250px" height="250px" alt="Image"/>
</div>
</div>
</div>
</div>
</div>
</div>
<span><?php if(isset($_SESSION['message'])){ echo $_SESSION['message']; unset($_SESSION['message']);} ?></span>
</div>
<?php endwhile;?>
</div>
</div>
</div>
</div>
The edit endpoint:
<?php
session_start();
$error='';
require_once '../include/DB_Functions.php';
$db = new DB_Functions();
if(empty($_POST['clubBrandInput']) || empty($_POST['clubNumInput'])){
$_SESSION['message'] = "Warning: Some fields are blank! Please try again";
header("Location: golfbag.php");
} else{
if(isset($_POST['clubBrandInput']) && isset($_POST['clubTypeInput']) && isset($_POST['clubNumInput'])){
$brand = $_POST['clubBrandInput'];
$type = $_POST['clubTypeInput'];
$num = $_POST['clubNumInput'];
$id = $_GET['id'];
$club = $db->editclub($brand, $type, $num, $id);
if($club) {
header("Location: golfbag.php");
$_SESSION['message'] = "Success! Details edited.";
}else{
header("Location: golfbag.php");
echo $error;
}
}
}
?>
The function method:
public function editClub($brand, $type, $num, $id){
$stmt = $this->conn->prepare("UPDATE clubs SET brand = '$brand', club_type = '$type', club_number = '$num' WHERE id = '$id'");
$result = $stmt->execute();
$stmt->close();
if($result){
$stmt = $this->conn->prepare("SELECT * FROM clubs WHERE user_id = ?");
$stmt->bind_param("s", $uid);
$stmt->execute();
$club = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $club;
}else{
return false;
}
}
You do not have a <form> defined in this HTML.
You are also clicking an anchor link <button id="submitChange" type="button" class="btn btn-danger btn-lg"><?php echo "<a href='deleteClub.php?id=".$row['id']."'>Delete</a>" ?></button>
even though it is in a button.
Therefore you will only pass the id=".$row['id']." parameter to the endpoint and that will be passed in the $_GET array and not the $_POST array

Categories