INSERT INTO Does not send data to database

Asked

Viewed 160 times

6

I have the following code:

$con=mysqli_connect("localhost","esferinf_fpessoa","*****","esferinf_factura");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql = ($con, "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ('$dia, $cliente',$toalhetes, $higienico, $bidons)");
$result = mysqli_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
    header('Location: index.php');
}
else {
    echo "ERROR";
}

However, the data is not sent to the BD. What’s the matter?

2 answers

6

In your query string, remove the variable $con, changing

$sql = ($con, "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ($dia, $cliente,$toalhetes, $higienico, $bidons)");

for

$sql = "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ($dia, $cliente,$toalhetes, $higienico, $bidons)";

The mysqli_query() in procedural mode asks for two arguments: the connection, and the query string. Your code should look like this:

$result = mysqli_query($con, $sql);

It is recommended to use Prepared statements to avoid sql Injection. Using this, your code should look like this:

$sql = "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES (?, ?, ?, ?, ?)";

$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "sssss", $dia, $cliente, $toalhetes, $higienico, $bidons);
mysqli_stmt_execute($stmt);

in stmt_bind_param() the sssss means the type of the argument, that is, five arguments of the string type.

s: para 'string'
i: para 'inteiro'
d: para 'double'
b: para 'blob'

1

Utilize quotation marks in the insertion variables:

$sql = ($con, "INSERT INTO Entregas (dia, cliente, toalhetes, higienico, bidons)
VALUES ('$dia', '$cliente','$toalhetes', '$higienico', '$bidons')");
$result = mysqli_query($sql);

Browser other questions tagged

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