B
B
Bohdan Kucheruk2022-03-28 18:47:09
MySQL
Bohdan Kucheruk, 2022-03-28 18:47:09

When you try to write an apostrophe in SQL, it gives an error? How to fix it?

I understand that this is happening at this moment:

$mysqli->query("INSERT INTO table
     (data)
    VALUES
    ('$data')
    ");


How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2022-03-28
@TerritoryOfPeace

It is necessary to learn PHP not according to the manuals written by noobs under Tsar Pea, but according to normal textbooks.
Or at least the normal answers on the toaster.
https://qna.habr.com/q/918033#answer_1847841
There should not be any $data in the request. Any variables must be sent to the database separately
. To do this, you need to
Replace all variables in the request with special markers, which are called placeholders or parameters, but in fact - just question marks.
Prepare the query for execution using the prepare () function. This function accepts a query string and returns an instance of the special class stmt, with which all further manipulations are performed
Bind variables to the query.
Execute the previously prepared query with execute()
In mysqli it would be like this

$sql = "INSERT INTO `events` (`title`, `discription`, `date`, `img`) VALUES (?,?,?,?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("sssss", $title, $discription, $date, $path);
$stmt->execute();

bind_param() takes as parameters all the variables that should be included in the request, in the same order as the placeholders in the request. But in addition, the types for all variables must first be specified in this function, as a string, where the type of the variable is denoted by a single letter. That is, there should be exactly as many letters in this line as there will be variables further. Luckily, you don't have to worry too much about types and specify the type "s" for all variables.
And then there will never be any request errors. Not to mention injections.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question