Return PDO data - php

Hi guys I have a program built using mysql_* and I am trying to convert it to PDO for security and depreciative reasons
So I have a load of mysql_* functions setup like
return select_from_where('users', '*', "username = '$username' AND password = '$pass'", "LIMIT 1");
Which I have converted to PDO
return $conn -> query("SELECT * FROM users WHERE username = '$username' AND password = '$pass' LIMIT 1");
However the program does not feed the right result, I'm not sure if it is even returning data
My question is, do I have to set the PDO response to a variable that I can then use, or is it possible to have it return values which I can use in my program using a similar method to above?
I have included global $conn for each function query so I'm sure it is connecting like it should, its just not feeding the result as intended..
Does anyone have a quick fix for this issue as my program is almost done and is pending release :D
Thanks in advance
Luke
** EDIT LINE *
$sql = ("SELECT * FROM users WHERE username = '$username' AND password = '$pass' LIMIT 1");
$stm = $conn->prepare($sql);
$stm->execute(array($username,$pass)); $user = $stm->fetch(); echo $user['username'];

First, Personally I see no point in having a function like select_from_where
You actually save yourself nothing - you just moved words "SELECT, FROM and WHERE" from query to function name, yet made this function extremely limited - say, no joins or stuff.
Second, PDO::query() function shouldn't be used anyway - it doesn't support prepared statements.
So, the code have to be
global $conn;
$sql = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";
$stm = $conn->prepare($sql);
$stm->execute(array($username,$pass));
return $stm->fetch();
You have to also configure your PHP and PDO in order to be able to see every error occurred.

Change this
return $conn -> query("SELECT * FROM users WHERE username = '$username' AND password = '$pass' LIMIT 1");
to:
$username = 'user';
$password ='password';
$stmt =$conn->prepare("SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1");
$stmt->execute(array($username, $password));
echo $stmt->rowCount();

Related

Mysql Query not returning my results when adding variables into the query [duplicate]

This question already exists:
How to construct an SQL query correctly in a PHP script? [duplicate]
Closed 5 years ago.
If I run this with the query
"SELECT * FROM users";
It returns my result. But as soon as I run this
$username = $_POST['username'];
$password = $_POST['password'];
$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
it doesn't.
If I run it in Mysql workbench without the variables it works. If I run echo the $_POST values they come through correctly.
I am stumped as to what I'm doing wrong PLEASE!! help me.
I also ran my code through https://phpcodechecker.com/ and it cant see any errors in my code.
This is the full function.
function login($username,$password){
global $db_conn;
$conn = new mysqli($db_conn['servername'], $db_conn['username'], $db_conn['password'], $db_conn['dbname']);
$username = $_POST['username'];
$password = $_POST['password'];
$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
$login_result = $conn->query($login);
if ($login_result->num_rows > 0) {
$output = array();
while($row = $login_result->fetch_assoc()) {
$output[] = $row;
echo "".$row['name']."-".$row['password']."<br>";
}
} else {
echo "Invaild Login Details!"."<br>" ;
$conn->close();
return false;
}
}
Every time it says "Invalid Login Details!" But I know their is one result that gets returned.
What am I doing wrong?
Inserting variables into your SQL directly is a major source of SQL Injection Attacks. Use PDO for security.
https://www.php.net/manual/en/book.pdo.php#114974
change the query like this
$login = "SELECT * FROM users WHERE name= '$username' AND password= '$password'";
note: this method is prone to sql injection attacks. try prepared statements to avoid it
try with ''(single quote) for comparing name and password
"SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";
$login = "SELECT * FROM users WHERE name = '{$username}' AND password =
'{$password}' ";
You can simply specify the variables no need to go for string append to construct query in php
Eg :
Query = "SELECT * FROM `users` where username = '$username' AND password = '$password' " ;
try following code
$login = "SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";

PHP Mysql query out puts nothing when selecting users data by username

I am trying to show a user's data from my mysql table by selecting them by username using the
following code, however it outputs 'no selection'. Important to note here that when I replace the '$username' by the real username from the database it works fine. Here is the complete code.
<?php
mysql_connect("localhost", "root", "")or die("cannot connect");
mysql_select_db("my_databse")or die("cannot select DB");
mysql_query("SET CHARACTER SET 'utf8';")or die(mysql_error());
$username=$_POST['username'];
$username = mysql_real_escape_string($username);
$sql="SELECT * FROM cv_users WHERE username LIKE '$username'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if( mysql_num_rows( $result ) === 1 ){
$row = mysql_fetch_assoc( $result );
$email = $row[ 'email' ];
$cv_txt = $row[ 'cv_txt' ];
$cv_txt = mysql_real_escape_string($cv_txt);
}
else {
echo 'no selection';
}
?>
<?php
echo $row[ 'cv_txt' ];
?>
Your problem is you are looking for 1 result and also you are adding an extra '' around the php string var you can remove this '.
Your current query :
$sql="SELECT * FROM cv_users WHERE username LIKE '$username'";
This states that you will take everything where there is a username LIKE $username
This is also incorrect as you are not considering the php var inside the string.
You could change this to
$sql="SELECT * FROM cv_users WHERE username LIKE '".$username."'";
OR
$sql="SELECT * FROM cv_users WHERE username = '".$username."'";
This will return 1 user if the username matches and if it does not match there will be no results at all.
This will clean up on the later :
if( mysql_num_rows( $result ) === 1 ){
There is code duplication here when you are already defining $count as mysql_num_rows( $result.
Debugging should be done when running into issues like this, echoing the SQL query in your page then executing that directly into MySQL would produce the error for you.
Your issue is that you are looking for an anything that matches the username supplied.
$sql = "SELECT * FROM cv_users WHERE username LIKE '$username'";
What you should be doing is fetching the data where the username is as supplied:
$sql="SELECT * FROM cv_users WHERE username = '{$username}'";
Now this would be done a whole lot easier with PDO (see footnotes)
$db = new PDO("...");
$statement = $db->prepare("SELECT * FROM cv_users WHERE username = :username");
$statement->execute(array(':username' => $username));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
I won't spoon-feed you all the code, the rest is up to you in your implementation :)
Footnotes
The whole php mysql_* api is depreciated and you should avoid using it at all.
This extension is deprecated as of PHP 5.5.0, and is not recommended
for writing new code as it will be removed in the future. Instead,
either the mysqli or PDO_MySQL extension should be used. See also the
MySQL API Overview for further help while choosing a MySQL API.
You should use either of the following two:
PDO
MySQLi
you need to understand the difference between " and '.
Simply put, the text between " will be parsed by the PHP-interpreter, while text between ' will just be text.
In your example MYSQL will search for a user with the username '$username' instead of searching for the value of the variable $username.
But in your case $username needs to be in quotes, otherwise MYSQL won't work. And here is how you do it:
$sql="SELECT * FROM cv_users WHERE username LIKE '".$username."'";
Hope this helps.
Are you sure php gets the username correctly? Maybe you can first try to echo the username(or debug), so you are certain you get the username.
It seemed that the problem is with the Post method, As I changet it to get it worked fine. Thanks for all of you

Using PHP functions in MySQL PDO

Can I use my own functions from PHP directly in SQL queries (using mySQL and PDO)? For example:
$query = null;
$result = null;
$query = $this->database_0->prepare("SELECT `id`, `salt` FROM `general_users` WHERE `username` = :username AND `password` = CONCAT(generatePassword(:password, `salt`)) LIMIT 1");
$query->bindValue(':username', $this->input->getValue('username'), PDO::PARAM_STR);
$query->bindValue(':password', $this->input->getValue('password'), PDO::PARAM_STR);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
Look at line 3 in "WHERE" case.
If it is not possible, I must use two queries just for check if a user exists, it do not look very optimal.
Thanks for your help, Bartek.
Can I use my own functions from PHP directly in SQL queries
No.
Mysql knows nothing of PHP and its functions. You are bound to use mysql functions in mysql and PHP functions in PHP. Quite easy to memorize.
So, here you go, with one single query
$sql = "SELECT id, salt, password FROM general_users WHERE username = ?";
$stmt = $this->db->prepare($sql);
$query->execute([$this->input->getValue('username')]);
$row = $query->fetch();
if (generatePassword($row['password'], $row['salt']) == $this->input->getValue('password'))
{
You can't use a PHP function in a MySQL query.
You can still do this with a single query. Just retrieve user info (including password) by comparing only its username. Then, in PHP, compare stored password with the one you have just computed. That would even allow you to distinguish two cases: "user exists, but password is wrong" and "user does not exist".

check if row exists with PDO

I am having trouble checking if a row exists to log someone in.
The password is salted in the db using the password+ the email
I am using PDO.
function is_valid_developer($username, $password)
{
global $db;
$query = 'SELECT COUNT(*) FROM users WHERE username = :username AND password = sha(CONCAT(:password,(SELECT email FROM users WHERE username = :password))) AND developer = true';
$statement = $db->prepare($query);
$statement->bindValue(':username', $username);
$statement->bindValue(':password', $password);
$statement->execute();
$count = $statement->fetchColumn();
if ($count === 1)
{
return TRUE;
}
else
{
return FALSE;
}
}
Your subquery appears to be incorrect (see the WHERE username = :password clause), and will likely never return any results. Further, using the same bound parameter twice is not supported in PDO (you use :password twice). Besides that, you don't actually need a subquery at all; try this query:
SELECT COUNT(*) FROM users
WHERE username = :username
AND password = sha(CONCAT(:password, email))
AND developer;
Further, make sure you call $statement->closeCursor() after your call to $statement->fetchColumn(); leaving PDO statement cursors open after you are done with them may cause the database to fail on all future queries.

SELECT query trouble - user login system

I am just trying to write a simple script that verifies the username and password of a user that has attempted to login...and then starts a session. However, I am running into some trouble.
When I try to run the script below, SUCCESS does not print out. As if the username and password is incorrect, however, I know for a fact that the username and passwords entered are, in fact, correct.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM users WHERE username='.$username.' AND password='.$password.'");
while($row = mysql_fetch_array($result)){
echo 'SUCCESS';
}
When I try to run the script below however, success prints out twice (which is the number of sample users I have in my db so far), which is correct.
I am guess I have a problem with the AND mySQL query above, however, it seems correct to me... is there a problem with my first query above? if not, than what else might be the problem?
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result)){
echo 'SUCCESS';
}
You're parsing variables, not concatenating them, you don't need the ..
"SELECT * FROM users WHERE username='$username' AND password='$password'"
username is a protected keyword, try this:
$result = mysql_query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password'");
Ignoring the gaping SQL injection vulnerability, you're constructing your query string incorrectly:
$result = mysql_query("SELECT * FROM users WHERE username='.$username.' AND password='.$password.'");
^ ^
You're still in "string mode" where the indicated periods are (and for the password section too), so you're embedding literal periods into your query string, instead of doing string concatenation.
Remote the periods, and you'll be better off (but still vulnerable to sql injection):
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
Try this instead:
$result = mysql_query("SELECT * FROM users WHERE username=\"$username\" AND password=\"$password\"");
Obviously, this isn't a great way of inserting data. You should look at mysqli to insert data as a minimum.
try this line instead:
$result = mysql_query("SELECT * FROM `users` WHERE `username`='".$username."' AND `password`='".$password."'");
Notice the extra "'s I've added in. before it was looking for '.$username.'

Categories