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.
Related
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."'";
I have a Mysql Database named user. Here is a picture:
I want to change the Username of the user "dodlo.rg" programmatically.
Actually, I have the PHP-Version 7.1. And this is a part of my PHPCode:
EDITED CODE:
$newName= $_POST["changeT"];
$userId = $_POST["userId"];
$db = mysqli_connect("trolö", "trolö", "trolö123", "trolö")
$sql = "UPDATE user SET username = '$newName' WHERE user_id = '$userId'";
$query = mysqli_query($db, $sql);
$response["successU"] = true;
But I get the Error: "You gave an Error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1"
Thanks in advance.
The problem lies in 2 parts.
Firstly, since this column is a varchar field it needs to be inside quotes else it produces an sql error.
Secondly the SELECT statement just after is not valid, but i guess it was a copy/paste error.
Therefore your working code should be:
$newName= $_POST["changeT"];
$db = mysqli_connect("trolö", "trolö", "trolö123", "trolö")
$sql = "UPDATE user SET username = '".addslashes($newName)."' WHERE username = 'dodlo.rg'";
$query = mysqli_query($db, $sql);
$response["successU"] = true;
Also, please consider using your primary keys on your where statement rather a varchar field, as it'll improve speed when more complex queries. (eg. where user_id = 35 instead of where username = 'dodlo.rg' ).
Lastly, but quite important this code might be vulnerable to sql injections. You need to use prepared statements.
You have to convert this query into two parts
$sql1 = "UPDATE user SET username = $newName WHERE username = 'dodlo.rg'";
$sql2 = "SELECT * FROM user";
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 8 years ago.
Ok so I am having some issues with a query. I am working to learn MySQLi as well so there may be some errors. I have a table named Authentication and in it, it has these columns
||id
||UserName
||Password
When running the query I am getting my username as the column name so it gives the unknown column error. I can not seem to see what is wrong with my code. Any help is appreciated.
<?php
// Report all errors
error_reporting(E_ALL);
session_start(); // Start PHP
// Get info sent to server from login form.
$my_username = $_POST['username'];
$my_password = $_POST['password'];
// MD5 Encrypt the password.
$my_password_md5 = md5($my_password);
// Connect to DB
$db = new MySQLi('localhost', 'user', 'password!', 'database');
if ($db->connect_error) {
$error = $db->connect_error;
}
//SQL query
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = $my_username HAVING `username` = $my_password_md5
SQL;
$result = $db->query($sql) or die($db->error.__LINE__);
if($result = $db->query($sql))
$rows=mysqli_fetch_assoc($result);
// Count how many rows match that information.
$count=mysqli_num_rows($result);
// Check if there are any matches.
if($count==1)
{// If so, register $my_username, $my_password and redirect to the index page.
ini_set("session.gc_maxlifetime", "18000");
session_cache_expire(18000);
$cache_expire = session_cache_expire();
$_SESSION['username'] = $my_username;
$_SESSION['id'] = $rows['id'];
header("location:http://somesitegoeshere.com");
}
// If not, redirect back to the index page and provide an error.
else {
header("location:http://somesitgoeshere.com?err=1");
}
?>
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = $my_username HAVING `username` = $my_password_md5
SQL;
You forgot to quote $my_username. so your query looks like WHERE 'username' = abcdefg HAVING...
Mysql thinks you're trying to compare to a column, put your username in quotes. Also put your password in quotes so it doesnt think your password is a column.
$sql = <<<SQL
SELECT UserName
FROM `Authentication`
WHERE `username` = "$my_username" HAVING `username` = "$my_password_md5"
SQL;
I'm making a forum in PHP and MySQL (not a real one, just for practicing). and i made a login page. The problem is that for some reason after I'm writing the username and password and sending it, it keeps getting to the point which it gives me the echo of "wrong password or username". Yet every detail is correct (the names of the columns and the tables in my database are exactly the same in this code and the username and password are correct) so I'm guessing it's not the problem. Any help would be appreciated.
<?php
if(!empty($_POST['username'] ) && !empty($_POST['password'])){
require_once 'dbConnect.php';
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` =". $_POST['username'] . "AND `password` = " .sha1($_POST['password']));
if($user){
$data = array();
$data = mysql_fetch_assoc($user);
session_start();
$_SESSION['username'] = $data['nickname'];
echo $_SESSION['username'];
}
else {
echo "wrong password or username";
}
}
else {
echo "enter a username and a password";
}
?>
<form action="index.php?page=login" method="post">
<label>username:
<input type="text" name="username" required/>
</label>
<label>password:
<input type="password" name="password" required/>
</label>
<input type="submit" value="login!" />
</form>
the problem is that yout user and password columns are of type text / varchar. In order to produce a correct query, you have to wrap your values in quotes.
For example:
SELECT * FROM users WHERE username='name' AND password='mypassword'
So you have to alter your existing query like this:
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` ='". $_POST['username'] . "' AND `password` = '" .sha1($_POST['password']) . "'");
Mind the single quotes around your values.
In addition: The use of mysql_query is deprecated in PHP. Please use the PHP PDO Class. It supports parameter binding. In your case SQL Injection would be possible.
Comments to answer/answer.
There are a few things wrong with your code and here is what I recommend you do.
Start by defining your variables: (placed below require_once 'dbConnect.php';)
$username = $_POST['username'];
$pass = sha1($_POST['password']);
or, for some added security till you switch to prepared statements:
mysql_real_escape_string($_POST['username'])
mysql_real_escape_string(sha1($_POST['password']))
Then, change:
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` =". $_POST['username'] . "AND `password` = " .sha1($_POST['password']));
to
$user = mysql_query("SELECT `nickname` , `id` FROM `users` WHERE `nickname` = '".$username."' AND `password` = '".$pass."'");
As it stands, your present code is open to SQL injection. Use mysqli_ with prepared statements, or PDO with prepared statements.
Add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL); ini_set('display_errors', 1); during development.
Also or die(mysql_error()) to mysql_query() to signal any errors found.
You need to wrap the name and password you provided in quotes.
Concatenating the sql query can solve your error.
there is a mistake in your sql statement,you should not use the quotes in field name and wrap username and password provided
$user = mysql_query("SELECT nickname, id FROM users WHERE nickname ='". $_POST['username'] . "' AND password = '" .sha1($_POST['password'])."'");
<?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'" ;