I am creating an edit profile page where the logged in user can edit the profile. I now run into the error below. what do i do?
ERROR:
Database Connection FailedYou have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= 'test#hotmail.com', Password = 'test', FirstName = 'hello', SecondName = 'world' at line 1
My code:
<?php
$connection = mysqli_connect('localhost', 'root', '', 'dbrateme');
if (!$connection){
die("Database Connection Failed" . mysql_error());
header('Location: dcf.php');
}
$select_db = mysqli_select_db($connection, 'dbrateme');
if (!$select_db){
die("Database Selection Failed" . mysqli_error());
}
if (isset($_POST['upd'])){
$course = $_POST['Course'];
$email = $_POST['inputEmail'];
$password = $_POST['inputPassword'];
$FN = $_POST['FirstName'];
$SN = $_POST['SecondName'];
$qsql = $_COOKIE['userID'];
$qresult = mysqli_query($connection, $qsql);
$qcount = mysqli_connect($qresult);
$sqli = "UPDATE tblaccounts Email = '".$email."', Password = '".$password."', FirstName = '".$FN."', SecondName = '".$SN."', Course = '".$course."' WHERE Student_ID='".$qsql."'";
$result = mysqli_query($connection, $sqli) or die("Database Connection Failed" . mysqli_error($connection));
//$count = mysqli_num_rows($result);
echo "Profile Update Successful!:";
header('Location: profile.php');
} else {
echo "Profile Update Failed!:";
?><br/>Go back to the profile update screen.<?php
}
?>
You miss the keyword set in your SQL. Syntax for Update is UPDATE <table> SET <colum Name> = value
$sqli = "UPDATE tblaccounts SET Email = '".$email."', Password = '".$password."', FirstName = '".$FN."', SecondName = '".$SN."', Course = '".$course."' WHERE Student_ID='".$qsql."'";
Learn about prepared stateemnts to prevent SQL injection.
Never store passwords as plain text. Use function to encrypt them
The issue is with the query, but my god are you open to a serious case of sql injection. To target the first issue.
UPDATE tblaccounts Email
Change this to
UPDATE tblaccounts SET Email
The query you are using is vulnerable to sql injection. You should fix this as soon as possible. I would suggest using PDO prepared statements for all of your SQL queries. http://php.net/manual/en/book.pdo.php
Related
I am fairly new to SQL and I am trying to write code to insert information from a messages form. Here is the SQL code:
$con = mysqli_connect($hostname,$username,$password,$db);
// Check connection
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$message = mysqli_real_escape_string($con, $_POST['message']);
$sql = "INSERT INTO messages (name, email, message) VALUES ( '$name' , '$email' , '$message' )";
if (!mysqli_query($sql)) {
die ('Error: ' . mysqli_error());
}
else {
echo "<html><script language='JavaScript'> alert('Thank you for your submission.'),window.location = 'home'</script></html>";
}
This code returns "Error: " that I interpreted as it thinking there is an error, but there isn't any errors. The connection variables in mysqli_connect are all correct, but I am unsure if I am using the mysqli_real_escape_string correctly and even the $sql statement, because this code also doesn't insert anything into my database. Thanks in advance.
As per the mysqli_query() documentation, if you are using the procedural notation you need to include your mysqli link:
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
This would suggest you need to pass in $con to mysqli_query() as you have with your other function calls as below:
mysqli_query($con, $sql)
Also, please look up and read about parametrization as your code as it is should not be used on a live site as you are vulnerable to SQL injection. Please take the time to read this and learn how to prevent it.
Try running the query this way
mysqli_query($con, $sql);
mysqli_query requires the link to your db connection which is "$con"
I am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.
I've followed a year old online tutorial of Unity Client - PHP Server - Database integration. The code seems to execute fine, it reaches the 'echo"Success"' line etc perfectly.
However when I look at my database, there is nothing there. Its blank, and I have no idea why.
Note: The online tutorial used mysql... whereas I'm using the (non-depracted) mysqli... but there didn't seem to be that much of a difference, but I'm a total rookie at PHP coding, only having minimal experience at it so it is very possible I'm wrong?
<?php
/**
* Created by PhpStorm.
* User: Josh
* Date: 09/04/2016
* Time: 14:11
*/
$Username = $_REQUEST["Username"];
$Password = $_REQUEST["Password"];
$Hostname = "localhost";
$DBName = "statemilitaryrpdb";
$User = "root";
$PasswordP = "";
$link = mysqli_connect($Hostname, $User, $PasswordP, $DBName) or die ("Can't Connect to DB");
if (!$Username || !$Password) {
echo "Empty";
} else
{
$SQL = "SELECT * FROM accounts WHERE Username = '" . $Username ."'";
$Result = #mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total == 0)
{
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
$SQL1 = mysqli_query($link, $insert);
$Result2 = #mysqli_query($link, $SQL) or die ("DB ERROR");
echo(mysqli_num_rows($Result2));
}
else
{
echo"Username Already Used";
}
}
mysqli_close($link);
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Answer: Username and Password are the fields but you are trying to insert Username, Password and 0
Suggestion: Do more than just MD5 encryption, that is SUPER easy to decrypt.
Edit:
Also like #andrewsi said in the comments if your only going to check if its empty, than anyone could SQL inject your database and drop your tables or make changes. Make sure that you are filtering your inputs correctly.
Firstly, your query have only 2 columns, but you are inserting 3 values:
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Columns
Username
Password
Values to insert
$Username
md5($Password)
0
Thus, not all the values will be inserted.
Secondly, for MySQL related names, you need to use back ticks instead of single-quote.
Thus, this:
INSERT INTO 'accounts'
Should be:
INSERT INTO `accounts`
Thirdly, your code is vulnerable to MySQL Injection, you should prevent it using mysqli_real_escape_string():
$Username = mysqli_real_escape_string($link, $_REQUEST["Username"]);
$Password = mysqli_real_escape_string($link, $_REQUEST["Password"]);
Tip: You shouldn't suppress error messages:
#mysqli_query($link, $SQL)
Remove # to enable error reporting. It's very useful in diagnosing syntax errors.
Also, you shouldn't use md5() to hash passwords, as it's not very secure. Use password_hash and password_verify instead.
In debug mode, never use # to suppress errors, ie. #mysqli_query. Also or die("DB ERROR") isn't very descriptive. Even if that resolves, what good does DB ERROR provide you? Instead, use or die( mysqli_error($link) ) to see what's really going on with the query.
You also have 3 values to be inserted, but only 2 columns represented in the query statement:
('Username', 'Password') // 2 columns
VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)"; // 3 values
What column is 0 being inserted into? This value needs to be represented by a column.
And a table/column name should never be wrapped with quotes; only ticks `accounts`
While giving the correct login ID and Password which is there in the databse "tutorial" in table "users", it is giving me an error on the login.php which is being redirected.
Error is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''users' WHERE 'user' = 'XYZ'' at line 1
where XYZ is the username given from the user.
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "tutorial";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or die("Database not found");
$query = "SELECT * FROM 'users' WHERE 'user' = '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password' = '$inputpass'";
$result = mysql_query($query) or die(mysql_error());
$resultpass = mysql_query($querypass) or die( mysql_error());
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row["user"];
$serverpass = $row["password"];
if ($serveruser && $serverpass){
if(!$result){
die("Username Name or Password is invalid");
}
echo "<br><center>Database Output</b> </center><br><br> ";
mysql_close();
echo $inputpass;
echo $serverpass;
if($inputpass == $serverpass){
header('Location: home.php');
} else {
echo "Sorry, bad Login";
}
}
?>
Abhik Chakraborty is correct.
If you want to enclose field/column or table names you have to use backticks (so ` instead of '). The backtick is the diagonal quote on the button next to the "1", above "Tab".
To enclose field values you should use quotes the way you did.
Your corrected query: SELECT * FROM `users` WHERE `user` = '$inputuser';
HOWEVER, you should never, ever insert input gotten from a user directly into a query. If they type in something like a';DROP TABLE your_table_name; they can cause your database to start deleting tables, requesting records, etc.
Use correct escaping of user input: see this StackOverflow article on how to safely escape user input.
Instead of single quotes you should use back ticks (`)
This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";