phpmysqlnodescytoscape.jscytoscape-web

name cytoscape's nodes by primary key in mysql table


I'm trying to display a network using cytoscape based on a mysql database, I've got two tables, one contains the name (device_id), ip and SN that means serial number (PK) of each device in the network, the otherone has relation's info: origin's SN destiny's SN, interface and port.

I've made those three querys:

$query = 'SELECT * FROM dispositivos';
$result = mysql_query($query) or die('Consulta fallida: ' . mysql_error());
$numdispositivos = mysql_num_rows($result);

then I've tried to make a for loop to create the nodes based on the number of rows at the table:

 var numerodispositivos = "<?php echo $numdispositivos; ?>";

using this loop im drawing nodes:

for (var i = 0; i < numerodispositivos; i++) {
            cy.add({
                data: { id: 'node' + i }
                }
            );
            var source = 'node' + i;
            cy.add({
                data: {
                    id: 'edge' + i,
                    source: source,
                    target: (i % 2 == 0 ? 'a' : 'b')
                }
            });

I would like to name those nodes with the primary key of "dispositivos" but i don't know how to iterate through the table row by row or how to extract that info.

Any help?

Thanks in advance


Solution

  • You could try using an array that includes your primary key in php instead of just the number of rows (you'll need to specify what your primary key is):

    $j=0;
    while ($row = mysql_fetch_array($result)) {
        $primary_key = $row["PRIMARY_KEY"];
        $php_array[$primary_key] = $j;
        $j++;
    }
    
    $json_from_php = json_encode($php_array);
    

    Th resulting JSON array could then be echo'd in JS (where i is your primary key in the loop), allowing you to run a for loop that you could then pull primary key strings/numbers from:

    var jsonArray = "<?php echo $json_from_php; ?>";
    
    for (var i in jsonArray) {
        cy.add({
            data: { id: i }
            }
        );
        var source = i;
        cy.add({
            data: {
                id: i,
                source: source,
                target: (jsonArray[i] % 2 == 0 ? 'a' : 'b')
            }
        });
    }
    

    You probably also want to move to mysqli or PDO instead of mysql.