Saving text area into mySQL database field PHP - php

Hi i am using openWYSIWYG as a text editor for a text area. I then am trying to post the contents of the text area to a field in my database.
This is the code i have so far -
<?php
$text = $_GET['Comments'];
mysql_connect ("localhost", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("databasename") or die ('Data error:' . mysql_error());
$query="INSERT INTO KeepData (player_data)VALUES ('$text')";
mysql_query($query) or die ('Error updating database' . mysql_error());
?>
I can connect to the database, and when i click submit it adds a blank entry into the field? how would i get it so it keeps all the formatted data?
Many thanks
update
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea id="Comments" name="Comments">
example text
</textarea>
<input type="submit" name="mysubmit" value="Save Post" />
</form>
DIM3NSION

Try something like the following:
<?php
if ($_POST['submit']) {
mysql_connect ("localhost", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("databasename") or die ('Data error:' . mysql_error());
$text = mysql_real_escape_string($_POST['comments']);
$query="INSERT INTO KeepData (player_data) VALUES ('$text')";
mysql_query($query) or die ('Error updating database' . mysql_error());
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea name="comments">Example Comment</textarea>
<input name="submit" type="submit" value="submit" />
</form>

You must save an format coded version elsewhere on a hidden textarea (much like here on StackOverflow, if you type **text** it will come out as text, in the database, they probably save it as **text** and render it with PHP.
Once the formatted version is saved, render it with PHP when you get the data from the database.

Is your form POSTing or GETing (you said POSTing in your post)? You have $_GET['Comments'], but if your form's action is POST, you need to use $_POST['Comments'];
if you add echo $text;exit; after you assign $text, do you see anything?

You should use mysql_escape_string function because of mysql injection and if text contains ' you'll get error.

Check if your have <form action='get'>. If it is just <form> get used by default
Check that your wisywig have name='Comments' attribute.
Escape the $text with mysql_real_escape_string. It can contain SQL-illegal symbols, like '. This function escapes them with \
(recommendation) do not use mysql_*, it is deprecated of PHP 5.3 and will be removed.
(recommendation) appending user input to sql query is always a risk of SQL-injection. Use prepared statements

just add the onclick event something like
<button onclick=" $('#txtEditor').val($('.Editor-editor').html());" type="Publish" id="Publish" name="Publish" class="btn btn-primary">Publish</button>
remember the #txtEditor has to match with the form id, this works well, and note the .html will save it to database with the color,Bold and many more effect if you added any (that is the wysiwyg fuction)
then for your php code that send to database, do something like this
$anything = ($_POST['txtEditor']);
$anything you which to use as variable,dont forget the txtEidtor is the form id. with this your wysiwyg is up and working.

Related

Updating database based on certain ID

I have a table within my database containing subscriptions, each subscription has a name, id and a notes column.
I'm trying to allow the user to update the notes column through a text area on the webpage. All of the subscriptions are in a list on the page which allows the user to click on them to view that specific subscription.
How would I make sure the note that is updated is correct with the id of the subscription they have clicked on?
I currently have this code.
<form method="POST" action="noteAction.php">
<textarea id="notes" name="noteValue">$notes</texarea>
<input type="submit" name="submit"/>
</form>
This is what I think my noteAction.php should look like however I cannot get it working.
mysql_connect ("host", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("database_name") or die ('Data error:' . mysql_error());
$text = mysql_real_escape_string($_POST['noteValue']);
$query="UPDATE `subscription` SET `notes`= '$text' WHERE `id` = '$id'";
mysql_query($query) or die ('Error updating database ' . mysql_error());
Any help would be great, thanks.
Use hidden element to store your id inside it.
<form method="POST" action="noteAction.php">
<textarea id="notes" name="noteValue">$notes</texarea>
<input type="hidden" name="id" value="id" value="your id goes here" />
<input type="submit" name="submit"/>
</form>
When you're putting the note in the form, you must have an id for that note kicking about somewhere, after you retrieved it from the database. If you only selected the note contents in that query, select the ID as well. Then pass the ID over in a hidden field, and you have the ID to use in the MySQL query (which is correct).
<input type="hidden" name="note-id" value="note_id_here">

PHP FORM INSERT INTO not inserting records

I'm working on a Uni assignment and am having trouble inserting records to MySQL database using a form. My set up is below.
I can view entries in the database with no problem. I'm new to this so sorry in advance :(
conninfo.php
<?php
$strServer="localhost";
$strDatabase="djdatabase"; // CHANGE TO YOUR DATABASE NAME HERE
$strUser="root";
$strPwd=""; // Leave blank for WAMPServer
$strDB=mysql_connect($strServer,$strUser,$strPwd)or die("Could not open database");
$database=mysql_select_db("$strDatabase",$strDB);
?>
addnewdata.php
<?php include "conninfo.php";
$newdj=$_POST["dj"]; //pick up from form
$newfn=$_POST["fn"];
$newem=$_POST["em"];
$newwe=$_POST["we"];
$newpi=$_POST["pi"];
$newev=$_POST["ev"];
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";
mysql_query($query);
header("location:showall.php");
?>
enternewdata.php
<?php include "conninfo.php";?>
<html>
<head>
</head>
<body>
<form action="addnewdata.php" method="post">
DJ Name:<input type="text" name="dj"><br>
FirstName: <input type="text" name="fn" /><br>
Email: <input type="text" name="em" /><br>
Website: <input type="text" name="we" /><br>
Picture: <input type="text" name="pi" /><br>
EventID: <input type="text" name="ev" /><br>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Many Thanks for your help :)
had better use SET command to insert data
$query = "INSERT INTO dj SET
DJName=".$newdj.",
FirstName=".$newfn.",
Email=".$newem.",
Website=".$newwe.",
Picture=".$newpi.",
EventNumber=".$newev."";
$save = mysql_query($query);
if($save){
header("location:showall.php");
}else{
die(mysql_error());
}
You are missing a quote ' wich is causing the error that you cannot see because you haven't done any debug. Anyway you should just change to this
'$newwe', '$newpi', '$newev')"; //a quote was missing after '$newv
I would suggest you to also debug query by adding or die('INVALID QUERY: ' . mysql_error());
so code would look like
mysql_query($query) or die('INVALID QUERY: ' . mysql_error());
Since you said this is an university test I don't know if you are supposed to use mysql_* function (wich are deprecated), but I would strongly reccommend to switch to mysqli or PDO if you can for security reason.
You missed ' on your query on $newev that gives you an error
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";

How to get a HTML Form to query and produce results from Mysql datebase

I have created a form that has one text field and one select box, I also have created a button. Now what I want to happen is when the button is pressed I want the string in the forms to be matched up to my database and then I want the results of those matches to be returned and shown on the screen.
For example if I was to type 'History' into my text field box and I also selected 'level 2' from my select box when the button (Submit Button) was pressed I would want returned on the page everything that matches up with the word history and the selection of level 2 in my database.
I know that I have to connect my page with my Database through PHP and I have successfully done that, but what I don't understand is how to then get my HTML Form to Query the database and provide results back onto the screen
In terms of a example website that is very similar to the concept I would like to create take a look at this webpage. http://search.ucas.com/cgi-bin/hsrun/search/search/search.hjx;start=search.HsSearch.run?y=2013&w=H (UCAS Course Search) this website has multiple text fields and select boxes and a submit button exactly as I am trying to create and the results provided are only the results that match with what has been searched.
The code below works in terms of it links my text-field to my database but I can't get my text-field and my select box to link and query the database, only one or the other. I want them both to work from the same button (search button)
<form method="post" action="Webpage here" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<form id="form1" name="ExamBoard" method="post" action="Webpage here">
<label for="select"></label>
<select name="ExamBoard" id="select">
<option value="EB1" selected="selected">EB1</option>
<option value="EB2">EB2</option>
<option value="EB3">EB3</option>
</select>
<input type="submit" name="submit" value="Search">
</form>
<p> </p>
<p>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("Name", "User", "Password*") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("Table Name");
//-query the database table
$sql="SELECT ID, CourseName, ExamBoard FROM subjects WHERE CourseName LIKE '%" . $name . "%' ";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$CourseName =$row['CourseName'];
$ID=$row['ID'];
$ExamBoard=$row['ExamBoard'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$CourseName . " " . "</li>\n" ;
echo $ExamBoard . " " . "</a>\n";
echo "</ul>";
}
}
}
}
?>
New HTML File
newHTML.htm
<form method="post" action="Webpage here" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form
New PHP file
newPHP.pfp
<?php
if(preg_match("/^[ a-zA-Z]+/", $_REQUEST['name'])){
$name=$_REQUEST['name'];
//connect to the database
$db=mysql_connect ("Name", "User", "Password*") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("Table Name");
//-query the database table
$sql="SELECT ID, CourseName, ExamBoard FROM subjects WHERE CourseName LIKE '%" . $name . "%' ";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$CourseName =$row['CourseName'];
$ID=$row['ID'];
$ExamBoard=$row['ExamBoard'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$CourseName . " " . "</li>\n" ;
echo $ExamBoard . " " . "</a>\n";
echo "</ul>";
}
?>
You have to ask yourself Do you want to do this with AJAX or with normal screen refreshes..
With normal screen refreshes (The easy way)
Take your HTML and place it in one file (HTMLfile.html)
Take your PHP and place it in another file (PHPCode.php)
HTML file form calls the PHP script from action attribute.
PHP file renders the response.
Dont mash up the view and the controlling application.
There is other ways to do this in one script if you want to use AJAX.

Saving to MySQL database via html forms

I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>

Setting value in mysql table using html button

I got a table with dynamic data with 5 td-s. First one is for the ID, second one for date, third for the name of the author, fourth for some properties and in the last one i got two buttons. I want them to change the value of the $status in applications table. For that I made 2 php files in which I added the mysql update function for each of the buttons. But I don't know why when I press the buttons it does everything in the php except it doesn't change the value of $status. Please let me know where I am wrong and how can I make it work. Thanks in advance.
The html code of the buttons (the last td):
<form action="status1.php">
<input type="submit" name="approve" value=" + ">
</form>
<form action="status2.php">
<input type="submit" name="refuse" value=" - ">
</form>
The PHP code for the buttons - status1.php (status2.php is the same but it changes the $status value to 2 instead of 1)
<?php
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_query('set names windows-1251', $link);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$id=$_GET['id'];
$qry="UPDATE applications SET status=1 WHERE id='$id'";
$result = mysql_query($qry);
if($result) {
header("location: applications.php");
exit();
}
else {
die("Query failed");
}
?>
You are using $_GET['id'] as identifier, but as far as I can see in the code, you are not actually sending any GET information apart from the submit button itself. So your query is currently actually updating the row WHERE id=''. That's why you don't get errors, but you don't get your desired result either.
Change the action parameter of your form to status1.php?id=$id, or add something like <input type="hidden" name="id" value="$id"/> inside the form.
Well, are you getting any errors? Comment out the header("location: applications.php"); line so you will see if it throws any. Also try adding something like echo $qry so you can visually verify that the query is correct.
Also, you should read up on SQL injection and how to protect against it. Directly sticking user input into the query like that can open the door to nastiness. Also, you aren't checking user input for apostrophes which can break your query. I personally use PDO, which makes it a lot easier and a bit safer.
Another suggestion, rather than having to maintain two separate submission PHP files, just put your two submit buttons like this:
<input type="submit" name="status" value=" + ">
<input type="submit" name="status" value=" - ">
Then change the form action to the name of the consolidated php file and in that file, just evaluate the value of the status like:
$status = 0;
if ($_GET["status" == " + ") $status = 1;
If you install PDO, you'd do the meat of the DB update like this:
$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_DATABASE, DB_USER, DB_PASSWORD);
$sql = $pdo->prepare("UPDATE applications SET status=? WHERE id=?");
$sql->execute(array($status, $_GET["id"]));
..which would be a little safer than what you're doing now.
Disclaimer: I'm just a hobbyist PHP programmer, so there may be better ways than I've mentioned :)
use this instead of ur form tag
for form 1
<from method="get" action="status1.php">
<input type="hidden" name="id" value="1"/>
<input type="submit" name="approve" value=" + "/>
</form>
for form2
<from method="get" action="status2.php">
<input type="hidden" name="id" value="2"/>
<input type="submit" name="refuse" value=" - "/>
</form>

Categories