尝试使用我的localhost上的代码修复SQL注入,无法使其工作。 (PHP)

Iam very new to PHP and I have been told that my previous code can be SQL injected so I am trying to solve it now. This is what I have come up with so far. When I submit into my form with this code below I get this error:

Notice: Undefined variable: mysqli in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 49

Fatal error: Call to a member function prepare() on null in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 49".

I have commented on line 49.

<?php 

$mysql_pekare= new mysqli ("localhost", "username","pass", "database");

if(!empty($_GET['namn'])) {
$unsafe_variable = "Welcome ". $_GET["namn"]. ". You are ".$_GET["age"]. " years old." ; 

$stmt = $mysqli->prepare("INSERT INTO Personinfo(`Personname`, `Personage`) VALUES('$_GET[namn]', '$_GET[age]')");` //this is line 49

$stmt->bind_param("s", $unsafe_variable);

$stmt->execute();

$stmt->close();

$mysqli->close();
}
?>

My form looks like this:

<form id="Personinfo" action="index.php" > 
<input type="text" id="namn" name="namn" placeholder="namn"/>
<input type="text" id="age" name="age" placeholder="age"/> 
<input type="submit"/>
</form>

You have to use the connection as you have named it:

$mysql_pekare= new mysqli ("localhost", "username","pass", "database");

if(!empty($_GET['namn'])) {
    $unsafe_variable = "Welcome ". $_GET["namn"]. " You are ".$_GET["age"]. " years old." ; 

    $stmt = $mysql_pekare->prepare("INSERT INTO Personinfo(`Personname`, `Personage`) VALUES(?,?))";
    $stmt->bind_param("ss", $_GET['namn'], $_GET['age']);
    $stmt->execute();
    $mysql_pekare->close();
}

Once you do that you have to use placeholders (?) for each unsafe variable and then bind to those variables.

You first create $mysql_pekare and then try to use $msqli. That's your issue.

Change your variables to match, and you should be good.

$mysql_pekare = new mysqli(...);

$mysql_pekare->prepare(...);