Here's how my insert code looks:
$values .= ($ta->account_toll_free_number != '') ? ",('" . $post_id . "', 'toll_free_number','" . $ta->account_toll_free_number . "')" : NULL;
Which gives me:
(111, 'toll_free_number', '888-123-1234')
Which works great until there is a single quote mark in the variable. Then it breaks. Is there someway I can clean/escape it before this? Do I just need to swap my single quotes to double quotes?
I did it this way.
I just started with your output and added a single quote for last part.
$values = mysql_real_escape_string("(111, 'toll_free_number', '888-'123-1234')");
$query = "INSERT INTO yourtable (fieldname) values ('".$values."')";
mysql_query($query) or die(mysql_error());
see more from manual http://php.net/manual/en/function.mysql-real-escape-string.php
As the commenter pointed out, I would recommend you use PDO as this is an escaping issue and opens you up to SQL injection vulnerabilities. On the change that you are using mysql_* instead, try escaping the variable with mysql_real_escape_string() first.
Related
$sql="INSERT INTO prescription
(username,phone,procedure,address,emailid,reviews,followups,nextappointment)
VALUES
("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")";
I think your problem is in the quotes, you have double quotes inside double quotes, you should escape the quotes or use single quotes.
The easy and simple thing is to use prepared statements.
I'm not sure which API you using PDO/MSQLI
if you in PDO :
<?php
$sql =$databaseConnectionVar->prepare("INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES(?,?,?,?,?,?,?,?)")
->execute(array($username,$phone,$procedure,$address,$emailid,$reviews,$followups,$nextappointment));
if(!$sql){
print_r($databaseConnectionVar->errorInfo());
}else{
echo "data inserted";
}
?>
if you are on mysqli then :
<?php
$sql =$databaseConnectionVar->prepare("INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES(?,?,?,?,?,?,?,?)");
$sql->bind_Param("ssssssss",$username,$phone,$procedure,$address,$emailid,$reviews,$followups,$nextappointment);
if($sql->execute()){
echo "data inserted";
}else{
echo "Error : ". $databaseConnectionVar->error;
}
?>
Then important links you need to look at :
How to get mysqli error in different environments?
When to use single quotes, double quotes, and backticks in MySQL
When should I use prepared statements?
Prepared Statements
Hope this will point you to the right path.
You should change "" is there know that one should change single quote ''.
for example below:
$sql = 'INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)
VALUES("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")';
Hope it will helps you
your inverted commas are wrong,
use single quote ('') in values,
you get error on your IDE. or if you just copy and run on DB.
$sql = "INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)VALUES('$usernam','$phone','$procedure','$address','$emailid','$reviews','$followups','$nextappointment')";
Check Your Insert Into Query:
$sql = "INSERT INTO prescription (username,phone,procedure,address,emailid,reviews,followups,nextappointment)
VALUES('$username','$phone','$procedure','$address','$emailid','$reviews',$followups,'$nextappointment')";
NOTE: Check THis : https://www.w3schools.com/sql/sql_insert.asp
I've tried everything, and I still can't figure it out. addslahes(), str_replace(), htmlentities(), I just can't understand why double quotes are not displaying on my website.
$sql = $con->prepare("SELECT * FROM `user_settings` WHERE `user_session` = '$user_session'");
$sql -> execute();
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$advertising_1 = $row['advertising_1'];
$advertising_2 = $row['advertising_2'];
$website_name = $row['website_name'];
$website_url = $row['website_url'];
$statistics = $row['statistics'];
}
echo '<input type="text" name="website_name" placeholder="Your Website URL" value="'. $website_name. '" />' ?>
Can someone please explain where I'm going wrong here? Problem arises with Double quotes in my string. Single quotes was fixed with mysql_escape but it appears to be deprecated.
You need to escape the data you are outputting to the browser use htmlspecialchars and use the quotes constant (ENT_QUOTES) so all quotes are converted to entities. Note this also is how XSS injections are prevented/performed. Elements/attributes are closed when they aren't suppose to be and then malicious code is written.
echo htmlspecialchars('Encode all of these "test" test \'test \'', ENT_QUOTES);
Output:
Encode all of these "test" test 'test '
and in a browser:
Encode all of these "test" test 'test '
Also from the code you displayed you are misusing prepared statements. Values need to be bound, not concatenated to your query. This way the PDO driver will handle the quoting/escaping. This could result in similar issues for you in the future, if you continue to use it as you have it. Also opens you to SQL injections.
For more information on prepared statements see: http://php.net/manual/en/pdo.prepared-statements.php
You need to use the prepare without variables on the statement and later you add them on the execute() as an array, like this:
$sql ="SELECT * FROM `user_settings` WHERE `user_session` = ?";
$stmt = $con->prepare($sql);
$stmt->execute([$user_session]);
Given this SQL
UPDATE `mytable`
SET `mycolumn`='karla bailey-pearapppppppp\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
WHERE `id`=5619
Why will mysqli_real_escape_string() not escape this string properly?
Trying to use this SQL query after escaping the column's value produces this mysqli 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 ''karla bailey-pearapppppppp\\\\\\\\\\\\\\\\\\\\\\\\\\\' at line 3"
Is there a limit to the number of backslashes that can be escaped?
Are you escaping the ENTIRE string? e.g.
$sql = "UPDATE .... \\\\\\\'";
$escaped = mysqli_real_escape_string($link, $sql);
If so, that's incorrect. You are trashing the string by doing that. You'll also be escaping the ' that delimit your where clause value. Escaping should be performed only VALUES that you're inserting into the string. e.g.
$name = "Miles O'Brien"; // ' in name would cause syntax error
$bad_sql = "SELECT '$name'";
$broken_sql = mysqli_real_escape_string($link, $bad_sql);
// produces: SELECT \'Miles O\'Brien\'
$ok_sql = "SELECT '" . mysqli_real_escape_string($link, $name) . "'";
// produces: SELECT 'Miles O\'Brien';
Ok, so I found the problem. The application checks for the value length > column maximum, and if the value is too great, truncates the value AFTER the escape is done - thereby breaking the escaped value (very isolated case where this would occur, this code has been in place for years).
Ergo, can't truncate a value that ends in backslashes after the value is already escaped.
I insert a text variable in a mySQL table. Everything works fine except in the text is a quotation mark. I thought that I can prevent an error by using "mysql_real_escape_string". But there is an error anyway.
My insert statement:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_real_escape_string($insertimage);
The error message:
MySQL 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 '1413885955514','10')' at line 1
You need to escape data that you are putting into the SQL so that any special characters in it don't break the SQL.
You are escaping all the special characters in the final string of SQL; even those that you want to have special meaning.
If you want to use your current approach, you would do something like this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
… but the PHP mysql_ extension is obsolete and you shouldn't use it.
Modern APIs, such as mysqli_ and PDO support prepared statements, which are a better way to handle user input. This answer covers that in more detail.
The problem with your current code is that you have not correctly escaped the values you're trying to enter into the table.
Better still is to avoid the mysql_* function family entirely. Those functions are now deprecated and bring security risks to the table (along with other concerns).
You'd be better to use PDO and Prepared Statements, for example:
$db = new PDO('param1', 'param2', 'param3');
$sql = $db->prepare( 'INSERT INTO `image` (`filename`, `text`, `timestamp`, `countdown`)
VALUES (:filename, :text, :timestamp, :countdown)' );
$sql->execute( array(':filename' => $filename,
':text' => $text,
':timestamp' => $timestamp,
':countdown' => $countdown )
);
mysql_real_escape_string($insertimage);
You will have to use this function to each variables before writing the query.
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
Try this ,
$insertimage = sprintf("INSERT INTO image(filename,text,timestamp,countdown) VALUES ('%s','%s','%s','%s')", mysql_real_escape_string($filename), mysql_real_escape_string($text), $timestamp, $countdown);
Why, because your inputs vars must be escaped before using them in sql
then execute your sql.
Escaping the entire query is not useful. In fact, right now, you are causing syntax errors by doing so.
You should be escaping the individual variables that you inject into it.
Try this:
$filename = mysql_real_escape_string($filename);
$text = mysql_real_escape_string($text);
$timestamp = mysql_real_escape_string($timestamp);
$countdown = mysql_real_escape_string($countdown);
$insertimage = "INSERT INTO image(filename,text,timestamp,countdown) VALUES ('$filename','$text','$timestamp','$countdown')";
mysql_query($insertimage);
Concat the php variables like this:
$insertimage= "INSERT INTO image(filename,text,timestamp,countdown) VALUES (" . $filenamec . "," . $text . ", " . $timestamp . ", " . $countdown . ")";
with the respective single quotes in those that are text fields i.e: "... '" . $text . "' ..."
I think i'm doing something wrong here, I'm very new to PHP and only using it to interface my database with my client software through a WWW call, I have a Insert script, which works, but as for my Update script im stumped... here are the queries I tried:
the newest one:
$query = "UPDATE accounts SET moonscore= ' " . $moonscore . " ', sunscore = ' " . $sunscore . " ' WHERE name = ' " . $name . "';";
and I also tried, which I figured was wrong after awhile.
$query = "UPDATE accounts SET moonscore = $moonscore, sunscore = $sunscore WHERE name =$name;
Would really appreciate the help from all you PHP gurus.
try,
$query = "UPDATE accounts
SET moonscore = '$moonscore',
sunscore = '$sunscore'
WHERE name ='$name'";
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
you should use single quotes around the variables ,try this
$query = "UPDATE accounts SET moonscore = '$moonscore' , sunscore = '$sunscore' WHERE name ='$name';
tips: try to use PDO or MYSQLI instead of mysql
Your query is open for SQL Injections. I've added a simple function that always served me well.
function inject($value)
{
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not integer
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
$query = "UPDATE accounts SET moonscore = ".inject($moonscore).", sunscore = ".inject($sunscore)." WHERE name =".inject($name);
Take a look at prepared statements to avoid having to think about protecting your queries against injection with some fancy functions. http://php.net/manual/en/pdo.prepared-statements.php
Here's a video that might give you more insight as a beginner: http://www.youtube.com/watch?v=_bw54BqS2UE