good morning, I have a question that is blowing my mind, I am making a web page that shows a dynamic image slider, the user can modify, delete or add images, I use: PHP, MySQL and javascript. I have a code where I do the consultation of the images
<?php
$a = 0;
include("conexion.php");
$query = "SELECT * FROM tabla_imagen";
$resultado = $conexion->query($query);
while($row = $resultado ->fetch_assoc()){
$pic [$a]=($row['Imagen']);
++$a;
}
?>
The array is being saved in $pic, my javascript code is:
<script type="text/javascript">
window.addEventListener('load', function () {
var imagenes = [];
var flag=0;
var tiempo = 5000;
for (flag = 0; flag < <?php echo count($pic)?>; flag++) {
imagenes[flag] = 'data:image/jpg;base64, <?php echo base64_encode($pic[flag]); ?>';
}
var indiceImagenes = 0;
function cambiarImagenes(){
document.slider.src = imagenes[indiceImagenes];
if (indiceImagenes < <?php echo count($pic)-1;?>) {
indiceImagenes++;
}else{
indiceImagenes = 0;
}
}
setInterval(cambiarImagenes, tiempo)
});
</script>
where specifically the code:
for (flag = 0; flag < <?php echo count($pic)?>; flag++) {
imagenes[flag] = 'data:image/jpg;base64, <?php echo base64_encode($pic[flag]); ?>';
}
It throws me an error in the "flag" variable, I am aware that javascript cannot be combined with php in that way, but does anyone have any idea how it can be done? Thanks in advance
PHP does not run in the browser, PHP creates the page or formats the page on the server and sends it to the browser where JavaScript takes care of it. In another word for PHP JavaScript is just another HTML tag and it doesn't execute it so the variable
Flag
for PHP doesn't exist and that's why it sends you that error. I advise you not to mix PHP with JavaScript.Here is the equivalent of what you are trying to do:
Note: The last element is
undefined
So I advise you to remove it or ignore it.I recommend that you use AJAX with JQuery (The page is in English, but it is interesting to read it):
get_image.php
javascript