Error caused by single quotation marks in sql statement

sql statement

$sql_insert = "insert into tabs(name,singer,address) values ("$name","$singer","$songaddress")";
$res_insert = $conn->query($sql_insert);

question

single quotation marks appear in my $name, $singer, and $songaddress variables, resulting in conflicts between quotation marks. At this time, the statement of sql cannot be executed. How to solve this problem?

May.16,2021

addslashes function to learn about


put the single quotation marks in the strings in your variables $name, $singer, $songaddress

  1. or add an escape character to become \'.
  2. or replace the original one with two single quotes in the variable and become '
  3. or use the addslashes function directly for variables to escape special characters.

In

sql, use two single quotation marks to indicate a single quote that is not a character boundary:

select 'fff''fff' ff

Don't splice SQL. It is easy to cause SQL injection.
use PDO objects to manipulate the database, and use preprocessing statements to process your SQL to prevent SQL injection:

/*  PHP   */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

http://php.net/manual/zh/clas.


use escape characters + double quotes, such as
$sql_insert = "insert into tabs (name,singer,address) values (\" $name\ ",\" $singer\ ",\" $songaddress\ ")";

Menu