how to insert data in database using textarea in php?

Alvi picture Alvi · Sep 12, 2016 · Viewed 10.4k times · Source

i am using text area in my code to insert data in database. but there is some confusion in my code. when i click at submit button, text in textarea disappear and not saved in database. this is my Code. Form Coding:

<form action="testing.php" method="post">
 <textarea name="text1" rows="10" cols=59></textarea><br>
 <input type="submit" name="submit" value="Add Record">
 <input type="reset" name="reset" value="Clear Text">
</form>

PHP Coding:

<?php 
$text1=mysql_real_escape_string($_POST['text1']);
// connection
$con=mysql_connect("localhost","root","") or die("connection error");
mysql_select_db("test") or die("database error");
//query...
$qry="INSERT INTO mytest(text1) values($text1)";
if(mysql_query($qry))
{
echo "Record have been saved...";
}
else
{
echo "Not Saved";
}
?>

Answer

Object Manipulator picture Object Manipulator · Sep 12, 2016

You need to wrap it within quotes. Also, it would be better if you use some debugging along with it.

$qry = sprintf("INSERT INTO mytest (text1) VALUES ('%s') ", $text1);

if (mysql_query($qry)) {
    echo "Record have been saved...";
} else {
    echo "There was an error:".mysql_error();
}

Note: The mysql extension is deprecated. Use mysqli or PDO instead.