Textarea not reading any input - php

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).

Related

Unable to save data with php

I want to save the data with php. The program does not return an error. But to the database does not record.
DOSYA ADI:signup.php
MY CODES:
<form action="islem.php" method="post">
Ad:<input type="text" name="bilgilerim_ad" placeholder="giriniz">
Soyad:<input type="text" name="bilgilerim_soyad" placeholder="giriniz">
Mail:<input type="text" name="bilgilerim_mail"placeholder="giriniz">
Yaş:<input type="text" name="bilgilerim_yas" placeholder="giriniz">
<button name="insertislemi" type="submit">Kayıt</button>
</form>
DOSYA ADI:config.php
MY CODES
<?php
include 'baglan.php';
if(isset($_POST['insertislemi'])){
$query = $db->prepare("INSERT INTO uyeler SET
bilgilerim_ad =: bilgilerim_ad,
bilgilerim_soyad =: bilgilerim_soyad,
bilgilerim_mail =: bilgilerim_mail,
bilgilerim_yas =: bilgilerim_yas,
");
$insert = $query->execute(array(
"bilgilerim_ad" => $_POST['bilgilerim_ad'],
"bilgilerim_soyad" => $_POST['bilgilerim_soyad'],
"bilgilerim_mail" => $_POST['bilgilerim_mail'],
"bilgilerim_yas" => $_POST['bilgilerim_yas'],
));
if ( $insert ){
$last_id = $db->lastInsertId();
print "insert işlemi başarılı!";
}
}
?>
MY CODES
CONNECTION FILE
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=test", "root", "");
//echo "giriş";
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
You first write bilgilerim_ad =: bilgilerim_ad, ... in your insert query, then "bilgilerim_ad" => $_POST['bilgilerim_ad'],.
There's a misplaced space, the datas are bound to bilgilerim_ad but you declared : bilgilerim_ad.
Replace your insert query by :
$query = $db->prepare("INSERT INTO uyeler SET
bilgilerim_ad = :bilgilerim_ad,
bilgilerim_soyad = :bilgilerim_soyad,
bilgilerim_mail = :bilgilerim_mail,
bilgilerim_yas = :bilgilerim_yas");
And bind your datas this way :
$insert = $query->execute(array(
":bilgilerim_ad" => $_POST['bilgilerim_ad'],
":bilgilerim_soyad" => $_POST['bilgilerim_soyad'],
":bilgilerim_mail" => $_POST['bilgilerim_mail'],
":bilgilerim_yas" => $_POST['bilgilerim_yas']));
This is out of topic, but in your php files where you are using only php code (the one that insert and the one that manage DB connection in example) do not close php tag ?>. This can send unwanted characters to http header

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>

Updating SQL with form and PHP. Values resetting to 0 on submit?

I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning PHP.
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: index.php");
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");

PHP update not working

I'm building a custom CMS and I've written a script that is supposed to edit already existing information in my database.
I've used the code for a different database before and it has worked without any troubles, but I've changed the index names to reference a new database and now it won't work.
The information is displayed on a page with an 'edit' button the links the user to a html form which displays the selected piece of info in a text box.
There's no problem displaying the info in the form, but once the submit button is pressed the code does not execute it, and the info is not updated and no error message is displayed..
so I'm fairly sure there's a problem somewhere in this... (Ignore the comments)
if (isset($_GET['edittimeslot']))
{
$timeslotid = $_GET['timeslotid'];
try
{
$sql = "SELECT timeslotid, Time FROM timeslots WHERE timeslotid = timeslotid" ;
//echo $sql;
$data = $pdo->query($sql);
$timeslots = $data->fetch();
//print_r($acts);
}
catch(PDOException $e)
{
echo "this didnt work" .$e->getMessage() ;
}
$pagetitle = 'Edit your date here';
$timeslotid = $timeslots['timeslotid'];
$time = $timeslots['Time'];
$button = 'Edit timeslot';
include 'timeslot.form.php';
exit();
}
// is all of the requested feilds appropiate
if (isset($_POST['submit']) && $_POST['submit'] == 'Edit timeslot')
{
// get the form data that was posted ready to insert into the stage database
$timeslotid = $_POST['timeslotid'];
$time= htmlspecialchars($_POST['time']);
try
{
// prepare the query to insert data into stages table
$sql = "UPDATE timeslots
SET Time = :Time,
WHERE timeslotid = :timeslotid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Time', $time);
$stmt->bindParam(':timeslotid', $timeslotid);
$stmt->execute();
}
catch(PDOException $e)
{
//error message goes here if the insert fails
}
}
HTML:
<!doctype html>
<head>
<style type="text/css">
.container {
width: 800px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1><?php echo $pagetitle;?></h1>
<form action='.' method='post'>
<!-- stage name -->
<p><label for='time'> What is the timeslots you would like to add? 00:00-00:00 </label></p>
<p><input type='text' name='time' id='time' value='<?php echo $time;?>'> </p>
<p><input type='submit' name='submit' value='<?php echo $button;?>'></p>
</form>
</div>
</body>
Shouldn't WHERE timeslotid = timeslotid be WHERE timeslotid = $timeslotid ?
Also, using a form value directly is a bad idea. Use it at least like $timeslotid = (int)$_GET['timeslotid'];.
Okay one thing that I see right away is this line:
$timeslotid = $_POST['timeslotid'];
Where is that form field in your form? I don't see it anywhere. Also try to assign the execution to a variable and var_dump it so you can see if it returns TRUE or FALSE:
$success = $stmt->execute();
var_dump($success);
Furthermore make sure that you DB column is named Time and not time with all lowercase.

Using HTTP to Add files [closed]

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">

Categories