I'm making php chat to my school project. Php code is divided to two files with code. First file is file, where is chat window and text input to enter message. This is the php code of first file:
<?php
$connection = mysql_connect('localhost', 'root', 'root');
if (!$connection) {
die('<b>Can\'t connect to database server. Error message: ' . mysql_error() . '</b>');
}
$database = mysql_select_db('vaclavik', $connection);
if (!$database) {
$command = 'CREATE DATABASE vaclavik';
if (mysql_query($command, $connection)) {
echo '<b>Database wasn\'t found. New one has been created. </b>';
mysql_close($connection);
$connection = new mysqli('localhost', 'root', 'root', 'vaclavik');
$command = 'CREATE TABLE chat(datum DATETIME, zprava TEXT)';
if (mysqli_query($connection, $command)) {
die('New table has been created!');
}
else {
die('Can\'t create new table!');
}
}
else {
die('Database wasn\'t found and new one can\'t be created!');
}
}
mysql_close($connection);
$connection = mysqli_connect('localhost', 'root', 'root', 'vaclavik');
$command = 'SELECT * FROM chat';
$result = mysqli_query($connection, $command);
if(empty($result)) {
$command = 'CREATE TABLE chat(datum DATETIME, zprava TEXT)';
if (mysqli_query($connection, $command)) {
die('New table has been created');
}
else {
die('New table can\'t be created');
}
}
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()) {
echo '<b>' . $row["datum"] . ":</b> " . $row["zprava"] . "<br />";
}
}
else {
echo '<b>No message found. Write something! :)</b>';
}
mysqli_close($connection);
?>
This code works. Then I created form to input message. It redirects to another file with php code to insert message into database. Problem is, if I put code with no error detections, it does nothing. And when I put there some error protetions, php starts report Parse errors with unexpected chars in code. Commonly '{' and 'echo'.
This is code of second file:
<?php
$message = $_POST["chatinput"];
$connection = mysqli_connect('localhost', 'root', 'root', 'vaclavik');
$command = "INSERT INTO chat (datum, zprava) VALUES (\'" . date("Y-m-d, h:i:sa") . "\', \'" . $message . "\')";
mysqli_query($connection, $command);
mysqli_close($connection);
echo "<script>window.location = \"../chat.php\"</script>";
?>