Mostrar nome do cliente e produto em uma tabela PHP - MySQL

  • Autor Autor Geg1
  • Data de início Data de início
Tradução em andamento: em alguns minutos este tópico estará em português. Por enquanto, o conteúdo está no original em espanhol. Ver original
Geg1

Geg1

Kappa
Verificación en dos pasos activada
Verificado por Binance
Hola a todos! tengo la siguiente tabla:


Inserir CODE, HTML ou PHP:
<table width="712" border="0">
  <?php do { ?>
    <tr>
      <td width="129"><?php echo $row_Pedidos['id_pedido']; ?></td>
      <td width="100"><?php echo $row_Pedidos['fecha']; ?></td>
      <td width="107"><?php echo $row_Pedidos['cliente_id']; ?></td>
      <td width="130"><?php echo $row_Pedidos['producto_id']; ?></td>
      <td width="160" widht="20">
      <td width="60" widht="20">&nbsp;</td>
    </tr>
    <?php } while ($row_Pedidos = mysql_fetch_assoc($Pedidos)); ?>
</table>


La cual muestra todos los pedidos ordenados. Pero yo quiero que el campo "cliente_id" relacionado con la tabla "clientes" muestre el campo "nombre" asociado a este id. lo mismo con el campo "producto_id"

de la siguiente forma lo intente:

Inserir CODE, HTML ou PHP:
<?php


$link = mysqli_connect("localhost", "root", "");

mysqli_select_db($link, "gestorpedidos");

$tildes = $link->query("SET NAMES 'utf8'"); 

$result = mysqli_query($link, "SELECT * FROM clientes");

while ($row_Cliente = mysqli_fetch_array($result)){

$row_Cliente [ $row_Cliente["id_cliente"] ] =$row_Cliente["nombre"]; 
}

mysqli_free_result($result);

mysqli_close($link);

?>

y lo inserte en la tabla asi:

Inserir CODE, HTML ou PHP:
<table width="712" border="0">
  <?php do { ?>
    <tr>
      <td width="129"><?php echo $row_Pedidos['id_pedido']; ?></td>
      <td width="100"><?php echo $row_Pedidos['fecha']; ?></td>
      <td width="107"><?php echo $row_Cliente[$row_Pedidos['cliente_id']]; ?></td>
      <td width="130"><?php echo $row_Pedidos['producto_id']; ?></td>
      <td width="160" widht="20">
      <td width="60" widht="20">&nbsp;</td>
    </tr>
    <?php } while ($row_Pedidos = mysql_fetch_assoc($Pedidos) ); ?>
</table>

Pero no me muestra nada, osea un campo vacio.
Cual puede ser el problema?

Gracias a todos!
 
Foi útil? Participe da conversa

Com sua conta grátis você pode responder, mandar mensagem privada ao autor e comprar com Saldo retido: o pagamento é liberado quando você recebe o combinado.

Leva 30 segundos · você volta a este tópico ao terminar
Tienes un relajo de código, exactamente que quieres hacer? buscar en la tabla de pedidos los pedidos del cliente usando su nombre? de ser asi postea aqui la estructura de la tabla en MYSQL para verla (tanto de clientes como de pedidos)
 
Tienes un relajo de código, exactamente que quieres hacer? buscar en la tabla de pedidos los pedidos del cliente usando su nombre? de ser asi postea aqui la estructura de la tabla en MYSQL para verla (tanto de clientes como de pedidos)

Perdon, luego me di cuenta que no especifique algunas cosas... sinceramente soy muy novato en estos temas y he usado dreamweaver para hacer las conexiones, usando un juego de registro por cada tabla:

5TFafGe.png


se6zWYc.png


- - - Actualizado - - -

Debes usar Join para eso.
SQL Joins

Eso es! justamente lo que necesito... ahora como trasformo esa instrucción SQL en PHP??
 
Tienes que cambiar esta query:

PHP:
$result = mysqli_query($link, "SELECT * FROM clientes");

Por esta:

PHP:
$result = mysqli_query($link, "SELECT * FROM clientes INNER JOIN pedidos ON clientes.id_cliente  = pedidos.cliente_id ");

Y ya tendrás el campo $row_Cliente["nombre"]

:encouragement:


También te recomiendo leer esta documentación.

Debes usar Join para eso.
SQL Joins
 
Última edição:
PHP:
<?php
$MySQLi = mysqli_connect("localhost", "root", "pass", "gestorpedidos");
$Result = $MySQLi->query("SELECT * FROM clientes INNER JOIN pedidos ON clientes.id_cliente = pedidos.cliente_id");
?>
<table style="width:712px;border:0">
	<? while($clientInfo = $Result->fetch_assoc()){?>
		<tr>
			<td><?=$clientInfo['id_pedido']?></td>
			<td><?=$clientInfo['fecha']?></td>
			<td><?=$clientInfo['cliente_id']?></td>
			<td><?=$clientInfo['producto_id']?></td>
		</tr>
	<? } ?>
</table>


Así te va a quedar más "limpio".
 
Última edição:
PHP:
<?php
$MySQLi = mysqli_connect("localhost", "root", "pass", "gestorpedidos");
?>
<table style="width:712px;border:0">
	<? while($clientInfo = $MySQLi->query("SELECT * FROM clientes INNER JOIN pedidos ON clientes.id_cliente = pedidos.cliente_id")->fetch_assoc()){?>
		<tr>
			<td><?=$clientInfo['id_pedido']?></td>
			<td><?=$clientInfo['fecha']?></td>
			<td><?=$clientInfo['cliente_id']?></td>
			<td><?=$clientInfo['producto_id']?></td>
		</tr>
	<? } ?>
</table>


Así te va a quedar más "limpio".

Me tira estos errores :S

Inserir CODE, HTML ou PHP:
query("SELECT * FROM clientes")->fetch_assoc()){?>

Notice: Undefined variable: clientInfo in C:\xampp\htdocs\xxxxxx\listadepedido.php on line 66

Notice: Undefined variable: clientInfo in C:\xampp\htdocs\xxxxx\listadepedido.php on line 67

Notice: Undefined variable: clientInfo in C:\xampp\htdocs\xxxxx\listadepedido.php on line 68

Notice: Undefined variable: clientInfo in C:\xampp\htdocs\xxxxx\listadepedido.php on line 69

- - - Actualizado - - -

Asi es el codigo completo:

Inserir CODE, HTML ou PHP:
<?php require_once('Connections/BDPedido.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_BDPedido, $BDPedido);
$query_Cliente = "SELECT * FROM clientes ORDER BY id_cliente ASC";
$Cliente = mysql_query($query_Cliente, $BDPedido) or die(mysql_error());
$row_Cliente = mysql_fetch_assoc($Cliente);
$totalRows_Cliente = mysql_num_rows($Cliente);

mysql_select_db($database_BDPedido, $BDPedido);
$query_Producto = "SELECT * FROM productos ORDER BY id_producto ASC";
$Producto = mysql_query($query_Producto, $BDPedido) or die(mysql_error());
$row_Producto = mysql_fetch_assoc($Producto);
$totalRows_Producto = mysql_num_rows($Producto);

mysql_select_db($database_BDPedido, $BDPedido);
$query_Pedidos = "SELECT * FROM pedidos ORDER BY id_pedido ASC";
$Pedidos = mysql_query($query_Pedidos, $BDPedido) or die(mysql_error());
$row_Pedidos = mysql_fetch_assoc($Pedidos);
$totalRows_Pedidos = mysql_num_rows($Pedidos);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lista de Pedidos</title>
</head>

<body>
<?php
$MySQLi = mysqli_connect("localhost", "root", "", "gestorpedidos");
?>
<table style="width:712px;border:0">
    <? while($clientInfo = $MySQLi->query("SELECT * FROM clientes")->fetch_assoc()){?>
        <tr>
            <td><?=$clientInfo['id_pedido']?></td>
            <td><?=$clientInfo['fecha']?></td>
            <td><?=$clientInfo['cliente_id']?></td>
            <td><?=$clientInfo['producto_id']?></td>
        </tr>
    <? } ?>
</table>
</body>
</html>
<?php
mysql_free_result($Cliente);

mysql_free_result($Producto);

mysql_free_result($Pedidos);
?>
 
PHP:
<?php
$MySQLi = mysqli_connect("localhost", "root", "pass", "gestorpedidos");
$Result = $MySQLi->query("SELECT * FROM clientes INNER JOIN pedidos ON clientes.id_cliente = pedidos.cliente_id");
?>
<table style="width:712px;border:0">
	<? while($clientInfo = $Result->fetch_assoc()){?>
		<tr>
			<td><?=$clientInfo['id_pedido']?></td>
			<td><?=$clientInfo['fecha']?></td>
			<td><?=$clientInfo['cliente_id']?></td>
			<td><?=$clientInfo['producto_id']?></td>
		</tr>
	<? } ?>
</table>

Disculpa se me pasó que la consulta debe estar afuera jaja, igual es posible que no te funcione en XAMPP.
 
PHP:
<?php
$MySQLi = mysqli_connect("localhost", "root", "pass", "gestorpedidos");
$Result = $MySQLi->query("SELECT * FROM clientes INNER JOIN pedidos ON clientes.id_cliente = pedidos.cliente_id");
?>
<table style="width:712px;border:0">
<? while($clientInfo = $Result->fetch_assoc()){?>
<tr>
<td><?=$clientInfo['id_pedido']?></td>
<td><?=$clientInfo['fecha']?></td>
<td><?=$clientInfo['cliente_id']?></td>
<td><?=$clientInfo['producto_id']?></td>
</tr>
<? } ?>
</table>

Disculpa se me pasó que la consulta debe estar afuera jaja, igual es posible que no te funcione en XAMPP.
A qué te refieres con "afuera"? Y porque no funciona en xampp? 🙁

Gracias por la ayuda!!

Enviado desde mi Moto G Play mediante Tapatalk
 
Voltar
Topo