I am going crazy [syntax error] [closed] - mysql

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 9 years ago.
Improve this question
I can't believe I am having this problem. I've been looking and looking but I can't see what is wrong. I hate this 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 ' poster_ip, message, posted, thread_id INTO posts ' at line 1
mysql_query("INSERT poster, poster_ip, message, posted, thread_id
INTO posts
VALUES (
{$post_info['poster']},
'".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
'".mysql_real_escape_string($post_info['message'])."',
{$post_info['posted']},
{$post_info['thread_id']}") or die (mysql_error());

Your SQL syntax is wrong.
You should be using something similar to:
INSERT INTO posts (poster, poster_ip, message, posted, thread_id) VALUES (...)

Maybe you should look at the doc ;)
Insert Syntax
If you're going to put the column names you should put it after the table name.
Example:
INSERT INTO table (col1, col2) VALUES (val1, val2)

Looks like a good opportunity to practice some debugging techniques. Try building the string you are passing to the function and assigning it to a variable, then echoing that variable to see what it is you are actually passing to the function. You can learn a lot that way about why you are getting errors. Also, it would help to know the data types of the columns you are inserting values into.

I have written this code to show you why arrays are useful for query generation and less likely to make a syntax error if you need to add more fields in future.
$fields = array('poster, poster_ip, message, posted, thread_id'); // Our fields
$table = 'posts'; // Our table name
$values = array(
$post_info['poster'],
$_SERVER['REMOTE_ADDR'],
$post_info['message'],
$post_info['posted'],
$post_info['thread_id']
);
$values = array_map('mysql_real_escape_string', $values); // Secure all inputs
// Generate query
$query = "INSERT INTO $table (" . implode(',', $fields) . ") VALUES ('" . implode("','", $values . "')";
// Run query
$result = mysql_query($query) or die('query error: ' . mysql_error());

Related

Remove escape symbols in string using mysql command [closed]

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 1 year ago.
Improve this question
I have a MySQL column with data looking like this,
I need to convert the column to the JSON format via convert(somecolumn,JSON). However, it seems that I first need to remove the escape symbols (e.g., \"). I did some search and found that mysql_real_escape_string will do the job (from this question).
But if I understand correctly, mysql_real_escape_string is a PHP command. Is there any native MySQL command that do similar thing as mysql_real_escape_string (something like convert(mysql_native_function(somecolumn),JSON))?
Use REPLACE. For harder things REGEXP_REPLACE.
SELECT REPLACE(somecolumn, '\"', '"')
SELECT REGEXP_REPLACE('"..."', '(^"|"$)', '')
The latter will unquote the entire string, as ^ is the start, and $ the end.
BTW I would actually correct all the data in the table once. (After a backup.)
The mysql library is old.. if you really need to use something like it - use mysqli
the mysql_real_escape_string is not as secure as you would think it to be, see this: https://security.stackexchange.com/questions/8028/does-mysql-escape-string-have-any-security-vulnerabilities-if-all-tables-using-l
That said you're much better off by not using any of them but using Php PDO and replacing something like:
$data = [
'name' => $name,
'surname' => $surname,
'sex' => $sex,
];
$sql = "INSERT INTO users (name, surname, sex) VALUES (:name, :surname, :sex)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
it will take care of the 'escaping' problems for you.
more examples here: https://phpdelusions.net/pdo_examples/insert

Num_rows doesn't work? [closed]

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 6 years ago.
Improve this question
I have a MySQL Database but my function is not working. I want to know how many results I get for my database query, but I just get nothing back, not even 0. I also tried $values->num_rows; same result. Do not get back a number... just nothing
My Code:
$values = $database->query("SELECT * FROM `wp_all_import_xml` WHERE name = '$title' AND price = '$price' AND shop = '$shop' AND link = '$link'");
$count_values = mysqli_num_rows($values);
echo "ERROR by detecting Product (More than 1 Row return by SQL!): " .$title. " Preis: " .$price. " Shop: " .$shop. " Link: " .$link. "\t num_rows: " .$count_values. "\n";
How can I get the amount of rows I get returned?
Greetings
The mysqli_num_rows function does work.
The most likely explanation for the observed behavior is an error is occurring and being ignored.
For debugging this, start with making sure error reporting is enabled.
Modify the code to check the return from the query. Verify that it's not returning FALSE, by performing a conditional test.
if ($values = $mysqli->query(...) ) {
// query returned a resultset
} else {
// query returned FALSE
}
If all we need to retrieve is the number of rows, then we can use COUNT(*) in the SELECT list.
if ( $res = $mysqli->query("SELECT COUNT(*) AS cnt FROM ... ") ) {
If the query is successful, then we get a row back, even if the count is zero. And we can easily process the result like we process results from other queries, without the need to muck with num_rows, and worrying about whether the query is buffered or unbuffered, etc.
We're going to assume that $database is a mysqli connection, and not a PDO connection, since the code includes a call to the mysqli_num_rows function. If it's PDO connection, then "num_rows doesn't work".
The code in the question follows the pattern frequently seen in code that is vulnerable to SQL Injection. (In this excerpt, we can't determine if the values of the variables being included in the SQL text are potentially unsafe, so we can't tell if it's vulnerable or not.)
If this was a prepared statement with bind placeholders, then we could tell.
Use prepared statements with bind placeholders. It isn't hard.

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.

SQL reserved word in an $array resulting in Error

I'm having a problem when I try to insert an array that has a reserved word on it.
It's really wierd I might say, take a look:
$sql="INSERT INTO sites (cat_id, cat_title, cat_parent, title, image, site_name, description) VALUES ('$_POST[cat_id]','$_POST[cat_title]','$_POST[cat_parent]','$title','$image','$site_name','$description')";
The array is comming from a opengraph fetch that I created but it's not important, the question is that sometimes when the array $title, for example, or $image has a reserved word like "use" on it, the sql return the error "Error: You have an error in your SQL syntax; check the manual that corresponds...."
so that's the case:
when the array $title = http://techcrunch.com/2012/08/28/flipboard-hits-20-million-users-3-billion-flips-per-month/ <---- it don't work and I receive the error above.
when the array is $title = http://techcrunch.com/2012/08/27/google-nexus-7-is-now-available-in-france-germany-and-spain/ <---- it works fine!
so I think that probably because theres a 'reserved word' in the array $title sometimes (or any other array that I'm using) that is returning the error... So theres any way that I could protect my arrays from this error?
Thanks! :)
EDIT:
SOLUTION
Ok! I followed the #dystroy and #tadman advice and used PDO instead of the regular mysql connection... I don't know if I'm totally secure against SQL injetion or attacks but it solve my problem with the reserved words. Now I can insert whatever content I have in an $array to the database.
If someone end up here with the same problem, that's what I did (please complain if you guys find any awkwardness):
$dbh = new PDO("mysql:host=MYHOST;dbname=MYDATABASE", "USER", "PASS");
$query = "INSERT INTO sites (cat_id, cat_title, cat_parent, title, image, site_name, description) VALUES (:cat_idpost, :cat_titlepost, :cat_parentpost, :titlepost, :imagepost, :site_namepost, :descriptionpost)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':cat_idpost', $cat_id);
$stmt->bindParam(':cat_titlepost', $cat_title);
$stmt->bindParam(':cat_parentpost', $cat_parent);
$stmt->bindParam(':titlepost', $titlepost);
$stmt->bindParam(':imagepost', $imagepost);
$stmt->bindParam(':site_namepost', $site_namepost);
$stmt->bindParam(':descriptionpost', $descriptionpost);
$cat_id = $_POST['cat_id'];
$cat_title = $_POST['cat_title'];
$cat_parent = $_POST['cat_parent'];
$titlepost = $title;
$imagepost = $image;
$site_namepost = $site_name;
$descriptionpost = $description;
$stmt->execute();
Thank you guys! :D
Always use prepared statement to insert strings in a database. Never simply concatenate them.
The problem isn't only reserverd words but all kind of errors (or attacks) due to special values or characters. Don't try to escape all this yourself : The database will handle that for you if you use a prepared statement.
Look at those samples based on today's recommended library for PHP/MySQL (PDO) : http://www.php.net/manual/en/pdo.prepared-statements.php
Escape reserved words like title with accents

sql injection protect [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
Is this code protected enough against sql injection
if(isset($_POST['Submit']))
{
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
$confirm_key=md5(uniqid(rand()));
$query = mysql_query("INSERT INTO members
(user, pass, mail, confirm_key, country, city, www, credo)
VALUES ('$user','$pass','$_POST[mail]','$confirm_key','$_POST[country]','$_POST[city]','$_POST[www]','$_POST[credo]')")
or die ("Error during INSERT INTO members: " . mysql_error());
exit();
}
Is this the right way and must be each input (like country, city...) be protected ?
DO NOT USE mysql_query for new applications. You should be using mysqli or PDO to do your escaping with placeholders. There are many examples you can use.
Generally your SQL should look like:
INSERT INTO `table` (column) VALUES (?)
It SHOULD NOT look like:
INSERT INTO `table` (column) VALUES('$dangerous_user_content')
If you use placeholders properly it's almost impossible to create a SQL injection hole.
http://php.net/manual/en/function.mysql-real-escape-string.php
Even the php docs say don't use mysql_real_escape_string