I've tried finding a fix to this, in fact some of this code was ripped out of previous "fixes" I found that didn't work. I'm pretty new to php so I may be missing something obvious. Here's the source.
<?php
$device=$_POST['Device'];
$license=$_POST['License'];
$tbl_name="tablename";
$con = mysql_connect("url", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$query="INSERT INTO $tbl_name(Id, Device Key,License Key)VALUES('', '$device', '$license')";
if (!(mysql_query($query,$con)))
{
die('Error: ' . mysql_error());
}
echo "1 device added was added.";
mysql_close($con)
?>
This is my error
Error: 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 'Key,License Key)VALUES('', 'Device Key Here', 'License Key Here')' at line 1"
Basic SQL syntax: identifiers (field names, table names, etc...) cannot have spaces in them:
$query="INSERT INTO $tbl_name(Id, Device Key,License Key)VALUES('', '$device', '$license')";
^---wrong ^---wrong
Generally speaking, you should never have spaces in your names. Use an _ instead, if you have to.
If you can't/won't rename the fields, you'll have to properly quote them:
$query="INSERT INTO $tbl_name(Id, `Device Key`,`License Key`)VALUES('', '$device', '$license')";
Related
I installed MySql on my Raspberry Pi 2 Model B+ a few days ago to see if I could use it, PHP, phpmyadmin, and Apache to make an accessible database to organize and catalog books that are around the house. I have a table in a MySQL database set up as a prototype with three columns; Booknumber (set to auto-increment), title, and authorLastName. I'm trying to use a form to insert books into table beta, in database bookProof.
Here's the code for the form:
<html>
<body>
<form action="catalog.php" method="POST">
<p>Book Title: <input type="text" name="title"></p>
<p>Author's Last Name: <input type="text name="authorlastname"></p>
</form>
</body>
</html>
Which links to "catalog.php", which is:
<?php
define('DB_NAME', 'bookProof');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Could not connect: " . $conn->connect_error);
}
$value = $_POST["title"]
$value2 = $_POST["authorlastname"]
$sql = "INSERT INTO beta ('title', 'authorLastName') VALUES ('".$value."', '".$value2."')"
$query = mysqli_query($conn,$sql);
if ($conn->($sql) === TRUE) {
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When demoform.php is opened, it functions normally, but when the "Add Books" button is clicked, it goes to catalog.php as intended, but the catalog.php page is blank, the table is unchanged, and Google Chrome's "Inspect" tool gives the error:
POST http://192.168.254.11/Library/catalog.php 500 (Internal Server Error) catalog.php:1
If anyone knows how to get the input to the database, please let me know.
Note: This is just a home system, so security is not a priority (I don't need SQL code injection protection).
Your note, "...security is not a priority (I don't need SQL code injection protection)" - you might think that, but you should do it anyways. Not only does it protect your database should your system be exposed (or made public at a later time), it will handle strings automatically for you, so that your query won't break if your strings have quotes ' in them.
One issue is that you're using singlequotes around column and table names. This should be backticks, or none at all. Then you were missing a semicolon ; after defining your $value, $value2 and $sql strings.
Then you're doing something a bit odd - which is also causing a parse-error (Had you enabled error-reporting and checked your logs, you'd see a "Parse error: syntax error, unexpected (" error in your logs), you're querying the table with mysqli_query(), but then you try to do it again - except you're trying to query on the querystring, and not the query method. Note the comments I've added in the code below.
// Don't use singlequotes ' for columns and table-names
// Use backticks ` - quotes are for strings
$sql = "INSERT INTO beta (`title`, `authorLastName`) VALUES ('".$value."', '".$value2."')"; // You were also missing a semicolon here!
// $query = mysqli_query($conn,$sql); // Remove this line, as you're attempting to query it twice
if ($conn->query($sql) === TRUE) { // You're missing the query() method here
echo "New entry completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Using prepared statements won't be that much of a difference, and you really should do it. There's absolutely no reason to not use prepared statements! Look how little changes that have to be made!
$sql = "INSERT INTO beta (title, authorLastName) VALUES (?, ?)";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ss", $value, $value2);
$stmt->execute();
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You've also got some invalid HTML which would cause issues - the following line had a missing quote to close off the type attribute.
<input type="text" name="authorlastname">
I suggest you read the following documentation and articles
When to use single quotes, double quotes, and backticks in MySQL
How can I prevent SQL injection in PHP?
PHP manual on mysqli_stmt::bind_param
How to get useful error messages in PHP?
PHP Parse/Syntax Errors; and How to solve them?
As a final note, you should check that the form was submitted and that it has values before inserting into the database. Also, using variable-names like $value and $value2 are not really descriptive - you should avoid it and use proper names for your variables.
I have tried a lot of syntax trials with single quotes and $session variables, now i decided to put the session variables in regular variables for less syntax complications.
$conn = mysql_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysql_error());
}
if (!mysql_select_db($dbname)) {
die('Could not select database: ' . mysql_error());
}
$this_email = $_SESSION['email'];
$this_password = $_SESSION['pw'];
$this_number = $_SESSION['phone'];
$sql = mysql_query("INSERT INTO user_accounts(Email, Password, Phone#) VALUES ('$this_email','$this_password','$this_number')");
if (!$sql) {
echo mysql_error();
}
mysql_close($conn);
This is the error i get:
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
Column names may have basic Latin letters, digits 0-9, dollar, underscore. All other characters will need to be in backticks.
http://dev.mysql.com/doc/refman/5.7/en/identifiers.html
so try:
INSERT INTO user_accounts(Email, Password, `Phone#`)
You also should update your driver and use prepared statements.
Because Phone# has a special character in it (#) you need to write it in backticks!
Furthermore I would recommend you to use the PDO or mysqli lib as well as prepared statements, because the mysql library is deprecated.
hostSo i know how to get the two fields to concatenate from directly inside of MYSQL, but having trouble getting it to work with my PHP.
Directly from MYSQL = SELECT CONCAT(ConfigurationItem, ' - ', ,Buzzword) FROM Buzz;
But how do i incorporate it into this PHP below, I have researched to no end. I want to combine the two fields ConfigurationItem and Buzzword into a field named shortdescription, without having to do it manually through MYSQL everytime the PHP is submitted.
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buzz_feed", $con);
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword, OccurrenceDate, PostingDate, TierStatus, MasterTicket)
VALUES
('$_POST[BuzzID]','$_POST[ConfigurationItem]','$_POST[Buzzword]','$_POST[OccurrenceDate]','$_POST[PostingDate]','$_POST[TierStatus]','$_POST[MasterTicket]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Buzz Phrase information updated";
mysql_close($con)
?>
I've concatenated them together in php as the insert.
Although there is nothing wrong with catting them in your select statement.
In fact I'd opt for that because it is redundnant-y, you are inserting the same data twice in essence.
But this should do what you are asking for.
I have also corrected your quotation marks in the query.
Also google sql injection
<?php
$con = mysql_connect("host","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("buzz_feed", $con);
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword,
OccurrenceDate, PostingDate,
TierStatus, MasterTicket, shortdescription)
VALUES
('".$_POST['BuzzID']."','".$_POST['ConfigurationItem']."',
'".$_POST['Buzzword']."','".$_POST['OccurrenceDate']."','".$_POST['PostingDate']."',
'".$_POST['TierStatus']."','".$_POST['MasterTicket']."',
'".$_POST['ConfigurationItem']."' - '". $_POST['Buzzword']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Buzz Phrase information updated";
mysql_close($con)
?>
I ended up resolving my issue by inserting "ShortDescription" in the INSERT INTO line and then just telling it to insert the two fields I wanted together in the field "ShortDescription" and by using double spaces between my hyphen, I was able to get the desired effect I was looking for which turns out like this "Example - Example" See my code below
$sql = "INSERT INTO Buzz (BuzzID, ConfigurationItem, Buzzword, OccurrenceDate, PostingDate, TierStatus, MasterTicket, ShortDescription)
VALUES
('$_POST[BuzzID]','$_POST[ConfigurationItem]','$_POST[Buzzword]','$_POST[OccurrenceDate]','$_POST[PostingDate]',
'$_POST[TierStatus]','$_POST[MasterTicket]','$_POST[ConfigurationItem]' ' - ' '$_POST[Buzzword]')";
I am receiving the error:
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 'long='-96.7812', label='abc' WHERE id='2'' at line 1
Here is my code:
$db=mysqli_connect($server,$username,$password,$dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
$sql="UPDATE locations SET name='$_POST[modname]', lat='$_POST[modlat]', long='$_POST[modlong]', label='$_POST[modlab]' WHERE id='$_SESSION[locnid]'";
echo $sql;
if (!mysqli_query($db,$sql)) {
die('Error: ' . mysqli_error($db));
}
echo "1 record modified";
mysqli_close($db);
The $sql string echoed is this:
UPDATE locations SET name='Baylor', lat='32.7923', long='-96.7812', label='abc' WHERE id='2'
I don't see anything wrong with that.
I tried escaping the values (didn't think it would help and it didn't):
$sql="UPDATE locations SET name='".mysqli_real_escape_string($db, $_POST[modname])."', lat='".mysqli_real_escape_string($db, $_POST[modlat])."', long='".mysqli_real_escape_string($db, $_POST[modlong])."', label='$_POST[modlab]' WHERE id='$_SESSION[locnid]'";
I get the same error and the same $sql string echoed out.
Thought maybe it had to do with the decimal points messing up the $sql string assignment, but even with whole numbers I get the same error.
Please help - if you can spot what the syntax error could possible be!
The column name long you have used is a reserved word in MySQL , Enclose it in backticks !
See here [An exerpt from your query]
g($db, $_POST[modlat])."', `long`='".mysqli_real_es
^ ^ ----- Enclose it like this
Try this:
$sql="UPDATE locations SET name='$_POST[modname]', lat='$_POST[modlat]', `long`='$_POST[modlong]', label='$_POST[modlab]' WHERE id='$_SESSION[locnid]'";
The column name long is a reserved word in MySQL. It should be enclosed between backticks.
I am trying to store data into database. if i am using the following code
$sql="INSERT INTO rohit(content,tags,uniquefield,required)
VALUES('$l','$y','$z','$t')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
it is running but when i am adding one more field then it is giving error check mysql syntax
$sql="INSERT INTO rohit(content,tags,uniquefield,required,numeric)
VALUES('$l','$y','$z','$t','$n')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
i have defined all the fields in database. what may be the possible error
numeric is a reserved word. Place it in tics to escape it:
$sql="INSERT INTO rohit(content,tags,uniquefield,required,`numeric`)VALUES('$l','$y','$z','$t','$n')";
because you are trying to add a string value to the numeric field and I guess that the type of that columns is not a string, because of the name