<?php
include ("account.php") ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db($project);
$number = NULL ;
$username = $_POST["username"];
$priority = $_POST["priority"];
$category = $_POST["category"];
$incident_description = $_POST["incident_description"];
$sql = "insert into incident values ( NULL, '$username','$priority','$category','$incident_description',curdate(),curtime() )" ;
mysql_query ( $sql ) or print ( mysql_error ( ) );
$credentials = "select * from Credentials where ("username" = '$username' ,"password" = '$password' , "email_address" = 'email_address')" ;
print $credentials;
$result = mysql_query ($credentials) or print (mysql_error ( ) );
$howManyRows = mysql_num_rows ( $result);
//if $howManyRows is positive continue process to update database with sql,if not,die.
?>
There is an html code for a form on another file hence the $_POST, but I don't think it s necessary to show it here since I need the right syntaxes on this php file.
With the part from the $credentials I need help with how to compare the values in the html form (username,password,email_address) with values in the table "Credentials" from the database?I need to do this in order to authorize the values to carry on the process.
The syntax I got there isn't right at the moment because it doesn't execute it properly. I just don't know how to compare the two.
This whole thing works up until the mysql_query ( $sql ) or print ( mysql_error ( ) ) line.
Suggestions would be nice.I apologize for the long question!
PS: columns for the Credentials table are username,password,email_address as well!
the problem is here
$credentials = "select * from Credentials where ("username" = '$username' ,"password" = '$password' , "email_address" = 'email_address')" ;
change to
$credentials = "select * from Credentials where `username` = '$username' and `password` = '$password' and `email_address` = 'email_address'" ;
The problem is in query, when you want to check multiple values use AND in WHERE clause.
I dont know but shouldn't u use the following...
$sql = "INSERT INTO incident (fieldname, fieldname) VALUES ('".mysql_real_escape($_POST['fieldname'])."', '".mysql_real_escape($_POST['fieldname'])."')";
To insert anything into mysql?
You can use your credential query as below
$credentials = "select * from Credentials where username = '$username' AND password = '$password' AND email_address = 'email_address'" ;
BUT for better performance & to prevent your code for mysql injection you have to do following things
1) Use Mysqli instead of mysql functions. here is good lib for mysqli as wrapper
https://github.com/nWidart/PHP-MySQLi-Database-Class
2) Always keep your database connection string to separate file and at safe place. then, include your connection file into your require project file.
3) Always validate value of your variables & use mysql_real_escape before using directly into query.
Try
$password = mysql_real_escape($_POST['password']); //to avoid SQL injunction
$username = mysql_real_escape($_POST['username']);
$credentials = "select * from Credentials where username = '$username' AND password = '$password' AND email_address = 'email_address'" ;
Related
I am new to php, I am learning how to update table using php with help of sql queries. But somehow, I have got stuck at the SQL query part. It always shows an error that I cant understand.
The query which I use is : $query= "UPDATE users SET username = '$username' , password = '$password' WHERE id = $id " ;
And the error that I get is :
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near '' at line 1
At first I was looking for any syntactical errors but I guess that's not the case..
I am also mentioning the validation isset code that I have been using just in case.
<?php
include "db.php";
include "functions.php";
?>
<?php
if(isset($_POST["submit"])){
$username= $_POST["username"];
$password= $_POST["password"];
$id= $_POST["id"];
$query= "UPDATE users SET username = '$username' , password = '$password' WHERE id = $id " ;
$result=mysqli_query($connection,$query);
if(!$result){
die("QUERY FAILED".mysqli_error($connection));
}
}
?>
$connection has already been defined at db.php..
Can you please tell where my fault is ??
If you are getting id,username and password values then
Just Try this
$query= "UPDATE `users` SET `username` = '$username' , `password` = '$password' WHERE `id` = $id " ;
Are your passwords hashed in your database? If so, that could be your problem. Try this.
$password = mysqli_real_escape_string($_POST['password']);
$hashed_password = password_hash($password, PASSWORD_BCRYPT, array('cost => 12'));
$query= "UPDATE `users` SET `username` = '$username' , `password` =
'$hashed_password' WHERE `id` = $id " ;
If you are storing your password in your database as plain text, I would recommend using this password_hash function. I would also recommend checking out prepared statements for this as well as it is more secure and will help to protect against sql injection.
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."'";
Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)
If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();
I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);
You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.
$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)
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
I'm kinda new to PHP and only using it for the backend of my Android App.
I've got three strings that I'm sending to the PHP from my Android App. I want to query a table called 'users' and find the userid of the username that was sent from my Android App and then inset the data into a seperate table called 'msg'.
I've tried for my life and I cannot get it to work, plus I haven't even finished.
thanks and helping me would be pretty amazing, as I'm new to PHP and can't finish off the rest of the code.
PHP:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!dbc) {
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain, $dbc");
if (!db_select){
die("Can't connect :" .mysql_error);
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
$query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$query', '$frienduser', 'msg'
);
echo ($msg);
?>
how about putting quotes around $query1 like
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (`id` ,`friendid` ,`msg`)
VALUES ('$query', '$frienduser', 'msg')");
Should be
$query = mysql_query("SELECT * FROM users WHERE usernames ='$username'");
$result = mysql_fetch_array($query);
$query1 = mysql_query("INSERT INTO gtanews1_zips54.msg (id,friendid,msg) VALUES ('" . $result['yourField'] . "', '$frienduser','$msg')");
your mysql select db code is wrong. you need to have the quotes before the comma
mysql_select_db("andagain", $dbc);
also place quotes at the end of your query
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'"); $query1 = mysql_query(INSERT INTO `gtanews1_zips54`.`msg` ( `id` , `friendid` , `msg` ) VALUES ( '$query', '$frienduser', 'msg' )");
There's a lot going wrong here:
<?php
$username = $_POST['username'];
$msg = $_POST['msg'];
$frienduser = $_POST ['frienduser'];
/*mysql data below */
$dbc = mysql_connect('localhost', 'removemypasswords', 'again');
if(!$dbc) { //- You forgot the dollar $ sign on $dbc
die("Something went wrong! Try again...");
}
/* select database */
$db_select = mysql_select_db("andagain", $dbc); //- You had the entire thing quoted, quotes are just around "andagain"
if (!db_select){
die("Can't connect :" .mysql_error()); //- You forgot the parentheses after mysql_error
}
$query = mysql_query("SELECT FROM users WHERE usernames ='$usernames'");
//- You need to actually get the results out of the query object
$row = mysql_fetch_assoc($query);
if (!$row) {
die('User not found');
}
$user_id = $row['id']; //- Or whatever the column is called
$query1 = mysql_query("INSERT INTO `gtanews1_zips54`.`msg` (
`id` ,
`friendid` ,
`msg`
)
VALUES (
'$user_id', '$frienduser', 'msg'
"); //- You forgot to put quotes around this query
echo ($msg);
?>
And that's just to start, there may be other problems depending on your database schema / data transfer format.
Also, you're wide open to SQL injection.
your code have many errors .
$db_select = mysql_select_db (andagain, $dbc);
$query = mysql_query('SELECT FROM users WHERE usernames ="$usernames"');
since Stackoverflow is not a community for fixing codes bugs ..so i am leaving this job for you .
below are some points which can help you to fix all errors ?
Variable-substitution cann't be dont with single quotes (') . double quotes allow variable substitution .
to escape quotes inside quotes , we use \
parameter cannot be encapsulated with double quotes .