-1

I am trying to make INSERT INTO work.

if (isset ($_POST['send']) ){
mysql_query('INSERT INTO msg (message, receiver, sender) VALUES ("'.$_POST["message"].', '.$_GET["user"].', '.$sendernick["nick"].'") ');
}

I tried to echo every single variable and they appear. But this inserting adds nothing to my database. Did i mess up something here?

To see errors I added this but nothing appear:

error_reporting(E_ALL); 
ini_set('display_errors','1');
Helloitsme
  • 23
  • 6
  • 1
    are you connected to a database? also, your VALUES are basically one long string. you need to examine those quotes – Kai Qing Oct 29 '14 at 00:22
  • Two things: 1. Your query may be vulnerable to SQL injection attacks. [Read this](http://bobby-tables.com) for information about what they are and how to prevent them. 2. Don't use `mysql_`, use `mysqli_` – Barranka Oct 29 '14 at 00:23

2 Answers2

1

You forgot the double quotes:

mysql_query( 'INSERT INTO msg (message, receiver, sender) VALUES ( "'.$_POST["message"].'", "'.$_GET["user"].'", "'.$sendernick["nick"].'" )' );

Also, read about parameter binding and sql injection How can I prevent SQL injection in PHP?.

Community
  • 1
  • 1
Danijel
  • 12,408
  • 5
  • 38
  • 54
1

You should avoid using the mysql_* functions as they are deprecated and will not be supported any more! Please consider using PDO instead, as it provides a common way to connect to all types of databases. Mysqli_* functions are an option as well, but that will limit you to just using MySQL.

Here is an example of how to use PDO and get your query working using prepared statements:

// connect.php
$db_host = '127.0.0.1'; 
$db_user = 'user';      
$db_pass = 'pass';
$db_name = 'database_name';
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_pass);

// the-script-youre-posting-to.php
require('connect.php');

$message = $_POST['message'];
$receiver = $_GET["user"];
$sender = $sendernick["nick"];

// Using prepared statements almost eliminates the possibility of SQL Injection.
$stmt = $db->prepare("INSERT INTO msg(message, receiver, sender) VALUES (:message, :receiver, :sender)");
$stmt->bindParam(':message', $message);
$stmt->bindParam(':receiver', $receiver);
$stmt->bindParam(':sender', $sender);
$stmt->execute();

For more information regarding prepared statements, have a look at the PHP manual.

tftd
  • 16,203
  • 11
  • 62
  • 106