mysql - PHP Insert Into not working
Get the solution ↓↓↓This code worked for me before, but now, it's not inserting the data into my DB. When I execute it, it receives a message ($mensaje), then connects with the DB and then tries to insert the data, but it can't do it.
$conn = mysqli_connect('127.0.0.1', 'user', 'pass', 'mydb');
if(mysqli_connect_errno($conn))
{
echo "<script>alert('Error en la conexiГіn');</script>";
}
else
{
echo "<script>alert('Conectado a la base de datos');</script>";
$sql = "INSERT INTO conversacion (mensaje, idUsuario, leido) VALUES ('$mensaje', NULL, FALSE)";
if(mysqli_query($conn, $sql))
{
echo "<script>alert('Datos introducidos correctamente');</script>";
}
else
{
echo "<script>alert('Error en la introduccion de datos');</script>";
}
mysqli_close($conn);
}
Answer
Solution:
since you have made entire sql in string you need to use like this:
$sql = "INSERT INTO conversacion (mensaje, idUsuario, leido) VALUES ('$mensaje', 'NULL', 'FALSE')";
if you will try to make it something like this:
$sql = "INSERT INTO play (id, type, periodId) VALUES ('$mensaje',".NULL.",". FALSE.")";
then it will end up this:
INSERT INTO play (id, type, periodId) VALUES ('10',,) // here $mensaje=10 an example a **wrong sql**
so better try like this:
$mensaje=10;$n=NULL;$flag=true;// here $flag=false will give '' in the sql.
$sql = "INSERT INTO play (id, type, periodId) VALUES ('$mensaje','$n','$flag')";
this will produce something like this:
INSERT INTO play (id, type, periodId) VALUES ('10','','1')
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: constant expression contains invalid operations
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.