-2

I'm having some trouble where I'm pulling values from both a session and a form - for a ticketing system - and when someone uses an apostrophe, it breaks the code.

See below where I receive the data:

$name = $_POST["name"];
$topic = $_POST["topic"];
$urgency = $_POST["urgency"];
$subject = $_POST["subject"];
$details = $_POST["details"];
$username = $_SESSION["username"];
$imgloc = $_SESSION["imgloc"];
$isit = $_SESSION["isit"];

I later insert it into my MSQL database here:

$sql = "INSERT INTO tickets (id, ticketname, urgency, topic, submitted, subject, details, isticketimage, imgloc) VALUES ('', '$name', '$urgency', '$topic', '$userno', '$subject', '$details', '$isit', '$imgloc')";

How would I amend this code to avoid apostrophe's breaking my mysql command?

ysth
  • 96,171
  • 6
  • 121
  • 214
  • You should use Prepared Statements, that will sort it, and other issues. – droopsnoot May 07 '21 at 07:53
  • Also, if your `id` column has a default, there's no need to include it in the query with a blank value, just omit it and it will use the default. – droopsnoot May 07 '21 at 07:54
  • 1
    Does this answer your question? [How to include a PHP variable inside a MySQL statement](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) – El_Vanja May 07 '21 at 07:56

2 Answers2

1

You can use PDO from php, it will avoid sql injections.

You can do something like this

$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$sql = "INSERT INTO tickets (ticketname, urgency, topic, submitted, subject, details, isticketimage, imgloc) VALUES (?,?,?,?,?,?,?,?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $urgency, $topic, $userno, $subject, $details, $isit, $imgloc]);

More info : https://www.php.net/manual/en/pdo.prepared-statements.php

Thomas
  • 410
  • 9
  • 14
  • Welcome to Stack Overflow. It's good to see you wanting to contribute, but questions like these are asked on a daily basis and already have plenty of answers on the site, such as [this](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and [this](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Please do a search of the site before answering to avoid creating duplicate content and flag the question as duplicate instead. – El_Vanja May 07 '21 at 08:00
-2
mysqli_real_escape_string($dbConnection, $variable)

should do the trick.

ProtoN
  • 135
  • 1
  • 7
  • `mysqli_real_escape_string` should be avoided because [it's not safe enough](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string). Prepared statements are the way to go. – El_Vanja May 07 '21 at 07:57