Hay 2 mesas. Estoy usando do while en la segunda tabla con satinID de la primera tabla. ¿Cómo hago esto como un solo dato json?

Tabla 1

<? Php
mysql_select_db ($database_intranet_connections, $ intranet_connections);
$query_mus = "SELECT
zey_satinalma.satinID,
zey_satinalma.mik,
zey_satinalma.fiyat,
zey_satinalma.alimtarih,
   FROM
zey_satinalma
WHERE
zey_satinalma.yilid = 2 AND
zey_satinalma.islendi <> 1
";
$ mus = mysql_query ($ query_mus, $ intranet_connections) or die (mysql_error ());
$ row_mus = mysql_fetch_assoc ($mus);

?>

Tabla 2

 <? php do {

$ colname = $ row_mus ['satinID'];
$ colname_columns = "-1";
if (isset ($ colname)) {
  $ colname_columns = $colname;
}
mysql_select_db ($database_intranet_connections, $ intranet_connections);
$query_kalanmikt $ = sprintf ( "SELECT zeytin_depo.zeytinID, zeytin_depo.kuyuID,  FROM zeytin_depo  WHERE kuyuID! = 8000 AND zeytin_depo.satinID =(%s)", GetSQLValueString ($colname_columns ," int "));

Bla bla?>

imagen de pantalla como está ahora

-1
Ulaş Cantepe 11 nov. 2017 a las 23:35

2 respuestas

La mejor respuesta
  • Hice una solución mysqli (estilo OOP), porque el mysql (la que estás usando) está obsoleta a partir de PHP 5.5.0 y tiene ha sido eliminado a partir de PHP 7.0.0. Sin embargo, te recomiendo encarecidamente que comiences a usar PDO en su lugar.
  • Puede / debe usar una declaración SQL.
  • Debe preparar las sentencias sql para evitar la inyección de SQL .
  • Otros recursos: Cómo usar mysqli correctamente, Declaraciones preparadas de PHP.

Buena suerte.

<?php

// Db configs.
define('HOST', '...');
define('PORT', 3306);
define('DATABASE', '...');
define('USERNAME', '...');
define('PASSWORD', '...');

// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // Set it to 0 on a live server!

/**
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions 
 * (mysqli_sql_exception). They are catched in the try-catch block.
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * See: http://php.net/manual/en/class.mysqli-driver.php
 * See: http://php.net/manual/en/mysqli-driver.report-mode.php
 * See: http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/**
 * Create a new db connection.
 * 
 * @see http://php.net/manual/en/mysqli.construct.php
 */
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);

/*
 * The SQL statement to be prepared. Notice the so-called markers, 
 * e.g. the "?" signs. Later, when using bind_param(), they will 
 * be replaced with the corresponding values.
 * 
 * SQL statement explanation: Get all records (e.g. values for the 
 * given column names) from zeytin_depo, together with the 
 * corresponding details (e.g. field values) from zey_satinalma, 
 * filtered by the yilid, islendi and kuyuID values.
 * 
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$sql = "SELECT 
            zd.zeytinID,
            zd.kuyuID,
            zs.satinID,
            zs.mik,
            zs.fiyat,
            zs.alimtarih,
        FROM zeytin_depo AS zd 
        LEFT JOIN zey_satinalma AS zs ON zs.satinID = zd.satinID 
        WHERE 
            zs.yilid = ? 
            AND zs.islendi <> ?
            AND zd.kuyuID != ?";

/*
 * Prepare the SQL statement for execution.
 * 
 * See: http://php.net/manual/en/mysqli.prepare.php
 */
$statement = $connection->prepare($sql);

/*
 * Bind variables for the parameter markers (?) in the 
 * SQL statement that was passed to prepare(). The first 
 * argument of bind_param() is a string that contains one 
 * or more characters which specify the types for the 
 * corresponding bind variables.
 * 
 * See: http://php.net/manual/en/mysqli-stmt.bind-param.php
 */
$yilid = 2;
$islendi = 1;
$kuyuID = 8000;

$statement->bind_param('iii', $yilid, $islendi, $kuyuID);

/*
 * Execute the prepared SQL statement.
 * When executed, any parameter markers which exist ("?") will 
 * automatically be replaced with the appropriate data of the
 * binded variables.
 * 
 * See: http://php.net/manual/en/mysqli-stmt.execute.php
 */
$executed = $statement->execute();

/*
 * Get the result set from the prepared statement.
 * 
 * NOTA BENE:
 * Available only with mysqlnd ("MySQL Native Driver"). If this 
 * is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in 
 * PHP config file (php.ini) and restart web server (I assume Apache) and 
 * mysql service. Or use the following functions instead:
 * mysqli_stmt::store_result() + mysqli_stmt::bind_result() + mysqli_stmt::fetch().
 * 
 * See: http://php.net/manual/en/mysqli-stmt.get-result.php
 * See: https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
 */
$result = $statement->get_result();

/*
 * Get the number of rows in the result.
 * 
 * See: http://php.net/manual/en/mysqli-result.num-rows.php
 */
$numberOfRows = $result->num_rows;

/*
 * Fetch data and save it into an array.
 * 
 * See: http://php.net/manual/en/mysqli-result.fetch-array.php
 */
$fetchedData = array();
if ($numberOfRows > 0) {
    // Fetch all rows at once.
    $fetchedData = $result->fetch_all(MYSQLI_ASSOC);

    // ...or fetch one row at a time.
    // while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    //     $fetchedData[] = $row;
    // }
}

/*
 * Free the memory associated with the result. You should 
 * always free your result when it is not needed anymore.
 * 
 * See: http://php.net/manual/en/mysqli-result.free.php
 */
$result->close();

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 * 
 * See: http://php.net/manual/en/mysqli-stmt.close.php
 */
$statementClosed = $statement->close();

// Just for testing: display fetched data as array.
echo '<pre>' . print_r($fetchedData, TRUE) . '</pre>';

/*
 * Just for testing: how to loop through the 
 * fetched data list and to use the values.
 */
foreach ($fetchedData as $key => $row) {
    echo 'Row ' . ($key + 1) . ': ';

    echo 'zeytinID is ' . $row['zeytinID'] . ', ';
    echo 'kuyuID is ' . $row['kuyuID'] . ', ';
    echo 'satinID is ' . $row['satinID'] . ', ';
    echo 'mik is ' . $row['mik'] . ', ';
    echo 'fiyat is ' . $row['fiyat'] . ', ';
    echo 'alimtarih is ' . $row['alimtarih'] . ', ';

    echo '<br/><br/>';
}

// Print json-encoded data.
echo json_encode($fetchedData);
0
11 nov. 2017 a las 22:19

Resolví el problema. Creo una vista para la segunda consulta. Hice una sola consulta con combinación izquierda. el código de resultado es tan exitoso como el. Gracias por su interés

while($data= mysql_fetch_assoc($sat))
{
    //$dataarray["data"][]=array_map('utf8_encode',$data);
    $dataarray["data"][]=$data;

    }
    echo json_encode($dataarray,JSON_UNESCAPED_UNICODE);
}
0
Ulaş Cantepe 11 nov. 2017 a las 22:17