Insert string values with apostrophe into MySQL table - php

I have read through some of the related questions but I still don't understand. So I decided to post a question here. I have a query like below
$query = "INSERT INTO Table (q1,q2,q3,q4....q25) VALUES ('".$_POST['Q1']."',
'".$_POST['Q2']."',
'".$_POST['Q3']."',
'".$_POST['Q4']."'.....)";
mysql_query($query);
The $_POST['Qx'] value is obtained from a survey where people are allowed to type in comments. Often people would like in words like "don't, can't, doesn't ...". The apostrophe will cause the problem when inserting the data to the table.
I have read through some articles suggesting the method of
mysql_real_escape_string($_POST['Q1'])
But I have 25 questions, some of them even have sub-questions.. so I have around 70 data to input to the table.
Is there any good method that I can adopt to be able to pass apostrophes into MySQL table?

edit: so I have around 70 data to input to the table.
70 is "nothing " for a for-loop ;-)
for($i=1; $i<71; $i++) {
$params[$i] = mysql_real_escape_string($_POST['Q'.$i], $link);
}
But you might want to consider a redesign of your database tables.
You have to encode/escape the parameters. In case of the (deprecated) mysql extension that would be mysql_real_escape_string()
$link = mysql_connect(...);
...
$query = sprintf(
"
INSERT INTO
Table
(q1,q2,q3,q4....q25)
VALUES
('%s','%s' ...)
",
mysql_real_escape_string($_POST['Q1'], $link),
mysql_real_escape_string($_POST['Q2'], $link)
...
);
mysql_query($query, $link) or die(mysql_error($link));
but better use a supported extension like mysqli or pdo.
And take a look at prepared statements.

Related

Adding record on database

I'm experiencing a strange problem with save query, and I'd like to better understand how to solve it.
I have a database with 2 tables, example:
TBL_PERSON
person_id
person_name
person_telephone
TBL_ADDRESS
address_id
address_person_id
address_address
address_city
address_zip
Now, I use a query like this to store records:
$sqlQuery = "INSERT INTO TBL_PERSON (
person_name,
person_telephone
) VALUES (
'$person_name',
'$person_telephone'
)";
$result = MYSQL_QUERY($sqlQuery);
//Get last id
$address_person_id = mysql_insert_id();
$sqlQuery = "INSERT INTO TBL_ADDRESS (
address_person_id,
address_address,
address_city,
address_zip
) VALUES (
'$address_person_id',
'$address_address',
'$address_city',
'$address_zip'
)";
$result = MYSQL_QUERY($sqlQuery);
Sometimes, no record is added on TBL_ADDRESS.
After the user presses Insert, Action Button, Name and Telephone are stored on TBL_PERSON, but not address on TBL_ADDRESS.
Barring the discussion on the use of deprecated an insecure mysql_* functions, I think this is a good opportunity to explain methods of debugging issues like this.
In the replacements for the mysql_* query functions, exceptions are thrown on errors allowing you to wrap the query in a try/catch block and handle it accordingly. In the case of mysql_query(), you will simply get false returned from the function. So to be able to debug and consequently see what is wrong, you need to do something like this (from the PHP manual):
$result = mysql_query('SELECT * FROM myTable');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If your query fails, you will see why, which is important in debugging.
As mentioned in the comments, you do not escape any of your values. Aside from the fact that you shouldn't be using these functions at all (see mysqli or PDO), you should at minimum be escaping your values using the mysql_real_escape_string() method:
$value = mysql_real_escape_string($value);
If you follow the above logic, you will see what is causing the issue, and I suspect fix it successfully using proper escaping of values. If it's not the value, you may have an issue with your database schema design such as a column that is not nullable and has no default value, yet you may be passing a null value.

How safe is this query method

If we can't use PDO or mysqli (for any reason), is this method safe for INSERT and SELECT?
<?php
if (!empty($_POST[id]) && !empty($_POST[name])) {
require_once ( 'config.php' );
// SAFE INTVAL ID
$id = intval($_POST[id]);
$connect = mysql_connect("$server", "$user", "$password")
OR die(mysql_error());
mysql_select_db("$database", $connect);
// ESCAPING NAME
$name = mysql_real_escape_string($_POST[name]);
$query = "INSERT INTO table (id, name) VALUES ('$id', '$name')";
$result = mysql_query($query, $connect);
if (!$result) { echo 'success'; } else { echo 'fail'; }
}
?>
cause i've read many times never to use mysql_query,
is it dangerous even if we are careful and escape in time?
As per my knowledge, your query is perfectly fine.
You are escaping the SQL with
mysql_real_escape_string($_POST[name])
This adds additional security to your code.
The only suggestion is that use:
$_POST['name']
instead of
$_POST[name]
As it will generate PHP warning.
Thanks.
To add to the other answers, it's "safe", as in the query can't be exploited. The one thing to watch out for though is that you're trusting your users to provide you with an ID (which I assume here is your primary key). Of course, this means that your users can overwrite other records.
A better way would be to omit the id column (and its value) from your query, and mark the column as AUTO_INCREMENT when creating the table. Any omitted value from a query becomes its default value, which in this case will normally be the last value of id+1.
Even though you say you can't use them, possibly because they're too complicated (?), you really should doing a little research and understanding how to use them. I promise that once you do, you won't even want to go back! :) I recommend using PDO / MySQLi because PHP 5.5 is depreciating MySQL and you'll get E_DEPRECIATED notices.
Prepared statements using MySQLi or PDO mean that you don't have to escape any strings, you simply refer to each variable with a ?, and then state later on what datatype the ? has s being string, for example.
You wouldn't need to use mysql_real_escape_string() then. Future proof your code! :)

SQL Insert and Submit

When I execute this query it returns false, which means the query is wrong. Can you figure out why?
$string1 = 'wee';
$string2 = 'wee';
$string3 = 'wee';
$string4 = 'wee';
if (isset($_POST['submit'])) {
$query = "INSERT INTO data (book, title, content, author)
VALUES ($string1, $string2, $string3, $string4)";
mysql_query($query, $con);
}
However, when I put something that is like the following, it returns true and inserts correctly:
$query = "INSERT into data (book, title, content, author)
VALUES ('wee', 'wee', 'wee', 'wee')";
And another question: when I submit, it seems that the query is returning twice when executed which means two records with one query. Does anyone understand that?
If you need more information, just ask.
Thanks in advance.
Although this question seems answered, you should not be using user input directly in queries as this opens holes for vulnerabilities like SQL Injection (and that's bad mmmay)
If you look at the mysql page on php.net (mysql_query) the page says it is recommended you use an abstraction layer like PDO (pdo-mysql)
Using PDO will allow you to bind parameters to your sql queries to bypass the security implications of using user input in your queries.
If you don't bind parameters to your queries, you're gonna have a bad time.
Your field data type is string or varchar so you need to put '' or "" around them.
Change your query as below
$query = "INSERT into data (book, title, content, author)VALUES ('".$string1."', '".$string2."',
'".$string3."', '".$string4."')";
To resolve submit issue, please post your html code

SQL and PHP problems

What is wrong with this query?
$query3 = "INSERT INTO Users
('Token','Long','Lat')
VALUES
('".$token."','".$lon1."','".$lat."')";
You have several issues with this.
Column names should be backtick escaped, not quoted (also LONG is a datatype in MySQL hence it's reserved and must be backtick-escaped).
You have SQL injection problems if those arguments aren't escaped.
You should provide us with the result of mysql_error() if it's not working.
Try running this code:
$token = mysql_real_escape_string($token);
$lon1 = mysql_real_escape_string($lon1);
$lat = mysql_real_escape_string($lat);
$query3 = "INSERT INTO `Users` (`Token`, `Long`, `Lat`)
VALUES ('{$token}', '{$lon1}', '{$lat}')";
$result3 = mysql_query($query3) or die("Query Error: " . mysql_error());
If that still doesn't work, give us the error message that's produced.
Long is the mysql reserved word and reserved words needs to be enclosed in backticks
$query3 = "INSERT INTO Users
(`Token`,`Long`,`Lat`)
VALUES
('".$token."','".$lon1."','".$lat."')";
You're using single quotes around your field names. This isn't valid in any SQL variant I know of. Either get rid of them or quote the field names in the correct way for your SQL flavor.
Your code likely has an SQL injection vulnerability, unless you left out the code that escapes $token etc
You shouldn't be putting values into the SQL string like that. This isn't the 1990s - we have parametrized queries now.
The mysql_ functions make it a bit difficult to do queries properly. Switch to either mysqli or PDO.

PHP Mysql multiple insert with foreach not working

Here is my code - I'm attempting to attach a bunch of user_id 's to a piece of content.
if (empty($errors)) // If everything's OK.
{
foreach($_POST['userId'] as $row)
{
$query = " ('".$row[learner_id]."', '".$postId."', '".$id."' ),";
}
$query = substr_replace($query,"",-1);
$mysql_return = mysqli_query("INSERT INTO subs (userId, postId, account_id ) VALUES ".$query) or die(mysql_error());
}
Would love any help you could give - it's not working...
And how's it not working? Syntax error? Silently puking? You're not escaping your POST data, so if any of those contain at least one single quote, that'll cause a syntax error right there, plus leaving you wide open for sql injection attacks.
Or maybe a foreign key check is failing... many possibilities, but you haven't given us nearly enough info to tell. What error message(s) are you getting?
Ok, I see several issues:
You are not using parameters or escaping, opening yourself up WIDE to sql injection attacks. See mysqli_real_escape_string.
What are you possibly sending to $_POST['userId'] that would make itself an array?
Unless learner_id is a constant, then this is a syntax error. If it is an array key, put it in quotes.
Where are $postId and $id coming from ?
The first parameter to mysqli_query is the identifier returned by mysqli_connect, whereas you're just giving it the query directly.
It should be like this,
$link = mysqli_connect("host", "user", "pass", "db");
$mysql_return = mysqli_query($link, "INSERT INTO subs (userId, postId, ac...

Categories