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\ ")";

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3dc9c-2c3b5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3dc9c-2c3b5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?