How do I use variables within this PHP + MySQLi code? [closed]

0

My code returns the following error:

  

Parse error: syntax error, unexpected T_VARIABLE in /home/a2015539/public_html/envio.php on line 28

The code is this:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('"$nome"','"$sexo"','"$dia"','"$mes"','"$ano"')";

if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}

$conn->close();
}
    
asked by anonymous 19.12.2016 / 23:34

2 answers

3

Typing error. You did not concatenate the values.

Solution:

$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('".$nome."','".$sexo."','".$dia."','".$mes."','".$ano."')";

It goes without saying that the data needs to be sanitized before insertion:

$nome_sanitizado = $conn->real_escape_string( $nome );

And when entering something like:

"..... VALUES ('".$nome_sanitizado."',

This avoids query corruption in values with quotation marks and special characters, and minimizes the chance of SQL Injection

    
19.12.2016 / 23:38
2

change this line

$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('"$nome"','"$sexo"','"$dia"','"$mes"','"$ano"')";

for

$sql = "INSERT INTO cadastro (nome, sexo, dia, mes, ano)
VALUES ('".$nome."','".$sexo."','".$dia."','".$mes."','".$ano."')";

the points serve to join their variables with the strings

    
19.12.2016 / 23:38