PHP - Con valor de BD mostrar una imagen diferente

 
Vista:
sin imagen de perfil
Val: 22
Ha aumentado su posición en 2 puestos en PHP (en relación al último mes)
Gráfica de PHP

Con valor de BD mostrar una imagen diferente

Publicado por Garikoitz (13 intervenciones) el 01/05/2018 10:21:34
Hola, ante todo muchas gracias a todo el mundo que me quiera ayudar.

Vereis, no soy programador ni he estudiado nada relacionado, tan sólo intento aprender por mi mismo. Con el método de investigar mucho prueba y error y como no con la ayuda de los foros.

Quisiera mostrar una imagen dependiendo del valor guardado en una base de datos, esto lo he conseguido.

1
<td><?php echo '<img src="img/' . $mostrar['estado'] . '.png" /><br />'; ?></td>

Ahora ya por dar un paso mas, quisiera utilizar en vez de imagenes botones de bootstrap. De la siguiente forma:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<td><td>
    <?php
    $estados = 'estado';
 
    if ($estados = "Pendiente")
 
    {
 
    ?>
 
    <button type="button" class="btn btn-danger">Pendiente</button>
 
    <?php
 
    } elseif ($estados = "Validado")
 
    {
 
    ?>
 
    <button type="button" class="btn btn-warning">Validado</button>
 
    <?php
 
    } else
 
    {
 
    ?>
 
    <button type="button" class="btn btn-success">Tramitado</button>
 
    <?php
 
    }
 
    ?>
</td>

Pero no consigo que funcione correctamente. Me muestra el boton de Pendiente, pero el resto aunque en la BD tenga otros valores (Tramitado, Validado) no se muestran.


Este es el codigo completo de mostrar-2.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
 
//Conectamos con el Servidor con los datos guardados en config.php
$connection = mysqli_connect('localhost', 'root', '');
if (!$connection){
    die("Fallo la conexion con la base de datos" . mysqli_error($connection));
}
 
 
 
// Conecta con la Base de Datos 
 
$select_db = mysqli_select_db($connection, 'albaranes');
if (!$select_db){
    die("Database seleccionada ha fallado" . mysqli_error($connection));
}
 
 ?>
 
 
<!DOCTYPE html>
<html>
<head>
	<title>Pedidos Realizados</title>
 
	<!--  Carga de Librerias  -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    	<script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
	<!-- Fin de Carga de Librerias-->
 
</head>
<body>
 
<br>
 
<div class="container">
	<div class="table-responsive table-hover">
	<table class="table" >
		<thead>
			<th>Nº Pedido</th>
			<th>Fecha Solicitud</th>
			<th>Estado del Pedido</th>
		</thead>
 
		<?php
		$sql="SELECT * from solicitud_material";
		$result=mysqli_query($connection,$sql);
		$estados = 'estado';
		while($mostrar=mysqli_fetch_array($result)){
		?>
 
		<tr>
			<td><a href="popup.php?id=<?php echo $mostrar['id'] ?>" onclick="window.open(this.href,this.target,'width=1000,height=650,top=200,left=200,toolbar=no,location=no,status=no,resizable=yes,menubar=no');return false;"><?php echo $mostrar['id'] ?></a></td>
			<td><?php echo date("d-m-Y  H:i", strtotime($mostrar['fecha_solicitud'])) ?></td>
			<!-- <td><?php echo $mostrar['fecha_solicitud'] ?></td> -->
 
			<!-- <td><?php // echo '<img src="img/' . $mostrar['estado'] . '.png" /><br />'; ?></td> -->
 
			<td>
				<?php
				$estados = 'estado';
 
				if ($estados = "Pendiente")
 
				{
 
				?>
 
    			<button type="button" class="btn btn-danger">Pendiente</button>
 
				<?php
 
				} elseif ($estados = "Validado")
 
				{
 
				?>
 
    			<button type="button" class="btn btn-warning">Validado</button>
 
				<?php
 
				} else
 
				{
 
				?>
 
    			<button type="button" class="btn btn-success">Tramitado</button>
 
				<?php
 
				}
 
				?>
			</td>
 
 
		</tr>
	<?php
	}
	?>
	</table>
	</div>
</div>
 
	<!--  Carga de Librerias  -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
	<!-- Fin de Carga de Librerias-->
 
</body>
</html>

Esta es la base de datos, por si alguno quiere hacer pruebas o aprender como yo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1:3306
-- Tiempo de generación: 01-05-2018 a las 08:08:58
-- Versión del servidor: 5.7.19
-- Versión de PHP: 7.0.23
 
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
 
 
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
 
--
-- Base de datos: `albaranes`
--
 
-- --------------------------------------------------------
 
--
-- Estructura de tabla para la tabla `solicitud_material`
--
 
DROP TABLE IF EXISTS `solicitud_material`;
CREATE TABLE IF NOT EXISTS `solicitud_material` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fecha_solicitud` datetime DEFAULT NULL,
  `cc_solicitante` varchar(70) DEFAULT NULL,
  `turno` varchar(50) DEFAULT NULL,
  `linea` varchar(350) DEFAULT NULL,
  `punto_entrega` varchar(100) DEFAULT NULL,
  `matricula` varchar(100) DEFAULT NULL,
  `denominacion` varchar(200) DEFAULT NULL,
  `referencia` varchar(100) DEFAULT NULL,
  `cantidad` varchar(50) DEFAULT NULL,
  `material_entregado` varchar(50) DEFAULT NULL,
  `estado` varchar(50) DEFAULT NULL,
  `fecha_tramitado` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
 
--
-- Volcado de datos para la tabla `solicitud_material`
--
 
INSERT INTO `solicitud_material` (`id`, `fecha_solicitud`, `cc_solicitante`, `turno`, `linea`, `punto_entrega`, `matricula`, `denominacion`, `referencia`, `cantidad`, `material_entregado`, `estado`, `fecha_tramitado`) VALUES
(1, '2018-04-19 00:00:00', '1131', 'T1', 'L141', '16 Planta Alta', '63213', 'Portacapsulas', '108401', '1', NULL, 'Pendiente', NULL),
(2, '2018-04-13 00:00:00', '1131', 'T1', 'L141', '16 Planta Alta', '63213', 'Portacapsulas', '108401', '1', NULL, 'Pendiente', NULL),
(3, '2018-04-13 00:00:00', '1131', 'T1', 'L141', '16 Planta Alta', '63213', 'Portacapsulas', '108401', '1', NULL, 'Pendiente', NULL),
(4, '2018-04-05 00:00:00', '1152', 'T2', 'L150', '15 Planta Baja', '52415', 'Capsula', '105426', '2', NULL, 'Pendiente', NULL),
(5, '2018-04-29 00:00:00', '1523', 'T3', '1524', '15 Planta baja', '56896', 'racor', '125478', '5', NULL, 'Pendiente', NULL),
(6, '2018-04-30 19:08:38', '1212', 'T1', '152', 'Planta Media', '65896', 'Manguera', '4568989', '5', NULL, 'Validado', NULL),
(7, '2018-04-30 19:10:39', '585', 'T1', '157', 'Planta Media', '65896', 'Manguera Corta', '45689', '4', NULL, 'Pendiente', NULL),
(8, '2018-05-01 05:28:05', '5555', 'T1', '65656', 'Planta baja Media', '5656565', 'Cable 2 m acodado', '452365', '2', NULL, 'Pendiente', NULL),
(9, '2018-05-01 05:28:05', '5555', 'T1', '65656', 'Planta baja Media', '5656565', 'Sarten', '565656', '5', NULL, 'Tramitado', NULL),
(10, '2018-05-01 06:57:16', '585585', 'T1', '65656', 'Planta estado', '56896', 'Estado racores', '56568', '3', NULL, 'Pendiente', NULL),
(11, '2018-05-01 06:57:16', '585585', 'T1', '65656', 'Planta estado', '56896', 'Estado racores', '56568', '5', NULL, 'Pendiente', NULL);
COMMIT;
 
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Alejandro
Val: 1.634
Plata
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Con valor de BD mostrar una imagen diferente

Publicado por Alejandro (839 intervenciones) el 02/05/2018 16:49:28
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Leete algo sobre operadores

= Es operador de asignación
1
if ($estados = "Pendiente")
Si (a $estados se le puede asignar "Pendiente" ){... poreso siemre entra al bloque verdadero.

== Es un operador binario (porque compara "dos" valores)
1
if ($estados == "Pendiente")
Si ($estados es igual a "Pendiente"){...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 22
Ha aumentado su posición en 2 puestos en PHP (en relación al último mes)
Gráfica de PHP

Con valor de BD mostrar una imagen diferente

Publicado por Garikoitz (13 intervenciones) el 05/05/2018 17:19:51
Finalmente lo he solucionado de esta forma usando los botones de Bootstrap como imagen.

1
2
3
4
5
6
7
8
9
10
11
switch ($estado)
{
    case "Pendiente":
        $clase="btn btn-danger";
        break;
    case "Validado":
        $clase="btn btn-warning";
        break;
    case "Tramitado":
        $clase="btn btn-success";
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar