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?
Related
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.
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).
I can upload images as a serialized array no problem, but all I need is to store the raw filename string on my database and I'm not sure where to start editing my pre-existing code get this to work. This should be easier but as a PHP novice I can't get it to work.
Essentially, I want to be able to upload images then display them on the front end of my site doing something like this:
<img src="img/<php echo $config->photo_a ?>"/>
My existing code is:
<?php
//connect to db //
session_start();
include('../config.php');
// check for login to use //
if (!$user->authenticated)
{
header('Location: login.php');
die();
}
//post form as array using class photo_loader//
if (isset($post->form_action))
{
$a = new photo_loader(false, $db);
$a->name = $post->name;
$image_files = array();
for ($i=1; $i<10; $i++)
{
if (isset($_FILES['file'.$i]['name']) && $_FILES['file'.$i]['name'] != "")
{
$img = new upload($_FILES['file'.$i], M_ENV_SITE_URL, M_ENV_SITE_ROOT);
$img->set_upload_target("/img/");
$n = $img->do_upload();
if (!$n)
{
$err = "Image file ".$i." too big or wrong file type.";
}
else
{
$image_files[] = $n;
$img->batchResize("/img/", "/img/", $n, array("320x240", "800x600"));
}
}
}
if (empty($image_files)) $err = "You must include at least one image.";
$a->value = $image_files;
if (!$err)
{
$a->create();
$succ = "Success!";
}
}
?>
Using a simple form like this:
<form action="" method="post" enctype="multipart/form-data">
<div class="control-group"><label for="file" class="control-label">Attach Slideshow Images:</label><div class="controls">
<?php
for ($i=1;$i<10;$i++)
{
echo "<input name=\"file".$i."\" type=\"file\" value=\"\" id=\"file".$i."\" />";
} ?>
</div></div>
<input type="hidden" name="name" value="photo_a">
<div class="form-actions">
<input type="submit" name="form_action" class="btn btn-large btn-primary" value="Save" />
</div>
</form>
and photo_loader.class.php looks like this:
<?php
class photo_loader
{
private $properties;
var $db;
function __construct($id, $dbase)
{
$this->db = $dbase;
if (is_numeric($id))
{
$sql = sprintf(
"SELECT * FROM minty_config
WHERE ID=%d",
$this->db->clean($id)
);
$result = $this->db->query($sql);
$fields = $this->db->fetch_array($result);
foreach ($fields as $k => $v)
{
$this->properties[$k] = $v;
}
$this->value = unserialize($this->value);
}
}
function __get($k)
{
return $this->properties[$k];
}
function __set($k, $v)
{
$this->properties[$k] = $v;
}
function update()
{
$sql = sprintf(
"UPDATE minty_config SET
name='%s',
value='%s'
WHERE ID=%d",
$this->db->clean($this->name),
serialize($this->value),
$this->ID
);
$this->db->query($sql);
}
function create()
{
$sql = sprintf(
"INSERT INTO minty_config
(name, value)
VALUES('%s', '%s')",
$this->db->clean($this->name),
unserialize($this->value)
);
$this->db->query($sql);
}
function delete()
{
$sql = sprintf(
"DELETE FROM minty_config
WHERE ID=%d",
$this->ID
);
$this->db->query($sql);
}
}
?>
I presume I need to remove the $image_files = array(); section but I don't know what to replace with! Seemingly keep making mistakes and returning blank pages with errors or not uploading the image. I can't see it being too diffuclt but I presume I'm going the wrong way about it. Many thanks in advance!!
i want to update the fields below but my form is not working. it is not storing data what should i do. i used jquery accordion fo r the fields so it will click the item he wants to edit then update the fields then submit. but it is not working.
VIEW
foreach($people as $row){
echo "<h3>".$row->service."</h3>";
echo "<form action='".base_url()."some_controller/updateCI' method='post'> <div>Service ID: <input type=text name=id value='".$row->id."' size=27px/><br>Service Name: <input type=text name=name value='".$row->service."'><input type='button' class='classname' value='Save'/></form></div>";
}
?>
CONTROLLER
public function updateCI(){
$this->load->model('some_model');
$id = $this->input->post('id');
$servName = $this->input->post('name');
$success = $this->some_model->updateCI($id,$servName);
if($success == TRUE)
$this->editCI_page(TRUE);
else $this->editCI_page(FALSE);
}
MODEL
public function updateCI($id,$servName){
//$name = $this->db->escape_str($name);
$appID = $this->db->escape_str($id);
$ciName = $this->db->escape_str($servName);
$queryStr = "UPDATE appwarehouse.service SET id='$appID',service='$ciName' WHERE id = '$appID';";
$query = $this->db->query($queryStr);
return $query;
}
You can do something like this in your model:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
I would recommend you to use the active record which are available for codeigniter. For more information visit the below link:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
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">