Using HTTP to Add files [closed] - php

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I'm using Luracast's Restler Framework which is great. But I was wondering if someone could tell me how I can upload files through HTTP.
I was using a simple HTML Form to POST data to the API, and trying to grabe the file information from $_FILES, but i'm not getting anything.
Here is my super simple form
<form method="post" action="index.php/product">
<p>
<label>Product name</label>
<input name="product_name" />
</p>
<p>
<label>MSRP Price</label>
<input name="msrp_price" />
</p>
<p>
<label>Category</label>
<input name="category_name" />
</p>
<p>Teir Pricing</p>
<p>
<label>Price</label>
<input name="price[]" />
</p>
<p>
<label>Buy Range Min</label>
<input name="buy_range_min[]" />
</p>
<p>
<label>Buy Range Max</label>
<input name="buy_range_max[]" />
<p>
<label>Price</label>
<input name="price[]" />
</p>
<p>
<label>Buy Range Min</label>
<input name="buy_range_min[]" />
</p>
<p>
<label>Buy Range Max</label>
<input name="buy_range_max[]" />
</p>
<p>
<label>Image</label>
<input type="file" name="image" />
</p>
<input type="submit" />
</form>
Here is my class that works with Restler
<?
class Product {
public $dp;
private $DBH;
public $highest_max = 0;
function __construct() {
$host = 'localhost';
$db_name = '';
$db_user = '';
$db_password = '';
try {
$this ->DBH = new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password);
// Line takes care of error reporting.
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e) {
// return $e->getMessage();
return 'Sorry there was an issue';
}
} // end function
function get($id=NULL) {
if (is_null($id)) {
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM products";
$data = array('product_id' => $id);
$STH = $this->DBH->prepare($sql);
// binds the params
$STH->execute($data);
// wHAT TYPE OF DATA WE ARE GRABING
$STH->setFetchMode(PDO::FETCH_ASSOC);
// GO TRough IT ALL
while($row = $STH->fetch()) {
$rows[] = $row;
} // end while
return $rows;
} // end if
else {
$sql = "SELECT * FROM products WHERE product_id = :product_id";
$data = array('product_id' => $id);
$STH = $this->DBH->prepare($sql);
// binds the params
$STH->execute($data);
// wHAT TYPE OF DATA WE ARE GRABING
$STH->setFetchMode(PDO::FETCH_ASSOC);
$row = $STH->fetch();
return $row;
} // end else
} // end function
function add_teir_pricing($price, $buy_range_min, $buy_range_max, $product_id) {
// check to see if the min is higher then this max
if ($buy_range_min >= $buy_range_max) {
throw new RestException(417,'Your min price teir must be smaller then your max' );
} // end if
elseif ($buy_range_min <= $this->highest_max) {
throw new RestException(417,'One of your minimum price teirs cannot overlap with another.' );
} // end if
$this->highest_max = $buy_range_max;
# the data we want to insert
$data = array( 'price' => $price, 'buy_range_min' => $buy_range_min, 'buy_range_max' => $buy_range_max, 'product_id' => $product_id );
$sql = "INSERT INTO teir_pricing (price, buy_range_min, buy_range_max, product_id, created) value (:price, :buy_range_min, :buy_range_max, :product_id, NOW())";
$STH = $this->DBH->prepare($sql);
$STH->execute($data);
} // end function
function post($product_id=NULL,$member_id, $product_name, $upc_code, $sku, $global_trade_item_number, $link_to_product_reviews,
$url_to_product,
$msrp_price,
$category_name, $price, $buy_range_min, $buy_range_max) {
// ADD PRODUCT
if (!isset($product_name)) {
$error = true;
// $errors['message'][] = 'Mising a product_name';
throw new RestException(417,'Mising a product_name');
} // end if
if (!isset($msrp_price)) {
$error = true;
// $errors['message'][] = 'Mising a msrp_price';
throw new RestException(417,'Missing MSRP price');
} // end if
if (!isset($category_name)) {
$error = true;
// $errors['message'][] = 'You must assign a category_name to this product';
throw new RestException(417,'You must assign a category_name to this product');
} // end if
// We still need to grab the member id from the key when this is added.
$member_id = 1;
$product_data = array('member_id' => $member_id,
'product_name' => $product_name,
'upc_code' => $upc_code,
'sku' => $sku,
'global_trade_item_number' => $global_trade_item_number,
'link_to_product_reviews' => $link_to_product_reviews,
'url_to_product' => $url_to_product,
'msrp_price' => $msrp_price,
'category_name' => $category_name);
$sql = "INSERT INTO
products
(product_name,
upc_code,
sku,
global_trade_item_number,
link_to_product_reviews,
url_to_product,
member_id,
msrp_price,
created,
category_name)
VALUES
(:product_name,
:upc_code,
:sku,
:global_trade_item_number,
:link_to_product_reviews,
:url_to_product,
:member_id,
:msrp_price,
NOW(),
:category_name
)";
$q = $this->DBH->prepare($sql);
$q->execute($product_data);
$product_id = $this->DBH->lastInsertId();
foreach($price as $key => $value) {
Product::add_teir_pricing($price[$key], $buy_range_min[$key], $buy_range_max[$key], $product_id);
} // end foreach
$response = array('product_id' => $product_id, 'status' => 'success', 'message' => 'Your product has been added', 'files' => $_FILES);
return $response;
} // end function
function upload_image($_FILES) {
return $_FILES;
} // end function
} // end class
?>

You can only upload files if the form data is sent as multipart/form-data. The default is application/x-www-form-urlencoded.
From the specification:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">

Related

Fatal Error:Maximum execution time of 120 seconds is exceeded

Error:
https://i.stack.imgur.com/ZZQkW.jpg
Fatal Error:Maximum execution time of 120 seconds is exceeded
The page loads very slowly.
The goal was to insert data and file to the table. But something does not let it. I will use my code as an example in this case.
So the user types their data here:
<?php
require_once $_SERVER["DOCUMENT_ROOT"] . "/tonevre/data_inc/functions.php";
use tonevre\general;
use tonevre\VideoUpload;
if(isset($_POST["addVideo"])) {
$videoUpload = new VideoUpload;
$response = $videoUpload->addVideo();
}
?>
<label>Name your video!</label>
<ul>
<input type="text" name="title" placeholder="Title" required>
<label>Description</label>
<input type="text" name="descrip" placeholder="Tell the viewers about your video" required>
<label>Upload your file</label>
<input type="file" name="image" required>
<button type="submit" name="addVideo">UPLOAD</button>
This data goes here (addVideo is a method from the class VideoUpload):
public function addVideo(){
#This will insert the data to the table called vidup
ini_set('max_execution_time', 0);
$title = $_POST["title"] ? $_POST["title"] : "";
$descrip = $_POST["descrip"] ? $_POST["descrip"] : "";
$image = $_FILES["image"]["name"] ? $_FILES["image"]["name"] : "";
$sql = "INSERT INTO vidup (title, descrip, image) VALUES (?, ?, ?)";
$paramType = "sss";
$paramValue = array(
":title" => $title,
":descrip" => $descrip,
":image" => $image
);
$this->ds->prepare($sql, $paramType, $paramValue);
$this->ds->execute($sql, $paramType, $paramValue);
// if the title is empty echo the error message
if(empty($title)) {
$response["status"] = "error";
$response["message"] = "Please enter a title";
return $response;
}
if(empty($paramValue)) {
$response["status"] = "error";
$response["message"] = "There is a problem";
return $response;
}
I will also mention this, for more details:
public function prepare($query, $paramType, $paramArray)
{
$stmt = $this->conn->prepare($query);
$this->bindQueryParams($stmt, $paramType, $paramArray);
$stmt->execute();
return $stmt;
header("location: ../header.php");
}
public function bindQueryParams($stmt, $paramType, $paramArray = array())
{
ini_set('memory_limit', '-1');
$paramValueReference[] = &$paramType;
for ($i = 0; $i < count($paramArray); $i++) {
$paramValueReference[] = &$paramArray[$i];
}
call_user_func_array(array(
$stmt,
'bind_param'
), $paramValueReference);
}
I couldn't find any solid enough explanation for the cause. A good explanation would help me and others in the future. Thank you.

Checkbox not updating SQL query on button press using PHP

With this code, it can retrieve the values from the database with a checkbox on each row. What I want for it to do is to update the unchecked values (namely 0) in the database with 1 for each checkbox checked.
Here's the query for the database and some sample rows.
CREATE TABLE IF NOT EXISTS `job_order` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`SI_no` varchar(12) NOT NULL DEFAULT '1',
`Date_Issued` date NOT NULL,
`Date_completed` date DEFAULT NULL,
`checked` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO `job_order` (`ID`, `SI_no`, `Date_Issued`, `Date_completed`,
`checked`) VALUES
(1, '2', '2018-12-19', '2018-12-26', 1),
(2, '5', '2018-11-06', '2018-12-04', 1),
(3, '7', '2018-12-01', '2018-12-13', 0),
(4, '8', '2018-12-20', '2018-12-12', 0);
COMMIT;
db_c.php - the class file
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'db_name' );
class db_c{
public $mysqli;
function __construct() {
$this->mysqli = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$this->mysqli){
die('Could not Connect My Sql:' .mysql_error());
}
}
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($order['order-complete'])){
foreach($order['order-complete'] as $ids){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `ID` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $id);
if($stmt->execute()){
array_push($processed, $id);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
function return_orders(){
$orders = array();
$sql = "SELECT `ID`, `SI_no`, `date_issued`, `date_completed`, `checked` FROM `job_order` WHERE `checked` != 1";
if($stmt = $this->mysqli->prepare($sql)){
if($stmt->execute()){
$stmt->bind_result($ID, $SI_no, $date_issued, $date_completed, $checked);
$stmt->store_result();
while($stmt->fetch()){
$orders[$ID]['SI_no'] = $SI_no;
$orders[$ID]['Issued'] = $date_issued;
$orders[$ID]['Completed'] = $date_completed;
$orders[$ID]['Checked'] = $checked;
}
return $orders;
}else{
return 1;
// failed to execute
}
}else{
return 0;
// failed to prepare
}
}
function orders_2_table(){
$unchecked = $this->return_orders();
if(is_array($unchecked) && !empty($unchecked)){
//returned results, build rows
$table = '';
foreach($unchecked as $id => $dets){
$table .= '<tr><td>'.$dets['SI_no'].'</td><td>'.$dets['Issued'].'</td><td>'.$dets['Completed'].'</td><td><input type="checkbox" name="order-complete[]" value="'.$id.'" /></td></tr>';
}
return array('Rows'=>$table, 'Count'=>count($unchecked));
}elseif(!is_array($unchecked)){
if($unchecked === 0){
return array('Rows'=>'<tr><td colspan="3">Error (SQL) </td></tr>', 'Count'=>0);
}else{
return array('Rows'=>'<tr><td colspan="3">Error (EXE) </td></tr>', 'Count'=>0);
}
}else{
return array('Rows'=>'<tr><td colspan="3">All Orders Completed </td></tr>', 'Count'=>0);
}
}
}
?>
I'm mostly having problems with the function complete_orders, which doesn't return anything on button press of the submit button. Nor does it check if the checkboxes are ticked.
Here's the HTML layout file
jobrequestfilter.php
<?php
session_start();
include 'db_c.php';
$dbc = new db_c();
$msg = '';
if(isset($_POST) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST);
if(is_array($process) && !empty($process)){
$msg = '<tr><td colspan="3">Successfully Processed '.count($process).' Orders</td></tr>';
}
else{
echo '<script>console.log("Nothing processed at jobrequestfilter")</script>';
}
}
$data = $dbc->orders_2_table();
?>
<html>
<head>
<meta charset="utf-8">
<title>Job Request Chart</title>
</head>
<body>
<div id="navbar">
<div id ="wrap">
<div class="logo"></div>
<img id="b" class="b">
</div>
</div>
<form action="" method="post">
<div id="filterby">
<input type="submit" id="Email" class="requestbutton" name="Email" value="Email">
</div>
</form>
<form method="post" enctype="multipart/form-data">
<table id ="jobtable">
<tr><th>SI no.</th><th>Date Issued</th><th>Date Started </th><th>Approve?</th></tr>
<?php echo $msg ?>
<?php echo $data['Rows'] ?>
<tr><td colspan="2"><input type="submit" name="process_orders" value="Process Orders" /></td><td>Count:<?php echo $data['Count'] ?></td></tr>
</table>
</form>
</body>
</html>
The isset button returns the echo statement I put, however, most seems to be working fine except for the process order button. Is it wise to just use javascript for the checkbox on update?
Try this one
db_c.php
It should not be
$order['order-complete']
But
$orders
Because the array variable name from post already stored in variable $orders.
It should not be
$id
But
$ids
Because you declare it as
foreach($orders as $ids)
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'your_db_name' );
class db_c{
public $mysqli;
function __construct() {
$this->mysqli = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$this->mysqli){
die('Could not Connect My Sql:' .mysql_error());
}
}
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($orders)){
foreach($orders as $ids){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `id` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $ids);
if($stmt->execute()){
array_push($processed, $ids);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
function return_orders(){
$orders = array();
$sql = "SELECT `ID`, `SI_no`, `date_issued`, `date_completed`, `checked` FROM `job_order` WHERE `checked` != 1";
if($stmt = $this->mysqli->prepare($sql)){
if($stmt->execute()){
$stmt->bind_result($ID, $SI_no, $date_issued, $date_completed, $checked);
$stmt->store_result();
while($stmt->fetch()){
$orders[$ID]['SI_no'] = $SI_no;
$orders[$ID]['Issued'] = $date_issued;
$orders[$ID]['Completed'] = $date_completed;
$orders[$ID]['Checked'] = $checked;
}
return $orders;
}else{
return 1;
// failed to execute
}
}else{
return 0;
// failed to prepare
}
}
function orders_2_table(){
$unchecked = $this->return_orders();
if(is_array($unchecked) && !empty($unchecked)){
//returned results, build rows
$table = '';
foreach($unchecked as $id => $dets){
$table .= '<tr><td>'.$dets['SI_no'].'</td><td>'.$dets['Issued'].'</td><td>'.$dets['Completed'].'</td><td><input type="checkbox" name="order-complete[]" value="'.$id.'" /></td></tr>';
}
return array('Rows'=>$table, 'Count'=>count($unchecked));
}elseif(!is_array($unchecked)){
if($unchecked === 0){
return array('Rows'=>'<tr><td colspan="3">Error (SQL) </td></tr>', 'Count'=>0);
}else{
return array('Rows'=>'<tr><td colspan="3">Error (EXE) </td></tr>', 'Count'=>0);
}
}else{
return array('Rows'=>'<tr><td colspan="3">All Orders Completed </td></tr>', 'Count'=>0);
}
}
}
?>
jobrequestfilter.php
3.It should not
if(isset($_POST) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST);
It should be
if(isset($_POST['order-complete']) &&
isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST['order-complete']);
<?php
session_start();
include 'db_c.php';
$dbc = new db_c();
$msg = '';
if(isset($_POST['order-complete']) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST['order-complete']);
if(is_array($process) && !empty($process)){
$msg = '<tr><td colspan="3">Successfully Processed '.count($process).' Orders</td></tr>';
}
else{
echo '<script>console.log("Nothing processed at jobrequestfilter")</script>';
}
}
$data = $dbc->orders_2_table();
?>
<html>
<head>
<meta charset="utf-8">
<title>Job Request Chart</title>
</head>
<body>
<div id="navbar">
<div id ="wrap">
<div class="logo"></div>
<img id="b" class="b">
</div>
</div>
<form action="" method="post">
<div id="filterby">
<input type="submit" id="Email" class="requestbutton" name="Email" value="Email">
</div>
</form>
<form method="post" enctype="multipart/form-data">
<table id ="jobtable">
<tr><th>SI no.</th><th>Date Issued</th><th>Date Started </th><th>Approve?</th></tr>
<?php echo $msg ?>
<?php echo $data['Rows'] ?>
<tr><td colspan="2"><input type="submit" name="process_orders" value="Process Orders" /></td><td>Count:<?php echo $data['Count'] ?></td></tr>
</table>
</form>
</body>
</html>
Please replace below complete_orders function code
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($orders['order-complete'])){
foreach($orders['order-complete'] as $id){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `ID` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $id);
if($stmt->execute()){
array_push($processed, $id);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
Two problem in code:
Function argument $orders you are passing but while process you using order. So it's was not going inside into loop
in foreach iteration your are using ids but while updating query you using id. so change variable accordingly. Please check

Can't insert text with apostrophe [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I can't insert the text from textarea when the text has apostrophe please sir's how to fix it.
this my whole code. I try mysqli_real_escape_string but it gives a error.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
$speakerid = $_SESSION['speakerid'];
$speaker_info = "SELECT * FROM speakers WHERE id=$speakerid";
$si_result = mysqli_query($conn, $speaker_info);
$array = mysqli_fetch_array($si_result);
$dbfullname = $array['speaker_fullname'];
$dbimage = $array['speaker_image'];
$dbspecialization = $array['speaker_specialization'];
$dbdescription = $array['speaker_description'];
$dbpaymentcost = $array['speaker_paymentcost'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Speaker</title>
</head>
<body>
<form action="updateSpeaker.php" method="post" enctype="multipart/form-data">
<textarea name="description" class="inputbox" cols="60" rows="5" autofocus required="required" maxlength="2000" style="resize:none;" placeholder="Description"><?php echo htmlspecialchars($dbdescription);?></textarea>
<br>
<input name="update" id="buttonsubmit" type="submit" value="Update">
</form>
<?php
if(isset($_POST['update']))
{
$newdescription = $_POST["description"];
$finaldescription = $mysqli_real_escape_string($conn, $newdescription);
$update_data = "UPDATE speakers SET speaker_fullname = '".$_POST["fullname"]."', speaker_description = '$finaldescription', speaker_specialization = '".$_POST["specialization"]."', speaker_paymentcost = '".$_POST["paymentcost"]."' WHERE id=$speakerid";
mysqli_query($conn, $update_data);
}
?>
</body>
</html>
Prepared statement:
$update_data = "UPDATE speakers SET speaker_fullname=?, speaker_description=?, speaker_specialization=?, speaker_paymentcost=? WHERE id=?";
$stmt = mysqli_prepare($conn, $update_data);
mysqli_stmt_bind_param($stmt, 'ssssd', $_POST["fullname"], $finaldescription, $_POST["specialization"], $_POST["paymentcost"], $speakerid);
Your current code is also mixing OOP and procedural based functions, so it will not work even once you have fixed the original issue with quoting user input.
I have converted your code into PDO (untested), which should point you in the right direction. Hope it helps.
<?php
session_start();
// config holder
$config = [
'db' => [
'host' => 'localhost',
'user' => 'root (DONT USE ROOT)',
'pass' => '',
'name' => 'srdatabase',
]
];
// connect to database
try {
$db = new PDO(
"mysql:host=" . $config['db']['host'] .";dbname=". $config['db']['name'],
$config['db']['user'],
$config['db']['pass'],
array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
} catch (PDOException $e) {
exit('Could not connect to database.');
}
// check id, though should be getting this from a $_GET
if (empty($_SESSION['speakerid']) || !is_numeric($_SESSION['speakerid'])) {
exit('Invalid speaker id');
}
// handle post
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = [];
// check or set inbound variables
$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$description = isset($_POST['description']) ? $_POST['description'] : null;
// you could set errors here if there empty, but lets continue
/*
if (empty($description)) {
$errors['description'] = 'Description is a required field.';
}
*/
if (
empty($errors) && // check for no errors
!empty($id) && // not required if you checked above, check id is not empty
!empty($description) // not required if you checked above, check description is not empty
) {
// prepare query for update, only want to update description
try {
$stmt = $db->prepare('
UPDATE speakers
SET speaker_description = :description
WHERE id = :id
');
// bind inbound variables to the query, then execute
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
$errors['query'] = 'Error updating database: '.$e->getMessage();
}
}
}
// select current row based upon the id
$stmt = $db->prepare('SELECT * FROM speakers WHERE id = :id LIMIT 1');
$stmt->bindParam(':id', $_SESSION['speakerid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
/* would contain
$result['speaker_fullname'];
$result['speaker_image'];
$result['speaker_specialization'];
$result['speaker_description'];
$result['speaker_paymentcost'];
*/
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Speaker</title>
</head>
<body>
<?php if (!empty($errors['query'])): ?>
<?= $errors['query'] ?>
<?php endif ?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $_SESSION['speakerid'] ?>">
<textarea name="description" class="inputbox" cols="60" rows="5" autofocus required="required" maxlength="2000" style="resize:none;" placeholder="Description"><?= htmlentities($result['speaker_description']) ?></textarea>
<?php if (!empty($errors['description'])): ?>
<span style="color:red"><?= $errors['description'] ?></span>
<?php endif ?>
<br>
<input name="update" id="buttonsubmit" type="submit" value="Update">
</form>
</body>
</html>

Textarea not reading any input

The textarea is not reading any input that is typed into the box. Initially, I was using PHP to check if the textarea was empty, and was recieveing an error there. So I removed that check, to see if it was php that was causing the issue, and added the required="required" attribute to the textarea tag, and even that is coming back with Please fill out this field. I am not quite sure where I am going wrong with my code, I had it working previously, then all of a sudden it stopped working, and I am completely confused as to why. I also looked at various other posts about the textarea not submitting, and ensured that I was checking the post with the name, not the ID; and making sure the textarea was submitting to the same form as the submit button. I have also tried it without specifying the form on the textarea tag.
HTML Code:
<form action="" method="post" id="CreateTopicForm">
<input type="hidden" name="create-topic" />
<span class="secondary radius label"><strong>Title</strong></span>
<input type="text" name="title" id="title" />
<span class="secondary radius label"><strong>Message</strong></span>
<textarea name="content" id="content" required="required" form="CreateTopicForm"></textarea>
<?php if($_SESSION['user']['account_type'] >= 3): ?>
<span class="secondary radius label"><strong>Sticky Topic</strong></span>
<input type="checkbox" name="sticky" /><br />
<?php endif ?>
<input type="submit" value="Post Topic" class="topic-post" />
</form>
PHP Code:
/* Retrieve necessary variables */
$fid = $_GET['fid'];
/* Get Forum Information */
$query = "SELECT * FROM bkg_forums where forum_id = :id";
$query_params = array(
':id' => $fid
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch(PDOException $e) {
$error[] = $pdoerror;
}
$forum = $stmt->fetchAll();
/* Begin the database upload */
if(!empty($_POST)){ /* Plan to change to if($_REQUEST['submit']) */
/* Check if data was actually submitted */
$db->beginTransaction();
/* DO SOME ERROR CHECKING. MAKE SURE FIELDS ARE NOT EMPTY. */
if(empty($_POST['title'])){
$error[] = "Sorry! You must enter a title!";
}
/* Previously had a check if $_POST['content'] */
/* GENERATE SOME VARIABLES NEEDED TO INSERT INTO TABLES. ACCOUNT_TYPE IS TEMPORARY*/
if($_SESSION['user']['account_type'] == 0) {
$account_type = "Normal";
$color = "white";
} elseif($_SESSION['user']['account_type'] == 1) {
$account_type = "Donator";
$color = "#F4FA58";
} elseif($_SESSION['user']['account_type'] == 2) {
$account_type = "Moderator";
$color = "#2EFE2E";
} elseif($_SESSION['user']['account_type'] == 3) {
$account_type = "Community Manager";
$color = "#0000FF";
} elseif($_SESSION['user']['account_type'] == 4) {
$account_type = "Administrator";
$color = "#DF0101";
}
if(isset($_POST['sticky'])){
$sticky = 1;
} else {
$sticky = 0;
}
if(!isset($error)){
/* INSERT INTO TOPICS TABLE */
$query = "INSERT INTO bkg_topics (
forum_id,
icon_id,
topic_approved,
topic_title,
topic_text,
topic_poster_id,
topic_poster,
topic_poster_color,
topic_post_time,
topic_status,
topic_type
) VALUES (
:forumid,
:iconid,
:topicapproved,
:topictitle,
:topictext,
:topicposter_id,
:topicposter,
:topicposter_color,
:topicpost_time,
:topicstatus,
:topictype
)";
$query_params = array(
':forumid' => $fid,
':iconid' => 1,
':topicapproved' => 1,
':topictitle' => $_POST['title'],
':topictext' => $_POST['content'],
':topicposter_id' => $_SESSION['user']['id'],
':topicposter' => $_SESSION['user']['displayname'],
':topicposter_color' => $color,
':topicpost_time' => time(),
':topicstatus' => 0,
':topictype' => $sticky
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastid = $db->lastInsertId();
/* Retrieve the last id of a topic, used to generate some links. */
/* UPDATE FORUM TABLE */
$query = "UPDATE bkg_forums SET
`forum_last_post_id` = :lastpostid,
`forum_last_post_topic_id` = :lastposttopicid,
`forum_last_post_title` = :lastposttitle,
`forum_last_poster_id` = :lastposterid,
`forum_last_post_time` = :lastposttime,
`forum_last_poster_name` = :lastpostername,
`forum_last_poster_color` = :lastpostercolor
WHERE `forum_id` = :forumid
";
$query_params = array(
':lastpostid' => null,
':lastposttopicid' => $lastid,
':lastposttitle' => $_POST['title'],
':lastposterid' => $_SESSION['user']['id'],
':lastposttime' => time(),
':lastpostername' => $_SESSION['user']['displayname'],
':lastpostercolor' => $color,
':forumid' => $fid
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
if($fid == 13){
$query = "INSERT INTO updates (
title,
content,
`date`,
`user`,
`topic_id`
) VALUES (
:title,
:content,
:date_posted,
:user_posted,
:topic_id
)";
$query_params = array(
':title' => $_POST['title'],
':content' => $_POST['content'],
':date_posted' => time(),
':user_posted' => $_SESSION['user']['displayname'],
':topic_id' => $lastid
);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
try {
$db->commit();
$post_ok = 1;
} catch(PDOException $e) {
$erroradmin[] = $e->getMessage();
$db->rollback();
}
if(isset($post_ok)): ?>
<script>
location.href = "http://www.boundlessknights.com?viewtopic&fid=<?php echo $fid; ?>&tid=<?php echo $lastid; ?>";
</script>
<?php else: ?>
<?php $error[] = "Your topic did not post."; ?>
<?php endif; ?>
<?php
}
}
?>
Questions I looked at:
Form Post Not Reading Any Value
Cannot Get the Value of a Textarea via Post Method
Textarea Not Posting with Form
Textarea Returns Empty Value in PHP Post
TinyMCE does not keep the underlying textarea in sync at all times. Normally, when you post the form, TinyMCE will update the textarea before the form is posted but the process seems to be stopped by the required attribute. You can use the following API call to force TinyMCE to update the textarea:
tinymce.triggerSave();
This will force TinyMCE to update the textarea when its called. You can either:
Do this in the onsubmit event of the form
Do this in the TinyMCE init:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});
Your page is using TinyMCE editor. It is giving the following error in the console: An invalid form control with name='content' is not focusable.
Fixing that will fix your problem.
Hmmm, did you try to remove this "form" attribute from your Textarea ?
<textarea name="content" id="content" required></textarea>
Tell us what it do when u try.
Change this
<textarea name="content" id="content" required="required" form="CreateTopicForm"></textarea>
to this
<textarea name="content" id="content" required="required" ></textarea>
You might not be able to post anything because you've NOT specified the action attribute of your form.
<form action="" method="post" id="CreateTopicForm">
Set it to the name of the php file (with the proper path to the file),
and it should work.
Note: To make sure the the $_POST array contains your form submitted values, do a var_dump($_POST).

jQuery-File-Upload blueimp PHP-MySQL-database-update data

how to make changes to the data 'title' and 'description' after the image is loaded, for example, add a button to "change"?
This is all done up and running
https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-MySQL-database-integration
Here is my code, but here it is necessary to make a new method to "upgrade" and synchronize it with html:
html:
name <br /><input name="title[]" value="{%=file.title||''%}">
description<br /> <input name="description[]" value="{%=file.description||''%}">
php:
public function update($print_response = true) {
$response = parent::update(false);
foreach ($response as $name => $update) {
if ($update) {
$sql = 'update set `title`=? ,`description`=? '
.$this->options['db_table'].'` WHERE `name`=?';
$query = $this->db->prepare($sql);
$query->bind_param('sss',$file->title,$file->description, $name);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}
JS?

Categories