php forum not detecting new line upon submission - php

I am trying to set up a feature very similar to a forum, where users can write chapters or stories (long sections of text). This text is then to be stored on mysql so that it can be recalled an read and commented on etc. This is all set up and works fine, however when a new line is typed by the user, it is not recognized. So the user may type -
This is para 1
This is para 2
But all that is displayed is -
This is para1This is para 2
I know that there are certain character is html and php such as or \n, but the people using the forum will not be savvy enough to do this. Is there a way that I can get this working automatically?
Below is the code for my add_topic.php
<?php
session_start();
$uname = $_SESSION['uname'];
$host="mysql.******************.co.uk"; // Host name
$username="**********"; // Mysql username
$password="************"; // Mysql password
$db_name="************_members"; // Database name
$tbl_name="forum_question"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['username'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, datetime)VALUES('$topic', '$detail', '$name', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
?>
Currently the 'details' field on the database is set to MidText. I have also tried MidBlob but there is no change in the result.
The following is my create_topic.php code -
<?php
session_start();
$uname = $_SESSION['uname'];
?>
<table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form id="form1" name="form1" method="post" action="add_topic.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3" bgcolor="#E6E6E6"><strong>Create New Story</strong> </td>
</tr>
<tr>
<td width="14%"><strong>Title</strong></td>
<td width="2%">:</td>
<td width="84%"><input name="topic" type="text" id="topic" size="50" /></td>
</tr>
<tr>
<td valign="top"><strong>Story</strong></td>
<td valign="top">:</td>
<td><textarea maxlength="2000000" name="detail" cols="50" rows="30" id="detail"></textarea></td>
</tr>
<tr>
<td><strong>Username</strong></td>
<td>:</td>
<td><input name="username" value="<?php echo $uname; ?>" type="text" id="username" size="50" readonly></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
I am an absolute beginner but I will try my best to make heads or tales of any advice that can be given. If you need anymore info please let me know.
Many thanks in advance.

Have you tried using nl2br before display? It will transform all the \n character to html <br/>.
See also the docs: http://php.net/manual/en/function.nl2br.php

Please try
$detail=htmlentities($_POST['detail']);
to get special HTML characters transformed in your database.
Hope that helps.
For further info go to http://php.net/manual/en/function.htmlentities.php

Related

inserting values in to database only once

<?php if(isset($_POST['submit']))
{
$tadd=$_POST["tadd"]; //getting values
$pname=$_POST["pname"];
$date=$_POST["date"];
$result=mysql_query("insert into pannel(tadd,pname,date)values('$tadd','$pname','$date')");
echo "<script type='text/javascript'>
alert('Quotation Generated Successfully!')
</script>";
} ?>
<center>
<h1>Title</h1>
</center>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5"
cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date"
id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center"><input type="submit" name="submit"
value="submit"/></td> </tr></center> </table> </form>
I have one record in my database with
id tadd pname date
1 hello vvv 22/10/2014
if i insert values into database again it should data already inserted
please help me regarding this issue
You can achieve this using mysql_num_rows() which is one way to do this, which I believe the goal is to avoid duplicates.
Sidenote: You can also set your column(s) as UNIQUE to avoid duplicates.
N.B.: I used the pname column as an example. It's up to you to check which one will always be unique in regards to a username for instance.
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
}
Do sanitize your data:
$tadd = mysql_real_escape_string($_POST["tadd"]);
and do the same for the others.
Even better, use mysqli with prepared statements, or PDO with prepared statements.
They're much safer, because your present code is open to SQL injection.
Footnotes:
You should get rid of onSubmit="submit;" in your form. As outlined in comments, it's not going to do anything.
Edit:
<?php
// assuming DB connection has been made.
if(isset($_POST['submit'])) {
$tadd= mysql_real_escape_string($_POST["tadd"]);
$pname= mysql_real_escape_string($_POST["pname"]);
$date= mysql_real_escape_string($_POST["date"]);
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
exit;
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
echo "<script type='text/javascript'>alert('Quotation Generated Successfully!')</script>";
}
} // brace for if(isset($_POST['submit']))
?>
<!DOCTYPE html>
<head></head>
<body>
<center><h1>Title</h1></center>
<form method="post" action="">
<div align="center">
<center>
<table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5" cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date" id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center">
<input type="submit" name="submit" value="submit"/>
</td> </tr>
</table>
</center>
</div>
</form>
</body>
</html>

PHP UPDATE script not working

I'm trying to implement an update script on my page but it doesn't work.
I have 2 pages, the 'update.php' page and the 'update_ac.php' page that runs the script after hitting 'submit' on the Form, the code is as below:
update.php
On this page i have this error : Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\update.php on line 16
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="764503"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$result=mysql_query("SELECT * FROM produse WHERE id='$id'");
$rows=mysql_fetch_array($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update data in mysql</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>titlu</strong></td>
<td align="center"><strong>stare</strong></td>
<td align="center"><strong>pret</strong></td>
<td align="center"><strong>descriere</strong></td>
</tr>
<tr>
<td> </td>
<td align="center">
<input name="titlu" type="text" id="titlu" value="<? echo $rows['titlu']; ?>">
</td>
<td align="center">
<input name="stare" type="text" id="stare" value="<? echo $rows['stare']; ?>" size="15">
</td>
<td>
<input name="pret" type="text" id="pret" value="<? echo $rows['pret']; ?>" size="15">
</td>
<td>
<input name="descriere" type="text" id="descriere" value="<? echo $rows['descriere']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
// close connection
mysql_close();
?>
update_ac.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="764503"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE produse SET titlu='$_POST[titlu]' ,stare='$_POST[stare]' ,pret='$_POST[pret]' ,descriere='$_POST[descriere]' WHERE id='$_POST[id]'";
$result=mysql_query($sql);
// if successfully updated.
if($result)
{
echo "Successful";
}
else
{
echo "ERROR";
}
?>
mysql_query return FALSE when error occurs instead of returning an Array, this test avoid a second (and bigger) error : if FALSE no problem, if an Array you can fetch it ;oP
if ($result) $rows=mysql_fetch_array($result);
This probably means you have an error in your query. If you have an error in your query, it doesnt create a resource to get your data from.
to find an error: add or die(mysql_error()) to your mysql_query command. so you can find out the error.
You have error in your update sql query in the update_ac.php file. So nothing is probably getting updated. You are using the array indexes wrong in the following statement:
$sql="UPDATE produse SET titlu='$_POST[titlu]' ,stare='$_POST[stare]' ,pret='$_POST[pret]' ,descriere='$_POST[descriere]' WHERE id='$_POST[id]'";
$_POST[titlu] should be $_POST['titlu'], $_POST[stare] should be $_POST'stare'] and so on. So the correct query can be as below:
$sql="UPDATE produse SET titlu='".$_POST['titlu']."' ,stare='".$_POST['stare']."' ,pret='".$_POST['pret']."' ,descriere='".$_POST['descriere']."' WHERE id='".$_POST['id']."'";

php mysql simple update: cannot read values

probably stupid question but...
I have a sample for PHP and MySQL, which doesn't work...
there are 3 php files:
list_records.php
update.php
update_ac.php
the problem is that 3rd one doesn't read variables from the 2nd. What am I doing wrong?
Here are my files/code:
list_records.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td colspan="4"><strong>List data from mysql </strong> </td>
</tr>
<tr>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['name']; ?></td>
<td><?php echo $rows['lastname']; ?></td>
<td><?php echo $rows['email']; ?></td>
<td align="center">update</td>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
<?php
mysql_close();
?>
update.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update data in mysql</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<tr>
<td> </td>
<td align="center">
<input name="name" type="text" id="name" value="<?php echo $rows['name']; ?>">
</td>
<td align="center">
<input name="lastname" type="text" id="lastname" value="<?php echo $rows['lastname']; ?>" size="15">
</td>
<td>
<input name="email" type="text" id="email" value="<?php echo $rows['email']; ?>" size="15">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<?php echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
// close connection
mysql_close();
?>
update_ac.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET name='TEST', lastname='$lastname', email='$email' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
u need to get the value in the server side from client side before inserting or updating them into the database.for this we have superglobal variables in php like $_GET,$_POST,$_REQUEST etc.
so include thses in your update_ac.php:
$lastname=$_POST[lastname];
$email=$_POST[email];
$id=$_POST[id];`
you can use $_REQUEST method if you are not sure by which method u passed the values from the form.but try to avoid it as it is less secure.
You need to get them from POST in the update_ac.php file like
$sql="UPDATE $tbl_name
SET name='TEST',
lastname='".$_POST['lastname']."',
email='".$_POST['email']."'
WHERE id=".$_POST['id'];
This is what you need in your update query
......lastname='".$_POST['lastname']."', email='".$_POST['email']."' WHERE id=".$_POST['id']
Whenever a form posts/submits a value to a file mentioned in an action, the file must access the values of form's field's name in $_POST array as $_POST['lastname'], $_POST['email']. etc. (if the method used is POST in form tag)
There are three ways of access submitted values:
GET http://php.net/manual/en/reserved.variables.get.php
POST http://php.net/manual/en/reserved.variables.post.php
REQUEST http://php.net/manual/en/reserved.variables.request.php

Updating data using PHP Edit form help needed

i am trying to update my table with the correct information linking to the follwing ID. I will have posted the code so you can all take a look.
Here is my problem: Once i submit the form with all the details recieved from the database, everything works successfull. But when i click submit it re-directs to my other page called update_ac.php. Everything works fine, apart from the data in the mysql tables do not get updated.
I wonder if anyone could take a look at the code to see what they think:much appreciated and feedback would be fantastic. PS I am not the best PHP programmer, still learning!
So here is edit.php - where teh user edits their information:
<?php
session_start();
$UserName = $_SESSION['UserName'];
require("checkLoginSession.php");
$adminid = $_GET['id'];
//CONNECTION CODE WAS HERE
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
echo("Logged In As: $UserName");
echo "<br />";
echo("We are editing Data for ID: $adminid");
echo "<br />";
echo "<a href=test.php>Go back to panel</a>";
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM admin WHERE id='$id'";
$result=mysql_query($sql) or die(mysql_error());
$rows=mysql_fetch_array($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update data in mysql</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Main Content</strong></td>
</tr>
<tr>
<td> </td>
<td align="center"><input name="name" type="text" id="name" value="<? echo $rows['name']; ?>"></td>
<td align="center"><input name="mainContent" type="text" id="mainContent" value="<? echo $rows['mainContent']; ?>" size="15"></td>
</tr>
<tr>
<td> </td>
<td><input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>"></td>
<td align="center"><input type="submit" name="Submit" value="Submit"></td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?
mysql_close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Page</title>
</head>
<body>
<h2>Edit Page (<?php echo ("$adminid"); ?>)</h2>
</body>
</html>
And here is the update_ac.php:
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$firstName = $_POST["name"];
$mainText = $_POST["mainContent"];
$sql="UPDATE admin SET name='$firstName', mainContent='$mainText' WHERE id='$id'";
$result=mysql_query($sql) or die(mysql_error());;
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='test.php'>Back to panel</a>";
}
else {
echo "ERROR";
}
?>
OK GUYS EDIT HERE:
If in the Update_ac.php if i change the following line to this:
$sql="UPDATE admin SET name='$firstName', mainContent='$mainText' WHERE id='1'";
The information now gets updated, therefore means something is going wrong with my ID variable
Looks like the typical omission of database escaping. You need to apply mysql_real_escape_string on any string that you concat in your sql query.
The lazy version is:
$_POST = array_map("mysql_real_escape_string", $_POST);
$firstName = $_POST["name"];
$mainText = $_POST["mainContent"];
Otherwise you will oftentimes get an invalid syntax error. Use print mysql_error(); after the query to find out what went wrong in your case.
See also String escaping for each database or read up on pdo for less fiddly database interaction.
From just a quick glance, it's because you are using variables and not the $_POST variables
$sql="UPDATE admin SET name='$firstName', mainContent='$mainText' WHERE id='$id'";
Should be the post variables with the names of your form fields
$sql="UPDATE admin SET name='$_POST['firstName'], mainContent='$_POST['mainText']' WHERE id='$_POST['id']'";
If you then put your $id variable within a hidden input field within your form, that file will also pick it up.
Just a quick answer cos' I'm out to get lunch.
It is just a syntax error in the update_ac.php
You used 2 semicolons in the following line
$result=mysql_query($sql) or die(mysql_error());;

How to insert data in database using php

I have just started to work with php. I write a simple code in php to insert data in a table customer. I am using mssql database.
<?php
function InsertData()
{
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mysql_query($sql, $link);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close();
echo "Data successfully inserted";
}
?>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td colspan="3" height="12" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Company Website:</td>
<td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>
</tr>
<tr>
<td > </td>
<td > <input type="button" value="submit" id="imgBtnSubmit" click="InsertData()"/> </td>
</tr>
</table>
I have written above code to insert data into the table and I am calling InsertData function on onClick event of submit button but on clicking button data is not getting inserted into the table. Please anyone tell me where is the problem in this code.
There are a few problems with your code.
You're missing the <form> as pointed out by Tudor Constantin.
The other problem is that you can't use the onclick event of an element to trigger PHP code as you're done above. The onclick event is for JavaScript (or other client side scripting languages like VBScript).
Additionally, make sure that you use the functions that start with mssql and not mysql if you use Microsoft SQL Server. The functions are not interchangeable.
Here's a short example:
<?php
// The request method is POST.
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
// Connect to the database
$link = mssql_connect('db','123','test');
// Do more stuff with the database.
}
?>
<form method="POST" action="/path/to/this/file.php">
<input type="text" name="example" />
<input type="submit" value="Send" />
</form>
When you click the "Send" button, the form will be POSTed to /path/to/this/file.php. By checking that the request method is "POST", you can then connect to the database and insert records accordingly.
Checking for $_SERVER['REQUEST_METHOD'] is one of many ways you can do this. You could also check that a value for an particular input was set using if ( ! empty($_REQUEST['input_name']) ) { ... }.
As the previous answer states, you don't actually have submission logic. What's at least equally important is that you, by your own admission, do not have a MySQL server. MySQL and MS-SQL are different and not at all equivalent. You can't use PHP MySQL commands or the MySQL extension to talk to MS-SQL.
You're using MS-SQL functions here:
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
and then MySQL here:
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mysql_query($sql, $link);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close();
echo "Data successfully inserted";
...and, as yet another answer states, you're trying to use Javascript to call a PHP function.
You therefore have two three problems - well, technically one problem. I suggest you read a FAQ on MS-SQL in PHP at the very least, and ideally complete Javascript and PHP tutorials. There is no way that we can provide an answer that you can use short of writing your program for you, as you - and I swear I'm not being unpleasant here, I know you're doing your best - just don't have the knowhow to put it together yet. Google is your friend here. Good luck.
As many have already mentioned there are a few errors in your code. My solution to your question offers a different approach.
Rather than calling the InsertData() method you can do something else in the one php document.
This is done by using an if/else statement, assigning 'submit' to the name value of the submit button as well as the special PHP variable $_SERVER['PHP_SELF'].
First, the server checks if the form has been submitted.
When the page is first loaded this will return false and the form is displayed for them to fill out
When the user clicks the submit button the form reloads the page and runs the PHP script again. This time the if statement returns true as the form HAS been submitted so it executes the part of the script that inserts the data in MSSQL and displays the successful message.
Check out the code below:
<?php
if (isset($_POST['submit'])){
//connect to the database
$link = mssql_connect('db','123','test');
//display error if database cannot be accessed
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
//assign form input to variables
$txtName = $_POST['txtName'];
$txtWebsite = $_POST['txtWebsite'];
//SQL query to insert variables above into table
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
//if the query cant be executed
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result);
mssql_close();
echo "Data successfully inserted";
}
else { ?>
<form name="input" action="$_SERVER['PHP_SELF']" method="POST">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%">Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td>Company Website:</td>
<td><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /></td>
</tr>
<tr>
<td><input type="button" name="submit" value="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Give that a try. There's some great PHP tutorials that go over the fundamentals here:
http://devzone.zend.com/article/627
Hope that all helped.
It looks like you don't have a <form> in your page - the data is not getting to your server.
Also, you are not reading the input anywhere - how do you fill your $txtName and $txtWebsite with meaningful values?
Also, InsertData is a PHP function, which is executed on the server side - your HTML part is interpreted on the client side (in the browser). You can't call that function there.
Try with this:
<?php
function InsertData()
{
$link = mssql_connect('db','123','test');
if (!$link || !mssql_select_db('php', $link))
{
die('Unable to connect or select database!');
}
$txtName = $_REQUEST['txtName'];
$txtWebsite = $_REQUEST['txtWebsite'];
$sql = " INSERT INTO customer ([Name],[Website])VALUES('$txtName','$txtWebsite')";
$result = mssql_query($sql, $link);
if(!$result)
{
echo mssql_error();
exit;
}
// close the connection
mssql_free_result($result);
mssql_close();
echo "Data successfully inserted";
}
if ($_REQUEST['txtName'] > ''){
InsertData();
}
?>
<form name="input" action="this_file_name.php" method="get">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td colspan="3" height="10" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Name:</td>
<td width="60%"><INPUT type="text" name="txtName" id="txtName" Width="200px" MaxLength="30" /> </td>
</tr>
<tr>
<td colspan="3" height="12" valign="top" width="98%"></td>
</tr>
<tr>
<td width="22%"> Company Website:</td>
<td width="60%"><INPUT type="text" name="txtWebsite" id="txtWebsite" width="200px" MaxLength="200" /> </td>
</tr>
<tr>
<td > </td>
<td > <input type="button" value="submit" id="imgBtnSubmit" /> </td>
</tr>
</table>
</form>

Categories