Here's the problem i'm having.
I've created a login page where the user enter his name and pass to enter. The database has already been created and i store the entered login info in session variable.
On clicking submit, i redirect the user to the page where php accesses the mysql database and searches the database for the user name and pass combination using session variables.
And there is the problem. The session variables cannot access the database table entries.
here is my code :
<?php
//starting the session
session_start();
//connecting to database and table "testdb"
#mysql_connect("localhost","root","") or die("no connect");
#mysql_select_db("testdb") or die ("no select");
//the session variables holding the username and password
//trying to access the entries in table named "table"
$sql="SELECT * FROM `table` WHERE name='.$_SESSION['uname'].' AND
pass='.$_SESSION['pass'].'";
$query=mysql_query($sql);
//printing the result which is just one entry
while($result=mysql_fetch_array($query))
{
echo $result['name'].' ';
echo $result['pass'];
}
?>
i don't know what the error is or if i'm using the syntax wrong.
i've not written comments on the actual code...this is just an identical example :D
I'm not looking for alternates cause i'm in the learning stages as of now. So any fix to this code will be greatly appreciated.
PS: I don't know java script.
Your string syntax is incorrect and this will actually generate a parse error
$sql = "SELECT * FROM `table` WHERE name='" .$_SESSION['uname']. "' AND
pass = '" .$_SESSION['pass'] ."'";
You need to actually close the string before using $_SESSION['key'], or leave off the quotes so it will be interpolated.
This code is also highly vulnerable to injection. You should use parameterized queries with PDO.
$stmt = $pdo->prepare("SELECT * FROM `table` WHERE name = ? AND pass = ?");
$stmt->execute(array($_SESSION['uname'], $_SESSION['pass']));
Your query has syntax errors. You either need to put double quotes around your sessions values or use curly brackets instead. Try -
$sql="SELECT * FROM `table` WHERE name='".$_SESSION['uname']."' AND
pass='".$_SESSION['pass']."'";
or
$sql="SELECT * FROM `table` WHERE name='{$_SESSION['uname']}' AND
pass='{$_SESSION['pass']}'";
Most obvious is that this is totally vulnerable to SQL Injection attacks. But ignoring that ...
$sql="SELECT * FROM `table` WHERE name='.$_SESSION['uname'].' AND pass='.$_SESSION['pass'].'";
... should be ...
$sql="SELECT * FROM `table` WHERE name='".$_SESSION['uname']."' AND pass='".$_SESSION['pass']."'";
Related
I have made a database where email id and corresponding name and password is stored. I have successfully obtained a form's data.. where the user enters updated name and password. But the problem is occuring with the query which is as follows
$db = mysqli_connect(all details)...
$name = $_POST['name'];
$password = $_POST['password']:
$email = $_POST['email'];
$query = "UPDATE mytable SET name='$name',password='$password' WHERE emailid='$email'";
$result = mysqli_query($db,$query);
Though I am getting all form values succesffuly and until and unless I put the 'where' clause.It works.But obviously updates all values. i want it to work with where..but so far unsuccessful :(
you need to put {} around the variables if its surrounded by quote ''
so your query should look like this
$query = "UPDATE mytable SET name='{$name}',password='{$password}' WHERE emailid='{$email}'";
$result = mysqli_query($db,$query);
EDIT : also before saving data to database make sure to filter and validate data
You need to make sure that emailid exists in mytable, you truly intended to filter by it and in your database scheme it has a type which supports the posted data. It seems that you are sending strings, like 'foo#bar.lorem' and your emailid is an int or something in the database scheme. Check it by running
desc mytable;
You need to put curly brackets around variables if you use apostrophe around them, but as a matter of style I like to close the string and attach the $variable with a . as this coding style is closer to me personally.
If everything fails, see what is generated, by echoing out the query string, try to run that directly, see what the error is and fix until...
... until it is fixed.
Also, you do not encrypt the password and your code is vulnerable to SQL injection too. Please, read about password encryption and SQL injection and then protect your project against these dangers.
You can write your statement as:
$query = "UPDATE mytable SET name='".$name."',password='".$password."' WHERE emailid='".$email."'";
using . as string concatenating operator
I am trying to concatenate a MySQL SELECT query with PHP variable but got an error.
My PHP statement which gives an error is:
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);
and error as:
( ! ) Notice: Undefined variable: info in C:\wamp\www\pollBook\poll\login.php on line 18
Call Stack
I don't understand where I missed the code.
When I write query without WHERE clause it works fine.
The reason why your code isn't working
You are attempting to use a variable, $info, that has not been defined. When you attempt to use an undefined variable, you're effectively concatenating nothing into a string, however because PHP is loosely typed, it declares the variable the second you reference it. That is why you're seeing a notice and not a fatal error. You should go through your code, and ensure that $info gets a value assigned to it, and that it is not overwritten at some point by another function. However, more importantly, read below.
Stop what you are doing
This is vulnerable to a type of attack called an SQL Injection. I'm not going to tell you how to concatenate SQL strings. It's terrible practice.
You should NOT be using mysql functions in PHP. They are deprecated. Instead use the PHP PDO Object, with prepared statements. Here's a rather good tutorial.
Example
After you've read this tutorial, you'll be able to make a PDO Object, so I'll leave that bit for you.
The next stage is to add your query, using the prepare method:
$PDO->prepare("SELECT * FROM tbl WHERE `id` = :id");
// Loads up the SQL statement. Notice the :id bit.
$actualID = "this is an ID";
$PDO->bindParam(':id', $actualID);
// Bind the value to the parameter in the SQL String.
$PDO->execute();
// This will run the SQL Query for you.
You are missing space before "AND " and you should use single quotes as suggested in other answers.
$result=mysql_query("SELECT user_id,username,add FROM users WHERE *username =".$user."AND* password=".$add);
Updated:
echo $sql = "SELECT user_id,username,add FROM users WHERE username ='".$user."' AND password='".$add."'";
$result=mysql_query($sql);
although there is no $info variable used in the query but you need to correct the query:
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username ='" . $user . "' AND password='" . $add . "'");
First from the error its looks like one of your variables is not defined. .. check it. Second surround your parameters with ' for safer syntax.
This is because the variables you are using might not have defined above
So first initialize your variables or if its coming from somewhere else(POST or GET) then check with isset method
So complete code would be
$user = 123; // or $user = isset($user)?$user:123;
$add = 123456; // or $add = isset($add)?$add:123456;
And then run your query
$result=mysql_query("SELECT user_id,username,add FROM users WHERE username =".$user."AND password=".$add);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
I just found that my website is vunerable.
Since it's connected to a DB and have functions like: Register, Change Password, Notices, etc... and SUPOSING it's fully vulnerable.
What should I look for into the code in order to start making it safe?
I mean, I did some researches and everywhere, everyone says different things about security.
"Use PDO."
"Use mysql_real_escape_string."
"Use addslashes."
What exactly should I look for??
"$_POST" and "$_GET" variables??
"$_SESSION" variables?
SQL querys?
$sql = "select * from user";
$sql = "update user set user="new_user_name";
$sql = "insert into user (user) values ('userid')";
What should I do in each case?
Please, help me to know what and where I must go.
Thank you.
Following are the points to be considered for making safe php application.
USE PDO or mysqli
Never trust any inputs. Consider every variable viz $_POST, $_GET, $_COOKIE, $_SESSION, $_SERVER as if they were tainted. Use appropriate filtering measure for these variables.
To avoid XSS attack use php’s builtin functions htmlentities,
strip_tags, etc while inserting the user input data into the
database.
Disable Register Globals in PHP.INI
Disable “allow_url_fopen” in PHP.INI
Don’t allow user to input more data than required. Validate input to
allow max number of characters. Also validate each field for
relevant datatypes.
Disable error reporting after Development period. It might give
information about database that’ll be useful to hackers.
Use one time token while posting a form. If token exist and matches
the form post is valid otherwise invalid.
Use parametrized database queries
Use stored procedures
You can google for each point for more details.
HOpe this helps
What you should look for: Any data send from the client/user. Sanitize/escape this data.
PDO can sanitize queries (using PDO::prepare) and supports multiple SQL systems.
For MySQL, use MySQLi. mysqli_real_escape_string is the function to use for sanitizing data if you are using MySQL.
None of the SQL queries you provided are actually vulnerable to SQL injection.
SQL injection vulnerabilities happen because SQL input is not properly escaped.
For example:
$sql = "select * from users where user_id =" . $_GET['user_id'];
Consider if I passed in the following:
http://some_server.com/some_page.php?user_id=123%20or%201=1
The query when executed would end up being:
select * from users where user_id = 123 or 1=1
To fix this, use parameterized queries:
$query = "select * from users where user_id = ?"
When you bind the user_id value to the query, the data access layer will escape the input string properly and the following would be executed:
select * from users where user_id = '123 or 1=1' which would not return any rows, preventing the injection
If using PHP and the mysql extension:
$sql = "select * from users where user_id = '" . mysql_real_escape_string($_GET['user_id']) . "'";
Keep in mind you need to escape ALL input that is going into a SQL query:
$sql = "select id_column from some_table where id = 1";
$stmt = mysqli_query($conn, $sql);
if($stmt === false) die(mysqli_error($conn) . "\n");
while($row = mysqli_fetch_assoc($conn, $stmt) {
$sql = "update some_other_table set some_value = 'new value' where some_column = '" . mysqli_real_escape_string($conn, $row['id_column']) . "'";
....
}
This is because values you select from the database might include characters that are not safe for execution in a SQL statement, like the name "O'Hara" or example.
}
I've been using PDO.
An example for that in your case:
<?php
$stmt = $dbh->prepare("insert into user (user) values (?)");
$stmt->bindParam(1, $name);
$name = 'ValueHere';
$stmt->execute();
?>
Why does this PHP code (mysql_query to delete a row where user name is $phpVar) do nothing?
mysql_query("DELETE FROM xraydeath WHERE user = $user");
Probably because you forgot to quote the $user parameter also, please escape variables goes into sql query strings. If that parameter is connected directly to user input someone might submit ' or 1=1 -- and your whole table gone. This idea know as sql injection.
note: the old mysql_* functions are now deprecated, you should avoid using them, see the alternatives.
You need to put quotes around strings like this:
mysql_query("DELETE FROM xraydeath WHERE user = '$user'");
you forgot the quotes around the user:
mysql_query("DELETE FROM xraydeath WHERE user = '$user'");
What are you expecting? How it fails? Mysql_query is not suppose to do anything in the form that you are using it, except sending the query to the server.
$result = mysql_query (...);
// use the result if any.
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// check the error that you might have
you need to put $user into quotes
mysql_query("DELETE FROM xraydeath WHERE user = '".$user."';");
also DELETE will succeed if even no rows where deleted, so to get how many rows where actually deleted use mysql_affected_rows()
$x = mysql_query("..");
echo "There were ".mysql_affected_rows()." rows affected";
**Try not to use mysql_* switch to PDO instead.
Assuming xraydeath.user is a character type, the value needs to be enclosed in quotes. If $user does not already contain the quotes, try:
mysql_query("DELETE FROM xraydeath WHERE user = '$user'");
And for kicks, try setting $user = "' OR '1'='1";! (Read up on SQL injection attacks and you should really switch to mysqli!)
It's also possible the table does not have a matching row, and therefore nothing will be deleted. Without knowing what you have assigned to $user and your data there is no way to know.
try this one:
mysql_query("DELETE FROM xraydeath WHERE user = '".$user."'");
or
mysql_query("DELETE FROM xraydeath WHERE user = '".$user."';");
every php variables that used in mysql, put them into '".$variable."'
First : mysql is deprecated. you should use mysqli.
Second : What kind of type is user?
if is int :
(object oriented style)
mysqli::query("DELETE (what you want) FROM xraydeath WHERE `user` = '".$user."'");
if is varchar (string) :
mysqli::query("DELETE (what you want) FROM xraydeath WHERE `user` LIKE '".$user."'");
or
(procedurel syle)
mysqli_query((your mysqli link), "DELETE (what you want) FROM xraydeath WHERE `user` LIKE/= '".$user."'");
Hope it helps
I have this query to submit data into the database:
$sql = "UPDATE table SET user='$user', name='$name' where id ='$id'";
the id will be obtained via url EX localhost/index.php?id=123
$id=$_GET['id']
The query will not work correctly; the data will not update.
If I write :
$sql = "UPDATE table SET user='$user', name='$name' where id ='123'";
It works fine.
If I echo the ID it will show the correct result, 123.
Where is the problem?
run ALL your queries the way you can get the error message along with erroneous query.
so, at least this way
$sql = "UPDATE table SET user='$user', name='$name' where id ='$id'";
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
and it will tell you where is the problem.
It is WAY more convenient, precise and faster than asking questions here.
I'm guessing your problem is mal-formed SQL due to unescaped data interpolation - an SQL injection hole.
What does your actual generated query look like? Not the code that creates the sql (which you've got above), but the actual SQL after the variables are inserted?
I'm guessing it'll look something like this:
UPDATE table SET user='fred', name='O'Brien' where id='123';
^--unescaped quote
causing a syntax error.
If you're running the query like this:
$result = mysql_query($sql);
then change it to be
$result = mysql_query($sql) or die(mysql_error());
so you'll immediately get feedback if the query fails for any reason.
And then read up about SQL injection holes
$id = $_GET['id']
<form action="#.php" method="POST">
<input type="hidden" name="id" value="<?php echo $id?>">
</form>
then, inside PHP block,
$id = $_POST['id'];
$sql = "UPDATE table SET user='$user', name='$name' where id ='$id'"
Without getting into the issue of how bad it is to pull data right from the GET array, I'd start by suggesting you properly escape your variables. I assume ID is an integer, so there's no need for singlequotes around it.
$sql = "UPDATE table SET user='".$user."', name='".$name."' where id=".$id;
See if that works.
TableName should be there ....you have not used table name in your query..Echo the $sql and then try executing in phpmyadmin.
First of all, you're wide open to SQL Injection attacks if you do it like this. Anyone can just alter the part after id= to anything they like and modify your database with that.
Secondly, I see you pass an id to the script, but where does it determine the $user and $name values? Seems like your code posted is incomplete.