0

This is script for sending messages to other users. Everything is OK but it doesnt save the input field values into the database. I am looking the code from 1 hour and I can't find the problem. 'to', 'subj', 'msg' come from the form.

<?php

include 'php/db_connect.php';

$name = $_SESSION['name'];

$to = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'to'))));
$sender = $name;
$subj = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'subj'))));
$msg = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'msg'))));

$errorTo = '';
$errorSubj = '';
$errorMsg = '';
$errorMain = false;

if (filter_input_array(INPUT_POST)) {

    if ($to === $name) {
        $errorTo = 'Не може да пращаш съобщение на себе си';
        $errorMain = true;
    }

    $checkTo = "SELECT user_name FROM users WHERE user_name='$to'";
    $resultCheck = mysqli_query($conn, $checkTo);
    $row = mysqli_fetch_array($resultCheck, MYSQLI_ASSOC);

    if (mysqli_num_rows($resultCheck) == 0) {
        $errorTo = 'Не съществува такъв потребител';
        $errorMain = true;
    }

    if (str_word_count($subj) > 20) {
        $errorSubj = 'Прекалено дълга тема за съобщение';
        $errorMain = true;
    }

    if (str_word_count($msg) > 300) {
        $errorSubj = 'Прекалено дълго съобщение';
        $errorMain = true;
    }

    if (!$errorMain) {
        $insertInDb = 'INSERT INTO msg (to, sender, subject, msg) VALUES ("$to", "$sender", "$subj", "$msg")';
        mysqli_query($conn, $insertInDb);
    }
}


?>
To. K
  • 55
  • 1
  • 3

1 Answers1

1

You use php variables into single quotes. Change string:

$insertInDb = 'INSERT INTO msg (to, sender, subject, msg) 
    VALUES ("$to", "$sender", "$subj", "$msg")';

to

$insertInDb = "INSERT INTO msg (to, sender, subject, msg) 
    VALUES ('$to', '$sender', '$subj', '$msg')";
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46