Query FailedYou have an error in your SQL syntax - php

I am trying to update mysql database using php.
$connection=mysqli_connect('localhost','root','','loginapp');
if(!$connection){
die("database connection failed");
}
if (isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password' ";
$query .= "WHERE id = $id";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Query Failed".mysqli_error($connection));
}
}
I have tried every possible way of writing the following code, but everytime I am getting the error:
Query FailedYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"

You must use prepared statements and switch on proper error reporting. Do not use die() to display error message. Do not store plaintext passwords in the DB, use password_hash() instead. A correct, but simple example of such code would be as follows:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli('localhost','root','','loginapp');
$connection->set_charset('utf8mb4');
if (isset($_POST['submit'])) {
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $connection->prepare('UPDATE users SET username=?, password=? WHERE id=?');
$stmt->bind_param('sss', $_POST['username'], $password, $_POST['id']);
$stmt->execute();
}

Related

why i trying to update the data, but it show me the error on the line "$result=mysqli_query($connection,$query);"

I have a problem on this, I can't find where is the problem in my code, anyone help me, pls.
<?php
if($_POST['submit']) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .="username = '$username' ";
$query .="password = '$password' ";
$query .="WHERE id = $id";
$result = mysqli_query($connection, $query);
if(!$result) {
die ('QUERY FAILED' . mysqli_error($connection));
}
}
?>
I need to update the new data into MySQL, but it show me the error message:
Fatal error: Uncaught mysqli_sql_exception: 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 'password='av' WHERE id='
Missing ',' in your query.
<?php
if($_POST['submit']) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', "; // missing ','
$query .= "password = '$password' ";
$query .= "WHERE id = $id";
$result = mysqli_query($connection, $query);
if(!$result) {
die ('QUERY FAILED' . mysqli_error($connection));
}
}
?>
The Update query should be :
UPDATE users SET username = 'username', password = 'password' where id = 1
As correctly pointed out by Majharul, the error is caused by the missing comma (,) between the columns listed in your SET clause. The error is almost always immediately preceding the part of the query returned in the error: password='av' WHERE id=.
More importantly, you should never store passwords in plain text, nor should you be simply concatenating strings and/or interpolating variables directly into your SQL. This is a very obvious SQL Injection vulnerability and easy to exploit. You should be using parameterized prepared statements to pass your variables into your query.
This is a simplistic example (validation of user input should be added) of how you might improve your code:
<?php
if($_POST['submit']) {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$id = $_POST['id'];
/* Prepare your UPDATE statement */
$stmt = mysqli_prepare($connection, 'UPDATE users SET username = ?, password = ? WHERE id = ?');
/* Bind variables to parameters */
mysqli_stmt_bind_param($stmt, 'ssi', $username, $password, $id);
/* Execute the statement */
$result = mysqli_stmt_execute($stmt);
if(!$result) {
die ('QUERY FAILED' . mysqli_error($connection));
}
}
Please read PHP docs for password_hash() for more detailed explanation.

Query is TRUE when its not

Please be gentle with me i have just recently trying to learn PHP/SQL.
The problem is that the first query is ALWAYS TRUE when it shouldn't (base on what i know).
The query simply state to get the 'username' where betakey=$betakey provided by user. The fact that my datebase columns is still empty except column betakey doesn't make that query statement true at all.
Please help, maybe i am missing some knowledge on this.
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host="localhost"; // Host name
$db_username="**"; // Mysql username
$db_password="**"; // Mysql password
$db_name="**"; // Database name
$conn = mysqli_connect("$host", "$db_username", "$db_password","$db_name");
if (!$conn){
die ("Error: ".mysqli_connect_error());
}
$query1 = "SELECT username='$username' FROM users2 WHERE betakey='$betakey';";
$result_1 = mysqli_query($conn,$query1);
if(mysqli_num_rows($result_1) > 0){
echo 'Beta key is used';
}else{
$query2 = "UPDATE users2 SET firstName='$firstName',lastName='$lastName',username='$username',password='$password' WHERE betakey='$betakey'";
echo 'Registration Successful';
}
mysqli_close($conn);//Close off the MySQL connection to save resources.
?>
You have plenty of problems in your code. Let me help you fix some of them
You should learn how to properly open mysqli connection. You need to enable error reporting and set the correct charset.
You should never concatenate PHP variables into SQL query. Always use parameterized prepared statements instead of manually building your queries.
Your first SQL query has an error. username='$username' is meaningless and wrong. If all you want to do is check existence use COUNT(1) or something similar.
Here is my take on your fixed code:
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host = "localhost"; // Host name
$db_username = "**"; // Mysql username
$db_password = "**"; // Mysql password
$db_name = "**"; // Database name
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($host, $db_username, $db_password, $db_name);
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare("SELECT COUNT(username) FROM users2 WHERE betakey=?");
$stmt->bind_param('s', $_GET['rusername']);
$stmt->execute();
$result_1 = $stmt->get_result();
$used = $result_1->fetch_row()[0];
if ($used) {
echo 'Beta key is used';
} else {
$stmt = $conn->prepare("UPDATE users2 SET firstName=?, lastName=?, username=?, password=? WHERE betakey=?");
$stmt->bind_param('sssss', $firstName, $lastName, $username, $password, $betakey);
$stmt->execute();
echo 'Registration Successful';
}

PHP not posting onto mySQL database

This code should check for existing usernames and if there isn't one, it should create a new one. No matter what it won't add. Additionally, as you can see in the code it only echoes 'here' and doesn't echo 'not here'.
<?php
$password = "hey";
$username = "hi";
require "conn.php";
//$password = $_POST["password"];
//$username = $_POST["username"];
echo 'here';
$result = $conn->query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
echo 'not here';
if ($result) {
if($result->num_rows === 0)
{
$stmt = $conn->prepare("INSERT INTO UserData (username,password) VALUES (:username,:password)");
$params = array(
':username' => $username,
':password' => $password
);
$stmt->execute($params);
}
}
?>
This is the connection code:
<?php
//$db_name = "xxx";
//$mysql_username = "xxx";
//$mysql_password = "xxx";
//$server_name = "xxx";
// Create connection
$conn = new mysqli("xxx","xxx","xxx","xxx");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Changes:
<?php
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', /*$_POST["username"]*/ $username );
$username = 'hi';
$stmt->execute();
$stmt->store_result();
echo "debug 2";
if ($stmt->num_rows == 0){ // username not taken
echo "debug 3";
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password =(/*$_POST["password"]*/ "hey");
$username =(/* $_POST["username"]*/ "hi");
$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);
$stmt2->execute();
if ($stmt2->affected_rows == 1){
echo 'Insert was successful.';
}else{ echo 'Insert failed.';
var_dump($stmt2);
}
}else{ echo 'That username exists already.';}
?>
This code gets through all of the debugs but for some reason, it is still not inserting.
Replace this line
$result = **$mysqli->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
with following
$result = **$conn->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
The mysqli and PDO interfaces must not be mixed. Here the database connection and the SELECT query are both using the mysqli interface. But the second INSERT query is attempting to use the PDO interface, as evidenced by the use of named placeholders, and also the passing of a data array directly to execute(). The latter two features are not supported by mysqli, hence the code fails at the second query. Also, note that the second query is using prepared statements, while the first one is not. Again, different approaches should not be mixed together.
Also it appears that passwords are being stored as plain text, with no security. The proper approach is to use the password_hash function.
Just ensure that the database field has enough width (say 80-120 characters or more) to handle the current bcrypt hash, plus allow some more for future changes.
Staying with the mysqli interface (and with password_hash), the code could go something like this:
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', $_POST["username"]);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0){ // username not taken
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$stmt2->bind_param('s', $_POST["username"]);
$stmt2->bind_param('s', $password);
$stmt2->execute();
if ($stmt2->affected_rows == 1)
echo 'Insert was successful.';
else echo 'Insert failed.';
}
else echo 'That username exists already.';
Note that the above approach would not be suitable for a high-traffic site, where there is a chance condition of another user trying to INSERT the same username, during the brief interval of time between the SELECT and INSERT database queries. That would require a different approach, like ensuring the subject database field is set to UNIQUE (which is good practice anyway), and then testing for violation of that UNIQUE field upon attempted duplicate insertion.
Assuming database and INSERT permissions are all set up OK and it is still not inserting, try enhancing the error-reporting.
Ensure the following are at the top of the page:
ini_set('display_errors', true);
error_reporting(E_ALL);
And put the following before the first query:
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
Then try again.

My MYSQL code isn't running

function UpdateTable(){
global $connection;
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query="UPDATE users SET ";
$query .="username = '$username' , ";
$query .="password = '$password' ";
$query .="WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result){
die("Database connection failed ".mysqli_error($connection));
}
}
this is the error message i get :
Database connection failed 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

PHP registered user check

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

Categories