Rosamunda Rosamunda - 5 months ago 12
MySQL Question

Why this query in a php script isn't working when the query itself does work?

I'm trying to upload a file using a PHP form.

The file gets uploaded correctly, but what I cannot do for some reason is to save the file's name into the database.

This is what I'm doing:

if (move_uploaded_file($tmp_name, "$root/docsCursos/$archivoFinal")) {
$conectar = new PDO('mysql:host='.HOST.'; dbname='.DATABASE.'; charset=utf8', USER, PASS);
$guardarArchivo = $conectar->prepare('UPDATE contenidos
SET archivoContenido="$archivoFinal"
WHERE contenidoID=$contenidoID
echo 'Se cargo el archivo '.$archivoFinal.'<br>';

What I've checked:

The echo line "Se cargo el archivo ..." gets printed out.

The file is saved to the folder.

The names of the table and column are correct.

When I try to manually type the query into phpMyAdmin it works so I guess the query it's ok.

I've tried preparing the statement instead of doing it directly with the variables, but as it didn't worked, I figured that it would be easier to find the error if I try the query directly.

The database connection does work, as it is used in the same file and it's not closed.

I've printed out the query itself on the screen to see if the variables are printed and they are not null, and they do get printed.

The error log don't show me anything.

What I'm missing here?


The problem is you're trying to reference variables inside single quotes, which PHP will just interpret literally.

$guardarArchivo = $conectar->prepare($sql = "UPDATE contenidos
                                    SET archivoContenido='$archivoFinal'
                                    WHERE contenidoID=$contenidoID

When you say the queries worked when you tried them manually, you weren't making this mistake. A good debug tip is to assign your compiled query to a var, like above, then just output that - then you'd have spotted the problem straight away:

echo $sql; //<-- oh-uh, obvious problem