I'm trying to write to a database using CKEditor.. when I press submit it dies and says localhost is currently unable to handle this request.
HTTP ERROR 500
I only want to save the textarea into a row in database so I can then read the row on to another page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>Classic editor replacing a textarea</title>
<script src="http://cdn.ckeditor.com/4.6.0/standard-all/ckeditor.js"></script>
</head>
<body>
<form id="editor1" action="save.php" method="post" >
<textarea cols="80" id="editor1" name="editor1" rows="10">
</textarea>
<p>
<input type="submit" value="Submit">
</p>
</form>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</body>
</html>
PHP script
<?php
if(isset($_POST['submit']))
{
// Putting data from form into variables to be manipulated
$text = $_POST['editor1'];
$conn = mysql_connect("localhost","root","root") or die ("Can't connect");
mysql_select_db("managerMessage",$conn);
// Getting the form variables and then placing their values into the MySQL table
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
}
?>
You are not concatenating the value correctly in this statement and also text data in a query like this should be wrapped in quotes
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
This is a corrected verion of your code
mysql_query("INSERT INTO text
(textarea)
VALUES ('" . mysql_real_escape_string($text) . "')");
A simpler piece of code would be to read and probably maintain would be
$t = mysql_real_escape_string($text);
mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
I would be remiss if I did not remind you that
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
EDIT RE: not saving the data to the database
Add some error checking to your code like so:
$t = mysql_real_escape_string($text);
$result = mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
if ( ! $result ) {
echo mysql_error();
exit;
}
Once you know the error, if one exists, you can start work on fixing it.
Related
I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>
<?php
include 'connect.php';
?>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user- scalable=no"/>
</head>
<title>Test Sign Up</title>
<body>
<header>
<h1>Test Sign Up</h1>
</header>
<div class="contactform">
<form action="testinsert.php" method ="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter
your name here" required>
<label for="testsentence">Test Sentence:</label>
<input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>
<label for="course">Course:</label>
<select id="course" name="course">
<?php
$query = "SELECT CourseID FROM Course";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo "<option>" . $row['CourseID'] . "<option>";
}
mysqli_close($conn);
?>
</select>
<button type="submit" name="submit">Submit</button>
</form>
</div>
<p></p>
View Courses
<p></p>
Return to home page
</body>
</html>
Testinsert.php -
<?php
include 'connect.php';
$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';
$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";
if (mysqli_query($conn, $sql)) {
echo "<p></p>New record added successfully";
echo '<p></p>Return to home page';
} else {
echo "<p></p>Error adding record";
echo '<p></p>Return to home page';
}
mysql_close($conn);
?>
You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag. / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
echo "<option>{$row['CourseID']}</option>";
}
The option tags still render even if you don't properly close them. In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
echo "<option>{$row['CourseID']}</option>";
}
About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts. Not once. Furthermore, the php manual has a specific Warning stating:
Warning
Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).
There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data. DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];
You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query. There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.
Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.
I want to insert date into database using php here is my php code and html input date tag
<form action="try.php" method="post">
<input type="date" name="date" id="date" />
<input type="submit" name="submit" id="sub" />
</form>
<?php
if(isset($_Post['submit'])){
$see = $_POST['date'];
$insert_c = "insert into test(date) values ($see)";
$run = mysql_query($insert_c);
}
}
?>
i have a suggestion for you. you can use mysqli_query insted of mysql_query.
i think if you use mysql_query that is really nota good practice.
here the date will be in the format of mm/dd/yy so you need to give the same type in the database to i mean in phpmyadmin. or you can save the date in database by making the date field as varchar..
INSERT INTO test.date (id, date) VALUES ('1', '22/07/2017');
one more thing while you executing the query you have to pass the connection object too
example: mysql_query( $query, $conn );
I use the following code
NOTE: Whenever your redirecting to the same page in the form action please use the following code <?php echo $_SERVER['PHP_SELF'] ?> this specifies that you want to redirect to the same page. Instead of leaving the action blank or putting the same name as that of the current page.
One problem might be check your column data type it must of type date
For Eg the table must look something like this
CREATE TABLE IF NOT EXISTS `test` (
`created_date` date NOT NULL
)
And the following code does the job for inserting into that.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
/* Her I am including my db_connect file which has db connection resource */
include_once ('db_connect.php');
/* User filter_input instead of $_POST */
$createdDate = filter_input(INPUT_POST,'createdDate');
/* Query to insert into test table */
$result = mysqli_query($link, "INSERT INTO test (created_date) VALUES ('".$createdDate."')");
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insert Date</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label>Created Date<label/>
<input type="date" name="createdDate"><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
I have a form I made using HTML/PHP, And I would like it to submit to the database; I have a movies website and I am currently working on the admin panel, I want it to have a form that adds new movies to the site, I tried out my form, but nothing goes to the database. The connection with the database is fine and the queries look fine to me, I honestly do not know what the problem is.
P.S. I am making it in Arabic, the Arabic writing does not mean anything..
PHP/HTML code:
<?php
session_start();
include('php/config.php');
if($_SESSION['username'] != true){
header('Location: http://www.domain.com/');
}
//this form allows to choose what to do (e.g. add new movie)...
else{
echo'
<head>
<link rel="stylesheet" href="css/main.css" />
<link rel="stylesheet" href="css/admin.css" />
<meta charset="utf-8"/>
<title>Admin Panel v1.0</title>
</head>
<ul class="management-b">
<li>إضافة فيلم جديد</li>
<li>إضافة مسلسل جديد</li>
<li>مسح فيلم/مسلسل</li>
</ul>
';
}
//this form adds new movies...
connectDB();
$genreQuery = mysql_query("SELECT genre FROM Genres");
echo'
<head>
<link rel="stylesheet" href="css/main.css"/>
<link rel="stylesheet" href="css/admin.css"/>
<meta charset="utf-8" />
</head>
<form method="post" id="new-movie">
عنوان الفيلم:<input type="text" class="new-movie-title" name="new-movie-title" /><br/><br/>
وصف الفيلم:<textarea class="new-movie-desc" name="new-movie-desc" cols="50" rows="7"></textarea><br/><br/>
نوع الفيلم:<select class="new-movie-genre" name="new-movie-genre">';
while($options = mysql_fetch_array($genreQuery, MYSQL_ASSOC)){
echo '<option>'.$options["genre"].'</option>';
}
echo'</select><br/><br/>
تاريخ الفيلم:<select class="new-movie-year" name="new-movie-year">';
for($years = 1995; $years<2017; $years++){
echo '<option>'.$years.'</option>';
}
echo'
</select><br/><br/>
رابط الفيلم:<input type="text" name="new-movie-link" class="new-movie-link"/><br/><br/>
صورة الفيلم:<input type="text" name="new-movie-img" class="new-movie-img" /><br/><br/>
تقييم imDB:<input type="text" name="new-movie-imdb" class="new-movie-imdb"/><br/><br/>
<input type="submit" name="new-movie-submit" class="new-movie-submit" value="إضافة الفيلم" />
</form>
';
if(isset($_POST['new-movie-submit'])){
connectDB();
$mNewTitle= $_POST['new-movie-title'];
$mNewDesc= $_POST['new-movie-desc'];
$mNewGenre= $_POST['new-movie-genre'];
$mNewYear= $_POST['new-movie-year'];
$mNewURL= $_POST['new-movie-link'];
$mNewIMG= $_POST['new-movie-img'];
$mNewIMDB= $_POST['new-movie-imdb'];
mysql_query("INSERT INTO Movies(title, description, genre, url, image, imdb, release-year) VALUES('$mNewTitle', '$mNewDesc', '$mNewGenre', '$mNewURL', '$mNewIMG', '$mNewIMDB', '$mNewYear'");
closeDB();
}
?>
If you checked for errors MySQL would tell you that you don't have a column identifier named year as release-year contains a dash in it which makes MySQL think you are subtracting the column identifier year from release. Wrap that column name in ticks to resolve this.
mysql_query("INSERT INTO Movies(title, description, genre, url, image, imdb, `release-year`) VALUES('$mNewTitle', '$mNewDesc', '$mNewGenre', '$mNewURL', '$mNewIMG', '$mNewIMDB', '$mNewYear'");
As mentioned in comments you are using an obsolete API as the mysql_* functions have all been removed from PHP in PHP 7 and you are wide open to SQL injections which is the most common form of web based attacks.
And as I mentioned before, you don't check for or handle errors. You would have caught this error quickly with basic error checking. You also need to be prepared for when errors happen or else your users will have a bad experience when an error occurs.
I am trying to change the contents of depending on the current option selected.
The getData(page) comes back correctly (onChange) but it just doesn't go over to the variable I get "Fatal error: Call to undefined function getData() in C:\xampp\htdocs\pdimi\admin\editpages.php on line 42"
EDIT: This is how I finished it!
Javascript:
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
Select form:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<select name="page" onChange="getData(this)">
<?php
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_POST['page']);
else
$page = '';
$query = "SELECT pageid FROM pages;";
?>
<option value="select">Select Page</option>
<option value="indexpage">Index Page</option>
<option value="starthere">Start Here</option>
</select>
Textarea:
<textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data">
<?php
if (isset($_GET['page'])) {
$sql1 = #mysql_query("SELECT * FROM pages WHERE pageid='".$_GET['page']."'") or die(mysql_error());
$sql2 = #mysql_fetch_array($sql1) or die(mysql_error());
if ($sql1) {
echo $sql2['content'];
}
}
?>
</textarea>
And that is that!
You cannot execute a Javascript function (client side) from PHP (which runs server side).
Also, you need to connect to a database server with user and password, and select a database. Do not use #, it will only prevent you from seeing errors -- but the errors will be there.
In the PHP file you need to check whether you receive a $_POST['page'], and if so, use that as the ID for the SELECT. You have set up a combo named 'page', so on submit the PHP script will receive the selected value into a variable called $_POST['page'].
Usual warnings apply:
mysql_* functions are discouraged, use mysqli or PDO
if you still use mysql_*, sanitize the input (e.g. $id = (int)$_POST['page'] if it is numeric, or mysql_real_escape_string if it is not, as in your case)
If you want to change the content of textarea when the user changes the combo box, that is a work for AJAX (e.g. jQuery):
bind a function to the change event of the combo box
issue a call to a PHP script server side passing the new ID
the PHP script will output only the content, no other HTML
receive the content in the change-function of the combo and verify success
set $('#textarea')'s value to the content
This way you won't have to reload the page at each combo change. Which reminds me of another thing, when you reload the page now, you have to properly set the combo value: and you can exploit this to dynamically generate the combo, also.
Working example
This file expects to be called 'editpages.php'. PHP elaboration is done (almost) separately from data presentation.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PDIMI - The Personal Development and Internet Marketing Institution</title>
<link href='http://fonts.googleapis.com/css?family=Oswald:400,300' rel='stylesheet' type='text/css' />
<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css' />
<link href="../style/default.css" rel="stylesheet" type="text/css" media="all" />
<!--[if IE 6]>
<link href="default_ie6.css" rel="stylesheet" type="text/css" />
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
function getData(combobox){
var value = combobox.options[combobox.selectedIndex].value;
// TODO: check whether the textarea content has been modified.
// if so, warn the user that continuing will lose those changes and
// reload a new page, and abort function if so instructed.
document.location.href = '?page='+value;
}
</script>
</head>
<?php include 'aheader.php';?>
<?php
error_reporting(E_ALL);
if (!mysql_ping())
die ("The MySQL connection is not active.");
mysql_set_charset('utf8');
// $_REQUEST is both _GET and _POST
if (isset($_REQUEST['page']))
$page = mysql_real_escape_string($_REQUEST['page']);
else
$page = False;
$query = "SELECT pageid, pagename FROM pages;";
$exec = mysql_query($query); // You need to be already connected to a DB
if (!$exec)
trigger_error("Cannot fetch data from pages table: " . mysql_error(), E_USER_ERROR);
if (0 == mysql_num_rows($exec))
trigger_error("There are no pages in the 'pages' table. Cannot continue: it would not work. Insert some pageids and retry.",
E_USER_ERROR);
$options = '';
while($row = mysql_fetch_array($exec))
{
// if the current pageid matches the one requested, we set SELECTED
if ($row['pageid'] === $page)
$sel = 'selected="selected"';
else
{
// If there is no selection, we use the first combo value as default
if (False === $page)
$page = $row['pageid'];
$sel = '';
}
$options .= "<option value=\"{$row['pageid']}\" $sel>{$row['pagename']}</option>";
}
mysql_free_result($exec);
if (isset($_POST['page_data']))
{
$page_data = mysql_real_escape_string($_POST['page_data']);
$query = "INSERT INTO pages ( pageid, content ) VALUES ( '{$page}', '{$page_data}' ) ON DUPLICATE KEY UPDATE content=VALUES(content);";
if (!mysql_query($query))
trigger_error("An error occurred: " . mysql_error(), E_USER_ERROR);
}
// Anyway, recover its contents (maybe updated)
$query = "SELECT content FROM pages WHERE pageid='{$page}';";
$exec = mysql_query($query);
// who says we found anything? Maybe this id does not even exist.
if (mysql_num_rows($exec) > 0)
{
// if it does, we're inside a textarea and we directly output the text
$row = mysql_fetch_array($exec);
$textarea = $row['content'];
}
else
$textarea = '';
mysql_free_result($exec);
?>
<body>
<div id="page-wrapper">
<div id="page">
<div id="content2">
<h2>Edit Your Pages Here</h2>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<form name="editpage" method="POST" action="">
<table border="1" width="100%">
<tr>
<td>Please Select The Page You Wish To Edit:</td>
<td>
<select name="page" onChange="getData(this)"><?php print $options; ?></select>
</td>
</tr>
<tr>
<td><textarea class="ckeditor" name="page_data" cols="80" row="8" id="page_data"><?php print $textarea; ?></textarea></td>
</tr>
<tr>
<td><input type="Submit" value="Save the page"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
The biggest issue that you have here, is that you need to learn the difference between client side and server side.
Server Side: As the page is loading... We run various code to determine what is going to be displayed and printed into the source code.
Client side: Once the page has loaded... We can then use DOM elements to interact, modify, or enhance the user experience (im making this up as i go along).
In your code, you have a PHP mysql command:
$thisdata = #mysql_query("SELECT * FROM pages WHERE pageid=".getData('value'));
1, Don't use mysql. Use mysqli or PDO
2, You have called a javascript function from your PHP.
There is absolutely no way that you can call a javascript function from PHP. The client side script does not exist and will not run until after the page has stopped loading.
In your case:
You need to server up the HTML and javascript code that you will be using. Once, and only when, the page has loaded, you need to use javascript (client side scripting), to set an event listener to listen for your select change event. Once this event is triggered, then you can determine what you want to do (ie change a textbox value, etc).
Before reading, please note that I am very new to both PHP and MYSQL. I have created a table in my MYSQL database. I would now like to 'spit out' this table onto a page through PHP. This part I seem to be okay with. After outputting the tables data into an HTML table, I would like to output an HTML form onto my page. So, I now have a table followed by a form. This form will contain a few text boxes that, when submitted, will post the data used to insert a new row into the preexisting table noted above.
All of the above code is currently in a PHP file named 'display.php'.
My Issue:
If the form described above is posting back to my 'display.php' file, after inserting a new row and displaying the new table information, what is stopping my code from inserting another new row full of NULL data? I'm sure I did a less than decent job of explaining this scenario so I will post some code.
HTML / PHP
<html>
<head>
<title>Html and PHP</title>
</head>
<body>
<!-- Form -->
<form action="insertdata.php" method="post">
Username: <input type="text" name="username" >
Hardware ID: <input type="text" name="hardwareid" >
<input type="submit" >
</form>
<?php
// Connect to MYSQL
$con = mysql_connect("localhost","blah","private");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("dbname", $con);
// Insert posted data into table
$sql="INSERT INTO tablename(
Username,
HardwareID)
VALUES
('$_POST[username]','$_POST[hardwareid]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record successfully added...";
mysql_close($con)
?>
</body>
</html>
Again, I am a complete beginner - and I understand this. I want to know, must the different parts of the above code be placed into multiple files? I don't want to have to go to a new address, which is why this is causing me so much confusion I'd say.
try some thing like this,
connection.php file
// Connect to MYSQL
$con = mysql_connect("localhost","blah","private");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("dbname", $con);
display.php file
<html>
<head>
<title>Html and PHP</title>
</head>
<body>
<!-- Form -->
<form action="process.php" method="post">
Username: <input type="text" name="username" >
Hardware ID: <input type="text" name="hardwareid" >
<input type="submit" >
</form>
</body>
</html>
process.php file
include_once("ur_file_dir/connection.php");
if ((isset($_POST['username']) && isset($_POST['hardwareid'])) {
$sql="INSERT INTO tablename(
Username,
HardwareID)
VALUES
($_POST['username'],$_POST['hardwareid'])";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record successfully added...";
mysql_close($con)
}
You should validate your input, ie:
if (!empty($_POST['username'] && !empty($_POST['hardwareid']) {
// do your insert here
}
Also, you should be wary of allowing user input to be inserted directly into your query, as this leaves your open to SQL injections. A better way to do this is to use PDO and prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php