I am working on a chatting web-application. The problem is that whenever the page is loaded everytime an empty message is inserted into the database.
The code is as below
<!-- Insert MySQL datbase into HTML -->
<?php
$connection = mysqli_connect("localhost", "root", "", "tru");
$query = "SELECT * FROM shouts ORDER BY id Desc LIMIT 8";
$shouts = mysqli_query($connection, $query);
?>
<!-- Insert MySQL datbase into HTML -->
<?php while ($row = mysqli_fetch_assoc($shouts)) : ?>
<li> <?php echo $row['shout']; ?> <b> Sent at </b><?php echo $row['Time']; ?></li>
<?php endwhile; ?>
</ul>
</div>
<footer>
<form action="index.php" method="post">
<label>Shout Text: </label>
<input type="text" name="shout" placeholder="Enter your message here">
<input type="submit" id="submit" value="SHOUT!" >
</form>
<?php
<!-- Insert into MySQL datbase -->
$link = mysqli_connect("localhost", "root", "", "tru");
$sql = "INSERT INTO shouts (name,shout) VALUES ('$_POST[name]','$_POST[shout]')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</footer>
</div>
</body>
</html>
<?php
if(isset($_POST["name"])){
$link = mysqli_connect("localhost", "root", "", "tru");
$sql = "INSERT INTO shouts (name,shout) VALUES ('$_POST[name]','$_POST[shout]')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
With an if sentece you have it solved. It will only add a record if the POST name variable isset.