Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So, I am trying to debug a program of mine, It is a simple PHP code for inserting into a database.
Whenever I run this in my browser :
http://localhost:3456/maps/savemdata.php?descr=Best&lat=-37.12345&lng=122.12345
It should Insert the values into the DB, but what I get is :
Invalid query: 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 'desc, lat, lng ) VALUES ('Best', '-37.12345', '122.12345' )'
at line 1
Savemdata.php
<?php
$hostname = '127.0.0.1:3306';
$dbname = 'login'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
mysql_select_db($dbname) or DIE('Database name is not available!');
// Gets data from URL parameters
$desc = $_GET['descr'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
" (desc, lat, lng ) " .
" VALUES ('%s', '%s', '%s' );",
mysql_real_escape_string($desc),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
DESC is a keyword in mysql. You should take it in backticks ;)
desc is a reserved keyword and happens to be the name of your column. To avoid syntax error, you need to escape it using backtick. eg,
$query = sprintf("INSERT INTO `markers` " .
" (`desc`, `lat`, `lng` ) " .
" VALUES ('%s', '%s', '%s' );",
mysql_real_escape_string($desc),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng));
MySQL Reserved Keywords List
If you have the privilege to alter the table, change the column name to which is not a reserved keyword to avoid problem from occurring again.
Rahul, i would suggest you to use PDO. Try changing your code in the below way.
<?php
$hostname = '127.0.0.1:3306';
$dbname = 'login'; // Your database name.
$username = 'root'; // Your database username.
$password = '';
// database connection
$conn = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
// new data
$desc = $_GET['descr'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
// query
$sql = "INSERT INTO markers (desc,lat,lng) VALUES (:desc,:lat,:lng)";
$q = $conn->prepare($sql);
$q->execute(array(':desc'=>$desc,
':lat'=>$lat,
':lng'=>$lng));
?>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to take a string username from my android app and use that username to add 5 points to that specific users account.
Example:
My database now: user_id name username password points
1 test test test 0
What I want: user_id name username password points
1 test test test 5
Here is the php code I'm using right now, something must be wrong with it:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$sql = "UPDATE user ". "SET points = points + 5 ". "WHERE username = $username" ;
$response = mysqli_query($sql, $con);
?>
You confused the parameters for mysqli_query. It should be mysqli_query($con, $sql); instead. Also there are a couple of other problems - this should work:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = mysqli_real_escape_string($con, $_POST["username"]);
$sql = "UPDATE user SET points = points + 5 WHERE username = '$username'" ;
$response = mysqli_query($con, $sql);
?>
As it was suggested, prepared statements are the preferred way to go. So you could do this... tested it now, and it works for me:
<?php
$points = 5;
// Connect to database (credentials should not be stored in code...)
$con = new mysqli("localhost", "id177667_root", "***", "id177667_loginb");
// Check if connection succeeded
if ($con->connect_error)
die("Connection error: " . $con->connect_error);
// Prepare statement
if ($st = $con->prepare("UPDATE user SET points = points + ? WHERE username = ?")) {
// Bind parameters (i for integer value, s for string)
$st->bind_param("is", $points, $_POST["username"]);
// Execute statement
$st->execute();
// Close statement
$st->close();
} else {
// Prepare failed: report error
die("Prepare failed: " . $con->error);
}
// Close DB connection
$con->close();
?>
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`
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
hi i am getting this error though i tried to change the new to i am stil getting this problem can anyone tell me what should i do. I have completely changed the page also database but still same error.
error>
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 ''calendar_admin' WHERE teacher_id='ipcst123' and password='a141c47927929bc2d1fb6'
at line 1
my code >
<?php
$username=$_POST['teacherId'];
$password=$_POST['password'];
$password=md5($password);
try {
$bdd = new PDO('mysql:host=localhost;dbname=XXX', 'XXX', 'XXX');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$query ="SELECT * FROM 'calendar_admin' WHERE teacher_id="."'".$username."' and password="."'".$password."' ";
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
$res = $resultat->fetchAll(PDO::FETCH_ASSOC);
foreach($res as $result){
$pass=md5($password);
$user=$result["teacher_id"];
if ($pass==$result["password"]&& $username == $user ){
echo "login Success";
session_start();
$_SESSION['teacher_id'] = $username;
header('Location:/addEvents.php');
}else{
header('Location:/login.php');
//echo "Incorrect Password";
}
}
You should use backticks instead of single quotes :
$query ="SELECT * FROM `calendar_admin` WHERE teacher_id='".$username."' and `password`='".$password."' ";
or just remove them
$query ="SELECT * FROM calendar_admin WHERE teacher_id='".$username."' and `password`='".$password."' ";
And since you use PDO, you should bind parameters, but not concatenate them into the query:
$query ="SELECT * FROM calendar_admin WHERE teacher_id= :teacher and `password`= :password ";
$sth = $bdd->prepare($query);
$sth->bindParam(':teacher',$username);
$sth->bindParam(':password',$password);
$sth->execute();
$res = $sth->fetchAll(PDO::FETCH_ASSOC);
Around column and table names has to be backticks, not single quotes. O rnothing if the names aren't from reserved words (or spaces, or hyphens, or anything else that MySQL will scream about, #Fred -ii- in comments below):
`calendar_admin`
The full query:
$query ="SELECT *
FROM `calendar_admin`
WHERE teacher_id = '" . $username . "' AND
password = '" . $password . "'";
Don't forget to escape data from user inputs.
$query = "
SELECT *
FROM calendar_admin
WHERE teacher_id = '$username'
AND password = '$password';
";
Next, take a look at prepared statements
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm sure it's a kickself-obvious typo, but I can't see it. I'm trying to INSERT data taken from a HTML form using POST into a MySQL database using PHP. The POST works successfully, but the query fails; I've checked the table to make sure nothing new has been inserted.
Here's the PHP code intended to run the query:
if ($_POST) {
$username = "root";
$password = "root"; //ssh don't tell
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$dbname = "asoiaf";
$tablename = "charlist";
$id = '3';
$bookIntroduced = $_POST['bookIntroduced'];
$pageIntroduced = $_POST['pageIntroduced'];
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$oldSurname = $_POST['oldSurname'];
$alias = $_POST['alias'];
$title = $_POST['title'];
$pageIntroduced = $_POST['regnalNumber'];
// Below is the query that fails to execute.
$query = "INSERT INTO $tablename (
$id, $bookIntroduced, $pageIntroduced, $title, $forename, $surname, $oldSurname, $alias, $regnalNumber
)";
mysql_query($query) or die("Nah, I don't feel like being helpful.");
mysql_close($dbhandle);
}
And here is the structure of the table given by the DESCRIBE command:
Can anyone help me to identify the problem?
Also, if it wasn't clear, I'm new to PHP and SQL.
Doing a SQL query like this is bad practice in many ways, not least because it's extremely fragile and insecure, but I think it will work if you add VALUES and quote the strings.
$query = "INSERT INTO $tablename VALUES (
'$id', '$bookIntroduced', '$pageIntroduced', '$title', '$forename', '$surname', '$oldSurname', '$alias', '$regnalNumber'
)";
I advise against doing this though, and I'm giving this answer just because it's the shortest path to working code. Always name your table and columns (INSERT INTO mytable (col1, col2) VALUES (:val1, :val2)), and use prepared statements with mysqli.
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to insert data into a database through php.. Easy enough (I thought). I can't figure out what I am doing wrong. Here is my code:
$DB_HostName = "localhost:8888";
$DB_Name = "Sample";
$DB_User = "root";
$DB_Pass = "root";
$DB_Table = "Check";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "INSERT INTO $DB_Table (name) VALUES ('Sally') ";
mysql_query($sql) or die ("Error with Result");
mysql_close($con);
It gives me an error saying "Error with Result". This means that it must be connecting to the database correctly and everything is working right except for the end part.. What am I missing? If I say (msql_error()) it also does tell me to check the $sql. I can't figure out though what I am typing in wrong.
escape your database name with backtick
$sql = "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";
or
$sql = "INSERT INTO `" . $DB_Table . "` (name) VALUES ('Sally') ";
CHECK is a MySQL Reserved Keyword.
MySQL Reserved Keyword List
How can I prevent SQL injection in PHP?
I can't stress this enough, don't use mysql_ functions, that time has gone. Use either mysqli or PDO.
A simple way to check what is wrong with your SQL query is to add an error flag on the end of your die statement mysql_query($sql) or die ("Error with Result<br>".mysql_error());
It appears in your case that check is a constraint used to limit the value range that can be placed in a column. You would need to identify that it is a table using "`":
$sql = "INSERT INTO `$DB_Table` (name) VALUES ('Sally') ";