Issues with simple insert statement - mysql

I am working on this code and i am using a simple insert statement and I cant figure out why its not working. If anyone could see what I am doing wrong please let me know. Thanks!
This is the error I am getting:
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,comments)
VALUES (2 ,2012-11-18 21:25:30, 39.3436984, -76.5856958, hh)' at line 1
here is the code:
mysql_query ("INSERT INTO incidents (emergency_type,date_time,lat,long,comments)
VALUES (2 ,$catchDate, $catchLat, $catchLong, $catchDescription)") or die(mysql_error());
echo"<br /> Data inserted";

Long is a reserved word, try `long` surrounded with backticks instead.
Reference https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
A quick browse around the docs reveals that you should be investigating PDO::prepare and PDO::execute to do this. Your current method appears to be vulnerable to SQL injection.
I'm not a PHP programmer, but something like:
$db = get a db handle from somewhere
$st = $db->prepare('Insert Into Incidents (emergency_type, date_time, lat, `long`, comments) Values (?, ?, ?, ?, ?)');
$st->execute(array(2 ,$catchDate, $catchLat, $catchLong, $catchDescription));

LONG is a keyword/reserved word in mysql. You can use backticks to escape it
INSERT INTO incidents (emergency_type,date_time,lat,`long`,comments)
Or change your table column name to longitude

INSERT INTO incidents (emergency_type,date_time,lat,`long`,comments)
VALUES (2 ,$catchDate, $catchLat, $catchLong, '$catchDescription')
LONG is on the list of MySQL Reserved Keywords. Escape it with backtick instead.
One more thing, values for date_time and comments must be enclosed with single quotes as they are not numeric.
and you query is now vulnerable with SQL Injection, please take time t read the article below
How can I prevent SQL injection in PHP?

Related

Prepared statements in SQL query while saving JSON data in PHP

I have simple php code for parsing some data from a JSON file and saving them into mysql database. But it's showing following error:
Parse error: syntax error, unexpected 'my_name' (T_STRING) in C:\xampp\htdocs\mycode.php on line 25
My php code is following:
$sql = "INSERT INTO table1 (my_name, hobby, other) VALUES ($row['my_name'], $row['hobby'], $row['other'])"; //line 25
mysqli_query ($conn, $sql);
Why is it showing syntax error? Is there anything wrong in the query?
You need to enclose interpolated placeholders in curly braces, i.e. $row['my_name'] -> {$row['my_name']}:
$sql = "INSERT INTO table1 (my_name, hobby, other) VALUES ({$row['my_name']}, {$row['hobby']}, {$row['other']})";
This addresses only PHP syntax.
The SQL syntax error you get now is the next issue.
The simplest thing to "fix" this would be to include additional apostrophes around placeholders, i.e.
$sql = "INSERT INTO table1 (my_name, hobby, other) VALUES ('{$row['my_name']}', '{$row['hobby']}', '{$row['other']}')";
BUT DON'T DO THAT, since this code is an example of a classic SQL Injection vulnerability.
Consider using a prepared statement instead — this eliminates the PHP's string interpolation altogether.

Writing prepared mysql queries with node mysql?

I am new to node.js I don't know whether this is a correct way to write prepared statements in node.js I am using this package https://github.com/mysqljs/mysql I know there are lots of question in stackoverflow covering this but no one suggested this way my colleague suggesting me to do this now I am doubting him..
let query = "INSERT INTO ??(??, ??, ??, ??) VALUES (?, ?, ?, ?)";
let inserts = [`user_active`, `UID`, `rep`, `point`, `status`, `${UID}`, rep, `${point}`, status];
query = mysql.format(query, inserts);
console.log(query) //Spits out the query
You can use ES6 templet string to form the query.
You are already using ES6 templet string in insert statement you can use that to form entire string
let query = ‘INSERT INTO user_active(UID, rep, point, status) VALUES(${UID}, ${rep}, ${point}, ${status})’;
Not able to get perfect syntax for ES6 templet string as I am answering from mobile, google proper syntax for ES6 templet string. Only thing wrong in my syntax is opening and closing quotes for string.

PHP Registration to MYSQL Database

I have a problem here..
Im currently building a website(blog) where I want people to be able to register. And I want that information to be sent to my MYSQL
This is some of the code:
<?php
$query="INSERT INTO Medlemmar(namn, epost)
VALUES("$_GET[namn]", "$_GET[epost]")";
if (!mysqli_query($mysql_pekare,$query))
{
die("Error: " . mysqli_error($mysql_pekare));
}
echo "Du har lagt till kunden I databasen";
?>
But for some reason i get error on the "VALUES" part.. That im missing a syntax.. WTF am i missing?! Been stuck with this for 1+ hours.. Just had to turn here, usually a quick response! Thanks!
edit: "Parse error: syntax error, unexpected T_VARIABLE"
There are syntax errors all over the place... This needs some work.
<?php
$query = "INSERT INTO Medlemmar(name, epost) VALUES(\"".$_GET['namn']."\", \"".$_GET['epost']."\")";
That should fix the query... You need to learn how to escape \" double quotes so they can be used in the actual query.
try
VALUES ('".$_GET[a]."', '".$_GET[b]."')
or ' and " exchanged.
You are forgetting the single quotation marks around each value
The way you're managing registration is extremely insecure. If you were to set the namn and epost value to a sql query (like SELECT FIRST (username) FROM user_table) then it would execute that as behalf of the original sql query.
if you set username to SELECT FIRST (username) FROM user_table then it would return the first username in the user_table
To avoid this from happening you can use prepared statements which means that you specifically assign a sql query with a placeholder value and then you apply a value to the placeholder.
This would mean that you force the sql query to only execute what you've told it to do.
E.g. You want to JUST INSERT into a table and only do that and nothing else, no SELECT and no table DROP well in that case you create the prepared INSERT query with a placeholder value like this.
$db = new PDO('mysql:host=localhost;dbname=database_name', 'database_user', 'database_user_password');
// Create the register statement for inserting.
// Question mark represent a placeholder for a value
$register = $db->prepare('INSERT INTO users_table (username, password) values (?, ?)');
// Execute the register statement and give it values
// The values need to be parsed over in a array
$register->execute(array("test_user", "test_password"));
I'm not the best at explaining but if you want to understand what EXACTLY is going on here then this is a pretty good article which explains it in more detail.

insert query is not working in mysql

I really don't know what is happening insert query is not working for me.
$query_getgreenyear = "INSERT INTO `greenityear` `ConsolidateYear` VALUES ('".$sentdata."')";
in $sentdata the value is ('A','B') and the datatype for ConsolidateYear is varchar.I need this value to be inserted into the database.
but i am getting error
You have a SQL syntax error near 'ConsolidateYear VALUES ('('A','B')')' at line 1.
Please help me in this regard.
I am new to database activities.
You forgot to place a bracket() for your column name.
Try this:
$query_getgreenyear = "INSERT INTO `greenityear` (`ConsolidateYear`)
VALUES ('".$sentdata."')";
Please take a look at the MySQL Reference Manual.
You need to surround your column name with parantheses in your INSERT statement:
$query_getgreenyear = "INSERT INTO `greenityear` (`ConsolidateYear`) VALUES ('".$sentdata."')";
And I would highly recommend you to use prepared statements as provided by your MySQL-extension (at least if you're not using the deprectated mysql_connect). This protects you against SQL injections.
INSERT INTO `greenityear` (`ConsolidateYear`) VALUES (...)
But, you really should be using prepared statements and not constructing statements as you are.
the correct syntax is
INSERT INTO `tablename` (`columnname1`,`columnname2`) VALUES ('value1','value2')
so your example would be like this:
$query_getgreenyear = "INSERT INTO `greenityear` (`ConsolidateYear`) VALUES ('".$sentdata."')";

Update Else Insert MySQL query

Hello i was here yesterday with this problem, i don't really know how to use this site well as i am new so i reposted. but I'm getting an error with this block of code and i think its the Update query which contains a syntax error.
// Updates if player's record already exists
$result = mysql_query("UPDATE PlayerStat SET Position='$POS', Number='$NUM', Name='$PlyrName', Status='$Status', TDS='$TDS', INT='$INT', YDS='$YDS', RTG='$RTG', Team='$Team' WHERE Name='$PlyrName'");
echo mysql_error();
if (mysql_affected_rows()==0){
// Populates table if record is non existent
$result = mysql_query("INSERT INTO PlayerStat(`Position`, `Number`, `Name`, `Status`, `TDS`, `INT`, `YDS`, `RTG`, `Team`) VALUES ('$POS','$NUM','$PlyrName','$Status','$TDS','$INT','$YDS','$RTG','$Team')");
echo mysql_error();
}
The Error message
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 'INT='1', YDS='86', RTG='52.5', Team='ARI' WHERE Name='Bartel, Richard'' at line 1
INT is a keyword in mysql (declares and integer), if it's your column name you should surround it backticks (`) like so: `INT`.
It's good practice to put these in even though they're not necessary in all cases
UPDATE
PlayerStat
SET
`Position` = '$POS',
`Number` = '$NUM',
`Name` = '$PlyrName',
`Status` = '$Status',
`TDS` = '$TDS',
`INT` = '$INT',
`YDS` = '$YDS',
`RTG` = '$RTG',
`Team` = '$Team'
WHERE
`Name` = '$PlyrName'
Two things:
Check the manual for INSERT ... ON DUPLICATE KEY UPDATE which should do this in one statement.
I suggest you take a hard look at mysql_real_escape_string() or similar in PHP to escape your data and prevent SQL Injections.
If you don't know what SQL Injections are, then google it and spend a bit of time reading NOW before it's too late and some cracker or script kitty has your database.
Hope this helps!
You may want to check these websites.
http://www.w3schools.com/php/php_mysql_update.asp
http://www.tizag.com/mysqlTutorial/mysqlupdate.php
And you might also want to check your spelling mistake or the single quote or double quote. Other than that, check your database namings and data type.