INSERT INTO Does not send the data to the database

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 DB. What is the problem?

    
asked by anonymous 24.03.2014 / 21:50

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 that you 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() o sssss means the argument type, ie five arguments of type string.

s: para 'string'
i: para 'inteiro'
d: para 'double'
b: para 'blob'
    
24.03.2014 / 22:45
1

Use quotes in the insertion variables:

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