MSLA - Description to each selected list with Ajax

Place for comments, problems, questions, or any issue related to the JavaScript / PHP scripts from this site.
Caterson
Posts: 7

MSLA - Description to each selected list with Ajax

Hello, I'm new to this system, really I served me much this script: https://coursesweb.net/php-mysql/multipl ... ts-ajax_s2
But I have a problem, I can not get the filter is reflected on the page, when I do that the whole database is shown.
Thank you.

Admin Posts: 805
Hi
I not know where the problem is. The script contains a sql and file for test. I tested it, and it works. Maybe you modified something in the $sql or $where variable.
Try to test the script as it is.
1. Import the "test.sql" in your database.
2. In the "msla.php" file add your own data for connecting to MySQL.
3. Access the "test.htm" page on your server and see if it works.

If in your case not works, tell what changes you made (put the code), and how it is the table in your database.

Caterson Posts: 7
Hello , first I want to congratulate you for the page , it is the max . Truth is the first time a page served me so much.
but the problem is that if I filter the data, but what I want is that also when I bring the bd with table with PHP (select) , I want you on the web page is displayed that is leaking dice , and how can I do if you want more than one data shown at the end .
I hope you understand me , I live in Argentina .
The multi filters work, but the process takes the final result is not seen as the select is gradually on page ... and if I want the end result is more than one thing ?
Thank you very much for your help

Admin Posts: 805
I not know what mysql table you have. What end do you want to result? Maybe you want to change the script to result somthing else.
Add here the structure of your mysql table (or attach a zip archive with table exported in sql format) and a picture to explain what you want to get.

Si vives en Argentina, supongo que hablas el español.
Puedes escribir en español, si te esta más fácil de explicar.
- Pienso que voy a entender mejor tu espanol que tu ingles.

Caterson Posts: 7
hola,si el tema es que tengo un web de venta de productos,quiero que se visualiza todos los productos que tengo en la bd,y con la posibilidad que el usuario va a filtrar,que el usuario puede ver que la categoría de producto que el esta eligiendo cambia realmente...todos los productos están en una tabla.Por ejemplo en la tabla hay marcas de auto, si elige marca Fiat que se ve solo los autos de Fiat, y si elige el modelo...para que se ve solo de este modelo de Fiat...y que el usuario pueda ver eso en la tabla..
De ante mano,Gracias.

Admin Posts: 805
Ahora entiendo. Pues, lo que tu quieres desde ese script necesita un poco de modificacion.
Bueno, proba uno de estos scripts:
- Try one of these scripts:
columns-description-msl-ajax-t168.htm#p515
https://coursesweb.net/php-mysql/filter- ... t-lists_s2

Caterson Posts: 7
hola, por lo menos podria ser algo asi : frozzie.com/scu/multiple/test.php
pero me da error en la linea 59

Code: Select all

Notice: Trying to get property of non-object in ...-
que es esa :

Code: Select all

 if ($result->num_rows > 0) {
siento que estoy cerca..y gracias por tu ayuda!!

Admin Posts: 805
No sé qué cambios has hecho en ese script, pero no es el MSLA, sino el script desde:
https://coursesweb.net/ajax/multiple-sel ... ist-ajax_t

- Yo no he visto ningun eror en la pagina: frozzie.com/scu/multiple/test.php
Pon aquí el código del "select_list.php" con los cambios que has hecho.

Caterson Posts: 7

Code: Select all

<?php
// Multiple select lists - https://coursesweb.net/ajax/

// Here add your own data for connecting to MySQL database
$server = 'localhost';
$user = 'root';
$pass = '';
$dbase = 'buswork';

// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'links' if you don`t want to display their data too
$table = 'productosmodificados';
$ar_cols = array('marca','modelo','precio','proveedor','codigo','rubro');

//Here you can add extra columns with data for description
//Let it empty ( array(() ) if you not use additional column for description
$extra_desc = array('...1', '....2', '....3','...4','...5','...6');

if(!isset($_SESSION)) session_start();
header('Content-type: text/html; charset=utf-8');

$preid = 'slo_';  // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0];  // the variable used for the column that wil be selected
$nrc = count($extra_desc);
$re_html = '';  // will store the returned html code

// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
  // set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
  $col = trim(strip_tags($_POST['col']));
  $wval = trim(strip_tags($_POST['wval']));
}

$key = array_search($col, $ar_cols);  // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1];  // gets the column for the WHERE clause
  
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';

$conn = new mysqli('localhost','root','','buswork');     // connect to the MySQL database
if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); }     // check connection

$_SESSION['ar_cols'][$wcol] = isset($wval) ? $conn->real_escape_string($wval) : $wcol;    // store in SESSION the column and its value for WHERE

// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
  $ar_where[] = '`'. $ar_cols[$i-1]. "`='". $_SESSION['ar_cols'][$ar_cols[$i-1]] ."'";
}

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
$get_cols = $key<$last_key ? $col : $col .($nrc >0 ?','. implode(',', $extra_desc) :'');
$get_cols = '`'. str_replace(array('`', ','), array('', '`,`'), $get_cols) .'`';  //add the column names between `..`
$sql = "SELECT DISTINCT $get_cols FROM `$table`".$where;
$result = $conn->query($sql);  // perform the query and store the result

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // sets the "onchange" event, which is added in <select> tag
  $onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';

  // sets the select tag list (and the first <option>), if it's not the last column
  if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';

  while($row = $result->fetch_assoc()) {
    // if its the last column, set a tablle with description, else, adds data in OPTION tags
    if($col==$ar_cols[$last_key]){
      $re_html .= '<table width="200" border="2"><tr><td>'. $row[$col] .'</td></tr>';  //start table with data from first column for description
      for($i=0; $i<$nrc; $i++) $re_html .='<tr><td>'. $row[str_replace('`', '', $extra_desc[$i])] .'</td></tr>';  //add data from $extra_desc columns
      $re_html .='</table>';  //end table
    }
    else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>';
  }

  if($col!=$ar_cols[$last_key]) $re_html .= '</select> '; // ends the Select list
}
else { $re_html = 'Error en la tabla...resultado al menos una fila'; }


$conn->close();

// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
  // adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
  // with ID in each SPAN, according to the columns added in $ar_cols
  for($i=1; $i<count($ar_cols); $i++) {
    if($ar_cols[$i]===null) continue;
    if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
    else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>';
  }

  // adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
  $re_html .= '<script>var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}
else echo $re_html;

Admin Posts: 805
He probado el script con el test.sql y funciona.
No estoy seguro cual es el problema; puede ser que algo en los columns desde $extra_desc no sea corecto.
Pero, no se ve ningun eror en tu pagina: frozzie.com/scu/multiple/test.php

- De todos modos, el error: "Trying to get property of non-object in" aparece cuando algo no esta corecto in $sql.
Para solucionarlo, es necesario verificar los datos de la variable $sql. Añada " echo $sql; " antes de la línea 59 (después de $resultado) y ve $sql dato cuando aparece ese error.
Eventualmente prueba ese SQL en phpMyAdmin.

Caterson Posts: 7
Hola,
la verdad siento que te molesto mucho...pero si hay para pagar algo, avísame,para mi es muy útil todo,y haces un buen trabajo. Ahora si me anda...pero me traer un solo dato de la tabla...como puedo hacer para que me traiga todos los datos(en una tabla) relacionado al filto y que puedo agregar un buscador y otro filto, segun un determinado criterio.
Tenes un teléfono o contacto para dar soporte online (pagado)?

Admin Posts: 805
Hola
Si hay algo de corregir en el código que le hice (por causa de error), ayudo, pero eso de "agregar un buscador y otro filto, segun un determinado criterio" excede la MSLA aplicacion. Tal vez se necesita otro script, personalizado, pero yo no me implico en eso.
Si no hay errores, el script funcciona bien para lo que le hice (crear múltiple select listas). Aplicaciones personalizadas no me implico a hacer. La libertad del tiempo vale mucho mas que el dinero o otra forma de pago.