I am using this code to send data to mysql database and its functioning well though users are sending blank data and duplicating too.
<?php
require "conn.php";
$lostidno = $_POST ["lostidno"];
$phonenol = $_POST ["phonenol"];
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
$conn->close();
?>
How do I prevent this?
You can use trim function to remove spaces at the beginning and the ending of a string. After that you are able to check if the two parameters aren't empty:
<?php
require "conn.php";
$lostidno = trim($_POST["lostidno"]);
$phonenol = trim($_POST["phonenol"]);
if(!empty($lostidno) && !empty($phonenol))
{
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE) {
echo "Information Recieved!";
}
else {
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
}
$conn->close();
}
?>
You should also have a look at this to prevent SQL injections.
1. To avoid blank values
Check the values of variables before executing insert query on database using empty() PHP function.
2. Avoid duplicate values
You can do it in two ways, Either specify UNIQUE constriant in database TABLE or run SELECT query before inserting data into database.
//this to check the duplicate records
Fire the select query : select * from lostdb.lost where col1= $lostidno and col2 = $phonenol;
//this is to check the blank condition
if($lostidno !== "" && $phonenol != "")
{
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
}
The best way to prevent duplicates is to mark the unique database columns as UNIQUE
ALTER TABLE <table_name> ADD UNIQUE(<column_name>);
To prevent blank data from ever getting into the database you need to check them with a few modifications in the code you posted:
if( ($lostidnol != "") && ($phonenol != "") )
{
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
{
//error
}
}
else
{
//Notify the user that they're trying to insert blanks
}
If you want to provide proper user experience you should also provide some client side validation using JavaScript or jQuery
Use trim function to remove blank spaces from string.
<?php
require "conn.php";
$lostidno = trim($_POST ["lostidno"]);
$phonenol = trim($_POST ["phonenol"]);
//Check record exist or not.
$unique_check = "select count(*) as cnt from lostdb.lost where lostidno='".$lostidno."' and phonenol='".$phonenol."'";
//Execute above query and check record already exist or not. If record not exist then only allow to insert it.
$result_unique_check = $conn->query($mysql_qry)->one();
$record_exist = $result_unique_check['cnt'];
if($record_exist > 0){
echo "Record alreay exist.";
}else{
//Insert new record
$mysql_qry = "INSERT INTO lostdb.lost (lostidno, phonenol) VALUES ('$lostidno', '$phonenol')";
if ($conn->query($mysql_qry) === TRUE)
{
echo "Information Recieved!";
}
else
echo "Sorry! An Error Occured:" . $mysql_qry . "br" . $conn->error;
$conn->close();
}
?>
Related
I am trying to use the INSERT INTO SQL statement in php. It will input everything correctly up until the last value ($bands_bio). Instead of putting in the correct information, it leaves the value blank. I have looked over everything and can't seem to find any sort of syntax errors.
$page_title = "Create a new band";
require ('includes/database.php');
require_once 'includes/bandsHeader.php';
$band_name = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_name', FILTER_SANITIZE_STRING)));
$band_photo = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_photo', FILTER_SANITIZE_STRING)));
$genre = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'genre', FILTER_SANITIZE_STRING)));
$band_bio = $conn->real_escape_string(trim(filter_input(INPUT_GET, 'band_bio', FILTER_SANITIZE_STRING)));
echo $band_bio;
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = "")) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/searchFooter.php';
exit;
}
$albums = 0;
$sql = "INSERT INTO bands VALUES (NULL, '$band_name', '$genre', '$albums', '$band_bio')";
$query = #$conn->query($sql);
if (!$query) {
$errno = $conn->errno;
$errmsg = $conn->error;
echo "<div id='contentWrapper'>";
echo "<div class='contentBox'>";
echo "Insertion failed with: ($errno) $errmsg<br/>\n";
echo "</div></div>";
$conn->close();
include 'includes/footer.php';
exit;
}
As you can see, I echoed out $band_bio in order to see if it was getting the right value from my form that uses the GET method, which it is so that's not the issue. It has no problem inserting everything correctly up until the last value, which is supposed to be the last column called band_bio in my bands table in my database. It will not output any errors or anything, either. It's almost as if it's taking the string data from the variable and removing all of the text before it inserts the information.
I have been working on this website for a few weeks now and have used the INSERT INTO statement the exact same way on other pages and it works just fine. This is the first thing that has really stumped me and I can't figure it out. Any help is appreciated.
When inserting, ensure that your pk (id) field is set to auto-increment.
This way, you can exert more control over your queries. You should be more successful with:
$sql = "INSERT INTO bands "
. "(`band_name`,`genre`,`numof_albums`,`band_bio`) "
. "VALUES ('$band_name', '$genre', '$albums', '$band_bio')";
By not specifying the pk field, INNODB will automatically increment and insert it for you.
The idea is that you want to specify which columns are being inserted into. Relying on column ordering by mysql is fine, but there may be something at play in your case.
There should be no reason why band_bio would be "left off". You would get a column-mismatch error.
Totally found the answer myself! It, in fact, was a syntax error.
if (($band_name === "") OR ($genre === "") OR ($band_photo === "") OR ($band_bio = ""))
The variable $band_bio was being assigned to a blank string in the if statement since I accidentally used an assignment operator rather than a comparison operator. So the correct code would need to be $band_bio === "" rather than $band_bio = "".
I swear, the problem is always something so much simpler than you think it's going to be.
I've created a code that updates an Sql entry, but when you leave an value blank, it removes the existing value.
<?php
$servername = "localhost";
$username = "root";
$password = "HahahNo";
$dbname = "DATA";
$id = $_POST["id"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error updating record: " . $conn->error;
}
?>
Is there any way not to clear the not filled in values? Im fairly new to php.
Check if $_POST contains values.
First check if $_POST value has been set with isset() (has been posted).
Then check if the string isn't empty with strlen():
if (!isset($_POST['firstname'] || strlen($_POST['firstname']) == 0) {
echo 'Please enter first name';
} else {
// Do your DB update
}
Edit: Naturally empty() is better because you only need one check to do:
if (empty($_POST['firstname']) {
echo 'Please enter first name';
} ...
Thanks to #Fred -ii-
Edit II: As pointed out by #alex
if ($_POST['firstname']) {
echo 'Please enter first name';
} ...
would work too. Explained in PHP type comparison tables
You can write condition before execute function,
//all values are not null then update is perform
if(!is_null($firstname) && !is_null($lastname) && !is_null($email)){
if ($conn->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error updating record: " . $conn->error;
}
}
What you're looking for is validation of user-supplied data. You're right - a user who hasn't read the instructions of your form could cause unintended data loss. Additionally a malicious user or innocent child could cause more harm with SQL injection.
First check your field meets minimum requirements. You could validate email addresses, postcodes, phone numbers, URLs... but to answer your question Daenu's answer is perfect.
Once you are satisfied the data meets your databases' requirements, check it is safe. Strip it of any malicious SQL commands. You can use prepared statements with PDO or MySQLi.
Also think about the specification of the data. Is the data type of each field a string or integer or float? What character set is your web page in (UTF-8 is a safe choice) and therefore what character set does your data arrive with? Does your database match (UTF8MB4 is a good companion)?
This would be a piece of my code.
$name = $_POST['UserNames'];
$pw = sha1($_POST['Passwords']);
$mail = $_POST['Emails'];
$pc = $_POST['Postcodes'];
$status = "0";
mysql_query("INSERT INTO userinfo
(Username,Password,Email,Postcode,status,valid)
VALUES
('$name','$pw','$mail','$pc','$status','$validate')
");
How do i make sure every input will not be null and the Email will never repeat.
Try this,
mysql_query("INSERT INTO userinfo (Username,Password,Email,Postcode,status,valid) VALUES ('$name','$pw','$mail','$pc','$status','$validate') ON DUPLICATE KEY UPDATE status='0'");
For more details refer, https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
use the empty function for the post fields to check if it contains something.
for the email, you must use a UNIQUE clause in your database for this field
About the email: set up the column of Email in userinfo table to be unique, and on insert just do on duplicate ignore
About the fields, well in the way you are working just do isset($_POST['XXX']) && !empty($_POST['XXX']). A better way would be working with some input validation class, like this one.
For empty input you can do the following :
$name = (isset($_POST['UserNames']) && !empty($_POST['UserNames'])) ? $_POST['UserNames'] : FALSE;
For duplicate email check you need to do a SELECT query before executing the INSERT statement.
First check values before mysql query:
$valid = true;
foreach($_POST AS $key=>$value)
{
if($value == null){
echo "Please provide ".$key;
$valid = false;
}
}
if($valid == true)
{
// check if email is in DB
$result = mysql_query("SELECT email FROM user info WHERE Email = '".addslashes($_POST['email'])."'");
if(mysql_num_rows($result) == 1)
{
echo "Email is already registered in our DB";
}
else
{
mysql_query("INSERT INTO userinfo (Username,Password,Email,Postcode,status,valid) VALUES ('$name','$pw','$mail','$pc','$status','$validate')");
}
}
I want to display an error message if the insert already exists.
I've made name unique in the database and if I enter the same value, it does not insert. Just as I wanted. Here is my code:
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
Now I want to echo a message to let the user know that the value he has entered is already present in the database and will not be inserted. Anyone?
I take it you are collecting $foo from a form?
what I would do is an sql query of the table register collecting the name field then when you collect the name entered in the form and its posted you can run an if condition against the name field you have already gathered using the sql statement and if there is a name = to the name they enter on the field they can receive a message and exit before the sql injection into the register table.
The simpliest way:
$res = mysql_query($query):
if ($res)
echo 'Insertion ok';
else
echo 'error: name already exists';
A better way: do first a SELECT query to see if name exists or not.
Note: you should think about moving from mysql_* to mysqli_* or PDO
Try this :
$query = "INSERT INTO register(name) VALUES('$name')";
$user = mysql_query($query):
if ($user)
echo 'User Register';
else
echo 'User Already Exist';
As per Melon's comment, you should use mysqli.
// Create your connection
$mysqli = new mysqli($host, $user, $pass, $dbname);
// Do your query
$mysqli->query("INSERT INTO register(name) VALUES('$foo')");
if($mysqli->affected_rows == 0) {
// Your chosen method of alerting the user goes here
}
\\this first part collects name information from your table.
$name="SELECT name FROM register";
$name_query = mysqli_query($db_conx, $name);
$numrows = mysqli_num_rows($name_query);
if($numrows < 1){
echo "cannot find user";
header ("location: index.php");
}
while ($row = mysqli_fetch_array($name_query, MYSQLI_ASSOC)){
$name = $row["name"];
}
\\ this part gets the name from your form
if (isset($_POST['class']) && ($_POST['class'] !='')){
$foo = $_POST['foo'];
\\this part checks to see if the 2 values are equal
if ($name == $foo){
echo "This name has already been used try again";
\\this part then adds the name if its not already in the database
}else{
$query = "INSERT INTO register(name) VALUES('$foo')";
mysql_query($query) or die('An Error occurred' . mysql_error());
}
}
//then all you need to do is create your form to post the foo or name so it can be collected and passed through the querys.
<?php
include"include/connection.php";
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "insert into employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['gender']."','".$_POST['email']."','".$_POST['username']."','".$_POST['password']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['city']."','".$_POST['country']."')";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
This is my code for inserting registration form data into a database. This code adds the data but also gives a parse error, but does not give the error if the username already exists.
Notice: Undefined variable: username in C:\Program Files\EasyPHP5.3.0\www\register_hirer2.php on line 6
Thanks for registration
line 6 is:
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
Well, your $username is undefined indeed.
Most probably you want to use $_POST['username'].
And of course this obligatory XKCD comic:
If the "data source" is an html form (supposedly using method="post") you have to use $_POST['username'] when register_globals is set to off (which is the default since ...ages). see http://docs.php.net/security.globals
Also have a read of http://php.net/manual/en/security.database.sql-injection.php
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values (". same mysql_real_escape_string() thing here for each parameter .")";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
You can also use prepared statements. This way you don't need/can't forget using an escaping function.
edit and btw: you don't need the SELECT before the INSERT in order to make the username unique. Actually it will make things even harder since now you have to deal with race conditions. You'd have to lock the table between those two queries.
If you add an unique index for the username in your table MySQL will not allow the insertion of a doublet but instead return a specific error code which your script can fetch and handle without the need of dealing with race conditions.
define('ER_DUP_ENTRY', 1062);
$mysql = mysql_connect('..', '..', '..');
mysql_select_db('..', $mysql) or die(mysql_error($mysql));
$fields = array(
'efname'=>'first_name',
'elname'=>'last_name',
'egender'=>'gender',
'eemail'=>'email',
'eusername'=>'username',
'epwd'=>'password',
'eadd'=>'address',
'ephone'=>'phone',
'ecity'=>'city',
'ecountry'=>'country'
);
$sqlparams = array();
foreach($fields as $sql=>$form) {
if ( !isset($_POST[$form]) ) {
die('missing post parameter '. $form);
}
$sqlparams[$sql] = "'".mysql_real_escape_string($_POST[$form], $mysql)."'";
}
$query = '
INSERT INTO
employer
'. join(', ', array_keys($sqlparams)) .'
VALUES
('.join(',', $sqlparams).')
';
// table:employer has been defined with "unique key idxName (eusername)"
$result = mysql_query($query, $mysql);
if ( false!==$result ) {
echo " Thanks for registration";
}
else if ( ER_DUP_ENTRY===mysql_errno($mysql) ) {
echo 'username already exists';
}
else {
echo 'an error occurred';
}
That is because you do not define $username anywhere. It looks as though you want to use $_POST['username']
mysql_query("SELECT * FROM employer WHERE eusername='{$_POST['username']}'");
Also, your code is vulnerable to a SQL Injection
You never define $usernameanywhere, so it gives that error because you are trying to use a variable that it doesn't have a value for.
This is most likely because you've not defined the '$username' variable. I presume that you're relying on this being populated from the incoming GET/POST data (most likely via the depreciated register_globals) which is bad practice.
As such, you'll need to either populate $username via $_POST or $_GET.
More importantly, you should update the insert query to escape the incoming 'untrusted' data using mysql_real_escape_string (e.g.: mysql_real_escape_string($_POST['username']), etc.)
As #Yacoby said your code is vulnerable to an SQL Injection to prevent it you can use mysqli or PDO , if you would like to use mysqli use the following code:
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = $conn->prepare("INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry)) values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; // preparing the insert
$query->bind_param("ssssssssss" , $variable1 , $variable2 , $variable3 , $variable4 , $variable5 , $variable6 , $variable7 , $variable8 , $variable9 , $variable10); // binding parameters
$query->execute(); // sending the parameter values
$query->close(); // closing the query
$conn->close(); // closing the connection
if ($query) { // checking if the query has been executed with no errors
echo " Thanks for registration";
}
}
?>
BE SURE TO CHANGE THE $conn AND variables to whatever you want!