PHP - Unir dos tablas Mysql para mostrar datos en datatable

 
Vista:
sin imagen de perfil

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Levis (5 intervenciones) el 07/09/2023 21:49:45
Hola, tengo dos tablas mysql "tbl_order_id" y"customers", las tablas tiene en comun el campo"customer_id", Quiero hacer un consulta uniendo las dos tablas por el campo "customer_id" para mostrar el nombre del cliente "customer_name" en la datatable (customer_name esta en tabla customers), Por ahora solo muestro customer_id en la datatable como ve en la figura.

Esta es la consulta que hago en la actualidad de una sola tabla "tbl_order_id", pero solo muestra customer_id:
1
2
3
4
5
6
7
8
9
10
11
12
13
$columns = ' customer_id , order_item, order_date, order_value, customer_name ';
    $table = ' tbl_order_id, customers ';
    $where = " WHERE tbl_order_id.customer_id=customers.customer_id OR customer_id !='' ".$date_range.$order_item;
 
    $columns_order = array(
        0 => 'customer_id',
        1 => 'order_item',
        2 => 'order_date',
		3 => 'order_value',
		4 => 'customer_name'
    );
 
    $sql = "SELECT ".$columns." FROM ".$table." ".$where;

Por favor alguna idea de que puedo hacer?



Quiero hacer un query uniendo las dos tablas: "tbl_order_id" y "customers" como este (pero no funciona):

$columns = ' customer_id , order_item, order_date, order_value, customer_name ';
$table = ' tbl_order_id, customers ';
$where = " WHERE tbl_order_id. customer_id=customers.customer_id OR .customer_id !='' ".$date_range.$order_item;

$columns_order = array(
0 => 'customer_id',
1 => 'order_item',
2 => 'order_date',
3 => 'order_value'
);
$sql = "SELECT ".$columns." FROM ".$table." ".$where;

Por favor alguien me puede ayudar?


datatablelist
tbl_order_id
customers
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

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Yamil Bracho (22 intervenciones) el 07/09/2023 22:18:54
Primero prueba tu sentencia SQL en algun clinete de MySQL como BeaverDB o algo asi.
El select seria algo como :

SELECT c.customer_id , o.order_item, o.order_date, o.order_value, c.customer_name
FROM tbl_order_id o
INNER JOIN customers c ON o.customer_id = c.customer_id
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

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Levis (5 intervenciones) el 07/09/2023 22:38:56
gracias, perdon, el codigo que me funciona y que solo muestra el customer_id es:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$columns = ' customer_id , order_item, order_date, order_value ';
    $table = ' tbl_order_id ';
    $where = " WHERE customer_id !='' ".$date_range.$order_item;
 
    $columns_order = array(
        0 => 'customer_id',
        1 => 'order_item',
        2 => 'order_date',
		3 => 'order_value'
    );
 
 
 
    $sql = "SELECT ".$columns." FROM ".$table." ".$where;
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

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Levis (5 intervenciones) el 08/09/2023 10:41:08
Gracias por la respuesta, probé tu consulta en BeaverDB y funcionó, por favor no se cómo adaptar tu consulta a mi código de forma parecida a esto:
1
2
3
4
5
6
7
8
9
10
11
$columns = ' customer_id , order_item, order_date, order_value, customer_name ';
$table = ' tbl_order_id, customers ';
$where = " WHERE tbl_order_id. customer_id=customers.customer_id OR .customer_id !='' ".$date_range.$order_item;
 
$columns_order = array(
0 => 'customer_id',
1 => 'order_item',
2 => 'order_date',
3 => 'order_value'
);
$sql = "SELECT ".$columns." FROM ".$table." ".$where;

Gracias
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
Imágen de perfil de Mauro
Val: 2.761
Oro
Ha aumentado 1 puesto en PHP (en relación al último mes)
Gráfica de PHP

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Mauro (1036 intervenciones) el 08/09/2023 20:16:26
¿Cuál es la finalidad del arreglo $columns_order?
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

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Levis (5 intervenciones) el 09/09/2023 02:44:59
Gracias por la respuesta, ese código lo descargue y estoy tratando de adaptarlo para mi, segun entiendo $columns_order contiene los datos de la consulta que luego voy a retornar al datatable, aqui todo el codigo que funciona, pero solo presenta el datatable con customer_id:
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
<?php
  // Courtesy: w3 Programmings
  // Article URL: https://w3programmings.com/apply-date-range-filters-in-server-side-jquery-datatables-using-php-and-ajax/
 
  include "config/db-config.php";
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Date range filters in server side jQuery datatables using PHP and AJAX</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.6.5/css/buttons.dataTables.min.css">
 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
 
 
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
  </head>
  <body>
  <style type="text/css">
 .header_part {
	 padding: 1px;
          background: #1abc9c;
		   height:60px;
		   text-align: center;
		   vertical-align: middle;
         }
label span { color: blue; }
</style>
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <div class="well">
		  <header class="header_part">
		  <h2 class="text-center">Detallado de estudios hechos</h2>
          </div>
          <div class="row well input-daterange">
		  <div class="col-sm-4"><label> <span>Item</span> </label>
				<select id="order_item" name="order_item"  class="form-control" onchange="showname(this)" required>
					<option selected disabled value=""> - Select Item- </option>
					<?php include("config/fetch_item.php") ?>
				</select>
			</div>
            <div class="col-sm-3">
			 <label> <span>Initial date</span> </label>
              <input class="form-control datepicker" type="text" name="initial_date" id="initial_date" placeholder="yyyy-mm-dd" style="height: 40px;"/>
            </div>
            <div class="col-sm-3">
			  <label> <span>Final date</span> </label>
              <input class="form-control datepicker" type="text" name="final_date" id="final_date" placeholder="yyyy-mm-dd" style="height: 40px;"/>
            </div>
            <div class="col-sm-2">
              <button class="btn btn-success btn-block" type="submit" name="filter" id="filter" style="margin-top: 30px">
                <i class="fa fa-filter"></i> Filter
            </div>
            <div class="col-sm-12 text-danger" id="error_log"></div>
          </div>
          <br/><br/>
          <table id="fetch_users" class="table table-hover table-striped " cellspacing="0" width="100%">
            <thead style="text-align: center; background-color: #01caca;color: white; font-weight: bold;">
              <tr>
                <th>#</th>
                <th>customer_id</th>
                <th>order_item</th>
				<th>order_value</th>
				<th>order_date</th>
              </tr>
            </thead>
          </table>
        </div>
      </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.6.5/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.6.5/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
    <script type="text/javascript">
      load_data(); // first load
      function load_data(initial_date, final_date, order_item){
        var ajax_url = "jquery-ajax-id_m.php";
        $('#fetch_users').DataTable({
          "order": [[ 0, "desc" ]],
          dom: 'Blfrtip',
          buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
          ],
          "processing": true,
          "serverSide": true,
          "stateSave": true,
          "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
          "ajax" : {
            "url" : ajax_url,
            "dataType": "json",
            "type": "POST",
            "data" : {
              "action" : "fetch_users",
              "initial_date" : initial_date,
              "final_date" : final_date,
              "order_item" : order_item
            },
            "dataSrc": "records"
          },
          "columns": [
            { "data" : "counter" },
            { "data" : "customer_id" },
            { "data" : "order_item" },
			{ "data" : "order_value" },
			//{ "data" : "nombrepaciente" },
			//{ "data" : "gran_total_usd" },
			{ "data" : "order_date" }
 
          ]
        });
      }
 
 
 
      $("#filter").click(function(){
        var initial_date = $("#initial_date").val();
        var final_date = $("#final_date").val();
        var order_item = $("#order_item").val();
 
        if(initial_date == '' && final_date == ''){
          $('#fetch_users').DataTable().destroy();
          load_data("", "", order_item); // filter immortalize only
        }else{
          var date1 = new Date(initial_date);
          var date2 = new Date(final_date);
          var diffTime = Math.abs(date2 - date1);
          var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
 
          if(initial_date == '' || final_date == ''){
              $("#error_log").html("Warning: You must select both (start and end) date.</span>");
          }else{
            if(date1 > date2){
                $("#error_log").html("Warning: End date should be greater then start date.");
            }else{
               $("#error_log").html("");
               $('#fetch_users').DataTable().destroy();
               load_data(initial_date, final_date, order_item);
            }
          }
        }
      });
 
      $('.input-daterange').datepicker({
        todayBtn:'linked',
        format: "yyyy-mm-dd",
        autoclose: true
      });
 
    </script>
  </body>
</html>

Y esta es la datatable que muestra:


datatable_solo_id
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

Unir dos tablas Mysql para mostrar datos en datatable

Publicado por Levis (5 intervenciones) el 12/09/2023 19:28:26
Gracias, ya corregi el codigo y ahora funciona, hice esto para unis las dos tablas:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$query = "SELECT * FROM tbl_order_id,customers WHERE ";
 
 
$query .= 'tbl_order_id.customer_id=customers.customer_id AND ';
 
if($_POST["is_date_search"] == "yes")
{
	if($_POST["customer_name"] != "")
{
 $query .= ' customer_name="'.$_POST["customer_name"].'" AND ';
}
 
if($_POST["start_date"] != "" && $_POST["end_date"] !="")
{
 $query .= ' order_date BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
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