How do I use variables within this PHP + Mysqli code?

Asked

Viewed 80 times

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();
}

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 is worth saying that the data needs to be sanitized before insertion:

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

And by inserting something like:

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

This prevents corruption of query values with quotes and special characters, and minimizes the chance of SQL injection

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."')";

points serve to join their variables with the strings

  • 2

    Thanks for the help @Italo Rodrigo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.