Using the " ' " mark as part of the data - sql

I am trying to create an insert statements that will allow the " ' " mark to be used as data, and having problems finding a reference to it. My current statement:
$sql = "INSERT INTO turnover(tail, discription, date) values ('$tail', '$discription', '$date')";
How ever when i put though this sample data i get:
INSERT INTO turnover(tail, discription, date) values ('173AB', 'No Dying MEL's tonight.', '05-14-2018')
If i remove the ' then it works fine. It seems i saw something a long time ago on it, but cannot find it.
Thanks in advance for any information that anyone can offer.

Best practice: Use prepared statements. Asuming you are using PHP: http://php.net/manual/en/pdo.prepared-statements.php
Alternatively you would apply some sort of escaping, like mysqli_real_escape_string().
Take care not to mix PDO and MySQLi functions, and do not in any case use mysql_*() functions.

INSERT INTO turnover(tail, discription, date) values ('173AB', 'No Dying MEL''s tonight.', '05-14-2018')

Related

inserting variables into MySQL

I am trying to insert 2 scores into Mysql for two photos for a particular user that already exists in the database. The scores and the photos are both POST variables from a form. I am having great difficulty with the syntax - I am fairly certain the error is related to the position of quotes but despite searching here and finding similar questions I can't seem to get it working. Loathed to bother people with this but need some executive assistance.
$imageT=$_POST[randomimage]."T" ;
$imageH=$_POST[randomimage]."H" ;
$observerid=$_POST[scoreid];
$traction=$_POST[gradeT];
$honeycomb=$_POST[gradeH];
$sql="INSERT INTO scorers ('$imageT', '$imageH')
VALUES ('$imageT', '$imageH') WHERE id=$observerid ";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
header("Location: testform.php");
} '
$imageT and $imageH are both integers with either T or H appended to them, for example 12T or 14H therefore I assumed they would be treated as strings and I put quotes around them. $traction, $honeycomb and $observerid are all integers. When I echo $imageT, $imageH, $traction, $honeycomb and $observerid the correct values are shown so I am assuming that there is no error in the these, just they way I am placing them within SQL code.
Very much appreciate any help (been learning PHP and My SQL for only 4 weeks so apologies).
At least three main problems at glance
You aren't using prepared statements
You are using WHERE clause in INSERT statement which is useless and erroneous. Either remove WHERE part or change your query to UPDATE.
You didn't post the error with your question. Which you always have to. Error messages is a cornerstone of troubleshooting.

web.py db.insert() doesn't work

I use db.insert() to insert data to database, the code is something like this,
db.insert('categories', name=cate_name, description=desc, _test=True)
but it doesn't work, the data can't not be found in table 'categories' after the code is execute, and no exceptions by the way.
Anybody know why this happened?
_Test variable stands for debug purposes.
It lets you get SQL statement instead of executing one.
It means that your command
result = db.insert('categories', name=cate_name, description=desc, _test=True)
will not execute anything on your DB. It will only return a string:
"INSERT INTO categories (name, description) VALUES ('cate_name value', 'desc value')"
If you want to make a real query, you need to remove it:
db.insert('categories', name=cate_name, description=desc)
It should work.
remove _test=True or set _test=False

Php mysql statement with set and select

I have a weird problem, when i use the query on phpmyadmin, it works. but when i use using a php script it returns an error.
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I tried to troubleshoot and discovered that the problem lies with the set statement.
this is my example code.
$sql = 'set #rank=0; select * from user;';
Please help somebody.
First Run
$sql = set #rank=0;
it will store value of rank
then run:
select * from user;
In sort you need to run both queries separately .
set statement stores values. that can be used by next executing query,
like code below :
$sql ="SET #id:=0";
$Executives=$DB->exec($sql);
$sql = "SELECT #id:=#id+1 as id,pes.* FROM profile_executive_summary as pes where profile_id=".$pid;
$Executives=$DB->fetchAssoc($sql);
See what mysql_error returns after you run mysql_query('...'). That might help. In general, mysql_query only permits one query. You can't separate them by newlines or semicolons. mysqli will do it for you though.

problem with sql query, variable value not inserting itself

the old query works, the new on doesnt. the android logcat gives me error as:
Failure 1: no such column abcname. abcname is the value of a editview that im trying to get from a popup in android.
i know that the first query will insert those values in the fields, as they are given in single inverted commas. the same query, i typed in the adb shell, works. so i copied the query, and just removed the data corresponding to the field names, and inserted the variable names. on trying to run, i get the above said error.
OLD QUERY:
MapsActivity.myDB.execSQL("INSERT INTO "
+MapsActivity.TableName
+ " (name, user_comment, latitude, longitude) "
+ " VALUES ('tagName','tagComment','tagLatitude','tagLongitude');");
NEW QUERY:
MapsActivity.myDB.execSQL("INSERT INTO "
+MapsActivity.TableName
+ " (name, user_comment, latitude, longitude) "
+ " VALUES ("+tagName +",'tagComment','tagLatitude','tagLongitude');");
what is the problem?
If tagName has, e.g., the value "abc", your query will expand to ... VALUE (abc,'tagComment',.... It's missing the single quotes.
Building SQL like this give bad karma. Use SQLite's parameter-binding mechanism instead.
I recommend creating a simple active record db implementation. here is a great tutorial for a simple sqlite active record for android. This adds some extra time up front but saves you time while you develop.
wrap your double quotes with single quotes?
...('"+tagName +"',....

SQL Error when using apostrophes

I'm getting the following error whenever I try to post something with an apostrophe in it:
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...
For example when I'm trying to post/using INSERT something like "I'm working hard".It's getting me an error. If I write "I am working hard" everything is fiine.
The code is:
$sql="INSERT INTO tb_table (`postcontent`, `userid`, `posttime`) VALUES ('".$_POST[content]."', '".$user_id."', '".time()."')";
Any ideas how to fix it?
That's because you are using apostrophes to show MySQL where each value for the field starts and ends. If you put an apostrophe in the middle of the string, suddenly the database thinks that you're trying to put in four values in three table fields, or some such thing.
It looks like you're using PHP to insert data in the database so I'll give you a couple of examples of dealing with this with the means that PHP provides.
A quick way to fix it to use mysql_real_escape_string():
$sql="INSERT INTO tb_table (`postcontent`, `userid`, `posttime`)
VALUES ('" . mysql_real_escape_string($_POST['content']) . "',
'" . mysql_real_escape_string($user_id) . "',
".time().")";
A better approach would be to use prepared statements:
$db = // your mysqli() connection
$sql="INSERT INTO tb_table (`postcontent`, `userid`, `posttime`)
VALUES (?, ?, ?)";
if ($stmt = $db->prepare($sql))
{
$stmt->bind_param("ssi", $_POST['content'], $user_id, time());
$stmt->execute();
$stmt->close();
}
P.S. You don't need single quotes around time() - this is a number, it's safe to insert as is.
The quotes in the value being inserted are closing the quotes that surround the value in the INSERT statement because you're using dynamically generated SQL.
Best solution is to use parameterised SQL which will prevent this problem and be safer (guard against SQL injection). Otherwise, you need to parse/make safe the supplied values - e.g. escape all single quotes so they don't break the statement.
If this is in any way accessible to the public, take it down NOW, then go and read up on SQL injection attacks. The best fix is to use parameterised queries, but you must use some kind of escaping mechanism, because the quotes in your text are being interpreted as part of the SQL command, not as part of the text.
Consider what would happen if you submitted the comment:
', 'No-one', time()); DROP TABLE tb_table; //
Your SQL:
$sql="INSERT INTO tb_table (`postcontent`, `userid`, `posttime`) VALUES ('".$_POST[content]."', '".$user_id."', '".time()."')"
Then expands to the string:
INSERT INTO tb_table (`postcontent`, `userid`, `posttime`) VALUES ('', 'No-one', now()); DROP TABLE tb_table; //', 'user', 'time')"