Help
cancel
Showing results for 
Search instead for 
Did you mean: 
Copilot Lvl 2
Message 1 of 2

data is not inserted to the MySQL database

hi all.

please help me out with my issue. I'll be happy as hell :)

 

I've tried to make a block for comments on my website.


steps to reproduce:
1. I've created a table in MySQL database:

> CREATE TABLE `messages` (
> `id` int(3) NOT NULL AUTO_INCREMENT PRIMARY KEY,
> `author` varchar(30) NOT NULL,
> `message` text NOT NULL,
> `date` varchar(25) NOT NULL
> ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

 

2. here is the form:

<form name="sendMessage" action="sendMessage.php" method="post">
  <p>
    <label>Имя:</label>
    <input type="text" name="author" />
  </p>
  <p>
    <label>Комментарий:</label>
    <br />
    <textarea name="message" cols="50" rows="10"></textarea>
  </p>
  <p>
    <input type="submit" value="Отправить" />
  </p>
</form>
 

3. sending data to database (sendMessage.php file):

<?php

$author = $_POST["author"];

$message = $_POST["message"];

$date = date;


$author = htmlspecialchars($author);
$message = htmlspecialchars($message);

$mysqli = new mysqli("my hostName", "my userName", "my password", "my databaseName");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
   }

$mysqli->query("INSERT INTO `messages` (`author`, `message`, `date`) VALUES (`$author`, `$message`, `$date`)");

?>

 

 

actual result: nothing is stored to the database

software: php v.7.3

additional information: the thing is, that there are no errors in the Console or Network (DevTools)

 

1 Reply
Highlighted
Commander Lvl 2
Message 2 of 2

Re: data is not inserted to the MySQL database

I'd start by checking the result from the query() call:

if (!$mysqli->query("INSERT INTO `messages` (`author`, `message`, `date`) VALUES (`$author`, `$message`, `$date`)")) {
    echo "Table creation failed: (" $mysqli->errno ") " $mysqli->error;
}

 

Then I'd try hard-coded VALUES settings. Did author, message or date end up being NULL (which violates the table setup)? [You'll want to limit the input field lengths so the value doesn't violate the database constraints as well.]

 

You probably want the id column to be INT and not int(3).

 

Not certain about this, but it's possible your line should read:

$mysqli->query("INSERT INTO messages (author, message, date) VALUES (`$author`, `$message`, `$date`)")

The quotes have me confused but I'm not a PHP expert.

 

Please follow-up to let us know how you made out. For good karma, mark a reply as the answer if it helped!