How to prevent filling empty data in MySQL table?

Also malicious insertions

I saw this question, but none of the answers worked for me (or rather, I was too stupid to make them work). I think I need individual help. Every time I refresh my php page, it inserts empty data. How to prevent the insertion of empty and / or malicious data.

This is my code:

<?php $con = mysql_connect("localhost","user","pass") or die ("Couldn't connect!"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("streams") or die ("Couldn't find db"); $sql="INSERT INTO streams (streamname) VALUES ('$_POST[streamname]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> <form action="submit.php" method="POST"> Stream Name: <input type="text" name="streamname" id="streamname" /><br /> <input type="submit" name="submit" value="Stream" /> </form> 
+4
source share
3 answers

Wrap it with some protective logic:

 if(!empty($_POST['streamname'])) { // Your code here } 
+5
source

Try checking if the POST options are set:

  <?php if($_POST) { $con = mysql_connect("localhost","user","pass") or die ("Couldn't connect!"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("streams") or die ("Couldn't find db"); $sql="INSERT INTO streams (streamname) VALUES ('$_POST[streamname]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con); } ?> <form action="submit.php" method="POST"> Stream Name: <input type="text" name="streamname" id="streamname" /><br /> <input type="submit" name="submit" value="Stream" /> </form> 
+2
source

You should avoid typing.

 $sql='INSERT INTO streams (streamname) VALUES ("'.mysql_real_escape_string($_POST[streamname]).'")'; 
0
source

Source: https://habr.com/ru/post/1390143/


All Articles