Insert session variable into MySQL database - php

Hey I am new to PHp and I am trying to enter details into my database. I am trying to enter an eventname- which the user enters (POST) and the username of the logged in user.
I have created sessions to store users usernames, the code i have is
$eventname=$_POST['eventname'];
$myusername = $_SESSION['myusername']
$sql = mysql_query("INSERT INTO $tbl_nameVALUES('','$eventname','$_SESSION['myusername'])");
echo "You have been added to the event";
Its the $sql statement which is giving the error? any help would be much appreciated.
Thanks all!

There are several potential problems here.
First, you have not escaped eventname against SQL injection. We assume hopefully that myusername is already safe. If it has not been previously filtered, also use mysql_real_escape_string() on $_SESSION['myusername'].
$eventname = mysql_real_escape_string($_POST['eventname']);
// Then you need space before VALUES and are missing a closing quote on $_SESSION['myusername'], which should be in {}
$sql = mysql_query("INSERT INTO $tbl_name VALUES('','$eventname','{$_SESSION['myusername']}')");
Finally, in order for the statement to work, it assumes you have exactly three columns in $tbl_name. You should be explicit about the columns used. Substitute the correct column names for colname1, event_name, username.
$sql = mysql_query("INSERT INTO $tbl_name (colname1, event_name, username) VALUES('','$eventname','{$_SESSION['myusername']}')");
The exact locations of SQL syntax errors will be revealed to you with some basic error checking via mysql_error().
$sql = mysql_query(<your insert statement>);
if (!$sql) {
echo mysql_error();
}

You're missing a ' on your insert statement. Try this
INSERT INTO $tbl_name VALUES('','$eventname','$_SESSION['myusername']')

Hope it help you...
$eventname=$_POST['eventname'];
$myusername = $_SESSION['myusername'];
$sql = mysql_query("INSERT INTO tbl_name VALUES('','$eventname','".$_SESSION['myusername'])."'");
echo "You have been added to the event";

You need a space between $tbl_name and VALUES, and indeed a ' after $_SESSION['myusername'].
And look up SQL injection.

Remove the single quotes around the key in your $_SESSION array:
$sql = mysql_query("INSERT INTO $tbl_name VALUES('', '$eventname', '$_SESSION[myusername])");

Related

Find a user using a form with PHP backend

I'm trying to check if a user exists on the database using a form front end.
If the user is there don't add to the database.
The code isn't working when adding a user it gives me the user has been added even the user exists.
Here my code:
<?php
$connection = mysql_connect("localhost", "dbuser", "dbpasswd"); // Establishing Connection with Server
$db = mysql_select_db("ldap", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$netid = $_POST['netid'];
$univid = $_POST['univid'];
if($netid !=''||$univid !=''){
//Insert Query of SQL
$query = mysql_query("SELECT FROM user ( UserName, temppass WHERE UserName=$netid");
if(mysql_num_rows($sql)>=1)
{
echo"NetID $netid already exists";
}
else
{
//insert query goes here
$query = mysql_query("insert into user( UserName, temppass ) values ('$netid', '$univid')");
}
echo "<br/><br/><span>User Registered successfully...!!</span>";
}
else{
echo "<p>Registration Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
?>
You could do something like:
$query = mysql_query("SELECT COUNT(UserName) as total FROM user;");
Then
$result = mysql_fetch_assoc($query);
The count of users will be in $result['total']. As an aside the mysql_* methods are inferior to prepared statements (google it).
Your select query has many errors with it.
SELECT FROM user ( UserName, temppass WHERE UserName=$netid
First issue you aren't selecting anything. Second issue I don't know what ( UserName, temppass is, maybe the columns you want to select? Third issue is that Username is presumably a string, not an integer, so that value should be in quotes. Once you quote that though you will open yourself to SQL injections.
Here is a valid version of your current query.
SELECT UserName, temppass FROM user WHERE UserName='$netid'
Here's the doc on mysql's select: http://dev.mysql.com/doc/refman/5.7/en/select.html
Here are some links to read up on about SQL injections:
How can I prevent SQL injection in PHP?http://php.net/manual/en/security.database.sql-injection.php
You also shouldn't be using the mysql_ functions they are deprecated and insecure now. Why shouldn't I use mysql_* functions in PHP?
Additional issues:
if(mysql_num_rows($sql)>=1)
The $sql isn't defined.
I don't know what $_POST['netid'] is but that sounds like an id, not a username.
You shouldn't store passwords in plain text.
You should enable error reporting and/or monitor your error logs.

Query not inserting data

trying to submit data from a form but does not seem to be working. Can't spot any problems?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proId = $_POST["id"];
$proCode = $_POST["code"];
$proDescr = $_POST["descr"];
$proManu = $_POST["manu"];
$proCPU = $_POST["cpu"];
$proWPU = $_POST["wpu"];
$proBarCode = $_POST["barcode"];
$proIngredients = $_POST["ingredients"];
$proAllergens = $_POST["allergenscon"];
$proMayAllergens = $_POST["allergensmay"];
//Insert users data in database
$sql = "INSERT INTO prototype.Simplex_List (id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay)
VALUES ('$proId' , '$proCode', '$proDescr' , '$proManu' , '$proCPU' , '$proWPU' , '$proBarCode' , '$proIngredients' , '$proAllergens' , '$proMayAllergens')";
//Run the insert query
mysql_query($sql)
First and foremost, please do not use mysql_*** functions and please use prepared statements with
PDO http://php.net/manual/en/pdo.prepare.php
or mysqli http://php.net/manual/en/mysqli.quickstart.prepared-statements.php instead. Prepared statements help protect you against sql injection attempts by disconnecting the user submitted data from the query to the database.
You may want to try using mysql_real_escape_string http://php.net/manual/en/function.mysql-real-escape-string.php to ensure no stray " or ' is breaking your query.
$proId = mysql_real_escape_string($_POST["id"]);
$proCode = mysql_real_escape_string($_POST["code"]);
$proDescr = mysql_real_escape_string($_POST["descr"]);
$proManu = mysql_real_escape_string($_POST["manu"]);
$proCPU = mysql_real_escape_string($_POST["cpu"]);
$proWPU = mysql_real_escape_string($_POST["wpu"]);
$proBarCode = mysql_real_escape_string($_POST["barcode"]);
$proIngredients = mysql_real_escape_string($_POST["ingredients"]);
$proAllergens = mysql_real_escape_string($_POST["allergenscon"]);
$proMayAllergens = mysql_real_escape_string($_POST["allergensmay"]);
Additionally ensure your form is being submitted by calling var_dump($_POST) to validate the data
You can also see if the query is erroring by using mysql_error http://php.net/manual/en/function.mysql-error.php
if (!mysql_query($sql)) {
echo mysql_error();
}
advices about PDO, prepared statements were done.
1) Do you have a database and connection to it?
Look at your prototypeconnect.php and find database name there. check that its name and password is similar that u have.
2) Do you have a table named prototype.Simplex_List in your database?
a) IF YOU HAVE:
check if your mysql version >= 5.1.6
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
b) IF YOU HAVE BUT ITS NAME is Simplex_List:
b-1) if your database name IS NOT prototype:
replace your
$sql = "INSERT INTO prototype.Simplex_List
with
$sql = "INSERT INTO Simplex_List
b-2) if your database name IS prototype:
you should escape your $_POST data with mysql_real_escape_string as #fyrye said.
c) IF YOU HAVE NOT:
you should create it
3) Check your table structure
does it have all theese fields id, code, descr, manu, cpu, wpu, barcode, ingredients, allergenscon, allergensmay?
if you have there PRIMARY or UNIQUE keys you should be sure you are not inserting duplicate data on them
but anyway replace your
$sql = "INSERT INTO
with
$sql = "INSERT IGNORE INTO
PS: its not possible to help you without any error messages from your side

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

How do I demonstrate a Second Order SQL Injection?

So I've been trying to replicate a second order SQL Injection. Here's an example template of two php based sites that I've prepared. Let's just call it a voter registration form. A user can register and then you can check if you're a registered voter or not.
insert.php
<?php
$db_selected = mysql_select_db('canada',$conn);
if (!db_selected)
die("can't use mysql: ". mysql_error());
$sql_statement = "INSERT into canada (UserID,FirstName,LastName,Age,State,Town)
values ('".mysql_real_escape_string($_REQUEST["UserID"])."',
'".mysql_real_escape_string($_REQUEST["FirstName"])."',
'".mysql_real_escape_string($_REQUEST["LastName"])."',
".intval($_REQUEST["Age"]).",
'".mysql_real_escape_string($_REQUEST["State"])."',
'".mysql_real_escape_string($_REQUEST["Town"])."')";
echo "You ran the sql query=".$sql_statement."<br/>";
$qry = mysql_query($sql_statement,$conn) || die (mysql_error());
mysql_close($conn);
Echo "Data inserted successfully";
}
?>
select.php
<?php
$db_selected = mysql_select_db('canada', $conn);
if(!db_selected)
die('Can\'t use mysql:' . mysql_error());
$sql = "SELECT * FROM canada WHERE UserID='".addslashes($_POST["UserID"])."'";
echo "You ran the sql query=".$sql."<br/>";
$result = mysql_query($sql,$conn);
$row=mysql_fetch_row($result);
$sql1 = "SELECT * FROM canada WHERE FirstName = '".$row[1]."'";
echo "The web application ran the sql query internally=" .$sql1. "<br/>";
$result1 = mysql_query($sql1, $conn);
$row1 = mysql_fetch_row($result1);
mysql_close($conn);
echo "<br><b><center>Database Output</center></b><br><br>";
echo "<br>$row1[1] $row1[2] , you are a voter! <br>";
echo "<b>VoterID: $row[0]</b><br>First Name: $row[1]<br>Last Name: $row[2]
<br>Age: $row[3]<br>Town: $row[4]<br>State: $row[5]<br><hr><br>";
}
?>
So I purposely made this vulnerable to show how second order SQL Injection works, a user can type in a code into the first name section (where I am currently stuck, I've tried many different ways but it seems that I can't get it to do anything).
Then when a person wants to activate the code that he has inserted in the first name section, all he needs to do is just type in the userID and the code will be inserted.
For example:
I will type into the insert.php page as:
userid = 17
firstname = (I need to inject something here)
lastname = ..
age = ..
town = ..
state = ..
Then when I check for my details, and type in 17, the SQL script injected will be activated.
Can I get few examples on what sort of vulnerabilities I can show through this?
What is there to demonstrate?
Second order SQL injection is nothing more than SQL injection, but the unsafe code isn't the first line.
So, to demonstrate:
1) Create a SQL injection string that would do something unwanted when executed without escaping.
2) Store that string safely in your DB (with escaping).
3) Let some other piece of your code FETCH that string, and use it elsewhere without escaping.
EDIT: Added some examplecode:
A table:
CREATE TABLE tblUsers (
userId serial PRIMARY KEY,
firstName TEXT
)
Suppose you have some SAFE code like this, receiving firstname from a form:
$firstname = someEscapeFunction($_POST["firstname"]);
$SQL = "INSERT INTO tblUsers (firstname) VALUES ('{$firstname }');";
someConnection->execute($SQL);
So far, so good, assuming that someEscapeFunction() does a fine job. It isn't possible to inject SQL.
If I would send as a value for firstname the following line, you wouldn't mind:
bla'); DELETE FROM tblUsers; //
Now, suppose somebody on the same system wants to transport firstName from tblUsers to tblWhatever, and does that like this:
$userid = 42;
$SQL = "SELECT firstname FROM tblUsers WHERE (userId={$userid})";
$RS = con->fetchAll($SQL);
$firstName = $RS[0]["firstName"];
And then inserts it into tblWhatever without escaping:
$SQL = "INSERT INTO tblWhatever (firstName) VALUES ('{$firstName}');";
Now, if firstname contains some deletecommand it will still be executed.
Using a first name of:
' OR 1 OR '
This will produce a where clause in the second SQL of
WHERE FirstName = '' OR 1 OR ''
Therefore the result will be the first record in the table.
By adding a LIMIT clause, you can extract all rows from the table with:
' OR 1 ORDER BY UserID ASC LIMIT 0, 1 --
Obviously it will only extract 1 row at a time, so you would need to repeat that and increment the 0 in the LIMIT. This example uses a comment -- to terminate the remaining SQL which would otherwise cause the query to fail because it would add a single quote after your LIMIT.
The above is a simple example, a more complex attack would be to use a UNION SELECT which would give you access to the entire DB through the use of information_schema.
Also you are using addslashes() in one of your queries. That is not as secure as mysql_real_escape_string() and in turn: escaping quotes with either is not as secure as using prepared statements or parameterised queries for example in PDO or MySQLi.

Insert query problem with php mysql

This is simple one i am using the following insert query
mysql_query(insert into table1 set saltval = 'Y'Z' where uid ='1');
but i does not work becaues the value for the field saltval is Y'Z . my question is how to considered this value is as a string .
You need to escape any single quotes with a backslash.
mysql_query("insert into table1 set saltval = 'Y\'Z' where uid ='1'");
However your SQL is invalid as well... Did you mean to do an update? Insert statements don't have a where.
As mentioned in other answers, if the input is from a user then you should use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php
$string = mysql_real_escape_string("Y'Z");
mysql_query("insert into table1 set saltval = '{$string}' where uid ='1'");
Always use mysql_real_escape_string() function for this if values come from user input
$query="insert into table1 set saltval = '".mysql_real_escape_string($InputVal)."' where uid ='1'";
See http://php.net/manual/en/function.mysql-real-escape-string.php
You have to add a backslash to certain characters to make your string fit into SQL syntax rules.
Assuming you're creating your query dynamically, PHP has special escaping function for this and you should use it for the every quoted string in the query, no exceptions.
So, write your code like this:
$salt = "Y'Z";
$id = 1;
$salt = mysql_real_escape_string($salt);
$id = mysql_real_escape_string($id);
$sql = "update table1 set saltval = '$salt' where uid ='$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
to make it safe and fault-tolerant

Categories