-2

I am really new to php and I am trying to use simple insert to my mysql database from the form.

I know that this mysql connection/insertion is dangerous and not used anymore. so can anyone please help me with this simple thing? I tried to google, but nothing is working so far :/

<? 
$text=$_POST['name']; 
$text=$_POST['surename'];

mysql_connect("localhost", "db_name", "pass") or die(mysql_error()); 
mysql_select_db("db_name") or die(mysql_error()); 
$result = mysql_query("INSERT INTO `table` (name, surename)
VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')");
if (!$result) {
    die('Invalid query: ' . mysql_error());     
}
?>
Robert
  • 7
  • 2
  • https://www.w3schools.com/php/php_mysql_insert.asp – Armin Aug 02 '18 at 10:00
  • *"I know that this mysql connection/insertion is dangerous and not used anymore"* then start learning useful and secure tools ! Documentation: [MySQLi](http://php.net/manual/en/book.mysqli.php) | [PDO](http://php.net/manual/en/book.pdo.php). Don't waste your time. – AymDev Aug 02 '18 at 10:02
  • 3
    **STOP** using deprecated `mysql_*` API. Use PDO or `mysqli_*`. and learn about prepared Statements to prevent SQL injection – Jens Aug 02 '18 at 10:02
  • 1
    Your query uses the variables called `$name` and `$surename`. But I can't see where you define those. Also, possibly related, you assign POST values to `$text` twice. – O. Jones Aug 02 '18 at 10:02
  • Possible duplicate of [How to change mysql to mysqli?](https://stackoverflow.com/questions/1390607/how-to-change-mysql-to-mysqli) – Nigel Ren Aug 02 '18 at 10:56

1 Answers1

0

Maybe change

$text=$_POST['name']; 
$text=$_POST['surename'];

to

$name = $_POST['name']; 
$surename = $_POST['surename'];

PS: And also your column names don't match your values. Your query, after inserting params

"INSERT INTO `table` (name, surename) VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')"

will probably look like this

INSERT INTO `table` (name, surename) VALUES (NOW(), 'Jhon', 'Wick')

As you can see there's name, surename (which probably should be surname) and (NOW(), 'Jhon', 'Wick'). So either add a column (if you have that column in your database):

INSERT INTO `table` (created_at, name, surename) VALUES (NOW(), 'Jhon', 'Wick')

or remove NOW() from your values

INSERT INTO `table` (name, surename) VALUES ('Jhon', 'Wick')
Theofanis
  • 523
  • 5
  • 15
Danon
  • 2,771
  • 27
  • 37