mysql — вопрос по сервису php code

Я создал службы в php, но я столкнулся с некоторыми проблемами, вот я и реализовал свой код

 <?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];
echo '{ <br>"'.$city.'" : [ <br>';

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){
echo  '{ <br>';
echo '"date" : "'.$re2["day"].'-'.$re2["month"].'-'.$re2["year"].'",<br>';

if($re2['price']==''){ echo "Price : -- , <br>";}
else{
echo '"Price" : "'.$re2["price"].'" <br>';
}
echo '}, <br>';
}
echo ']<br>}';
}
?>

Формат ответа JSON, как это.

{
"Ahmedabad" : [
{
"date" : "1-10-2014",
"Price" : "353"},
{
"date" : "2-10-2014",
"Price" : "353"},
{
"date" : "3-10-2014",
"Price" : "327"},
]
}

Но в окончании словаря формата json как это убрать , , Можете ли вы предложить мне.

0

Решение

Прежде всего, вы не можете иметь <br> в ответе JSON, если этот ответ только для показа, а не для фактического использования.

Для того, чтобы удалить это , в конце вам нужно создать каждую «строку» в переменной, которую вы можете редактировать, а не просто повторить строку.

Вот некоторый код, который выполнит это:

<?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];
echo '{
"'.$city.'" : [
';

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){
$line = '{
';

$line.= '"date" : "'.$re2["day"].'-'.$re2["month"].'-'.$re2["year"].'",
';

if($re2['price']=='')
{
$line.= "Price : -- ,
";
}
else
{
$line.= '"Price" : "'.$re2["price"].'"';
}
$line.= '},';
echo $line;
}
$line = substr($line,0,-1);
echo ']
}';
}
?>

Вы должны использовать встроенные в PHP функции форматирования JSON, такие как json_encode ()

Чтобы получить хороший ответ JSON, вам нужно правильно работать с данными, чтобы избежать появления ошибок.

Так что этот код гораздо лучше использует PHP и MySQL:

<?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){
// create each line in the city
$line["date"] = $re2["day"].'-'.$re2["month"].'-'.$re2["year"];

if($re2['price']=='')
{
$line["Price"] = "--";
}
else
{
$line["Price"] = $re2["price"];
}

// add the line to the city
$cities[$city][] = $line;
}
}
// encode to json
json_encode($cities);
?>
1

Другие решения

Я думаю, что это должно сделать это. Теперь я добавляю запятую в начале блока дата / цена, в каждой комбинации дата / цена, кроме первой (проверяется новой переменной $ ct).

 <?php
include("db.php");
$month=10;
$year=date("Y");
$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');
while($re1=mysql_fetch_array($sq)){
$id = $re1['id'];
$city = $re1['city'];
$city_id = $re1['id'];
echo '{ <br>"'.$city.'" : [ <br>';

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY day ASC';
$sql2=mysql_query($sql);
$ct = 0;
while($re2=mysql_fetch_array($sql2)){
if ($ct > 0) { echo ', ';}
ct++;
echo  '{ <br>';
echo '"date" : "'.$re2["day"].'-'.$re2["month"].'-'.$re2["year"].'",<br>';

if($re2['price']==''){ echo "Price : -- , <br>";}
else{
echo '"Price" : "'.$re2["price"].'" <br>';
}
echo '}<br>';
}
echo ']<br>}';
}
?>
0

попробуй это

include("db.php");
$month=10;
$year=date("Y");

$sq=mysql_query('select * from city where id=1 ORDER BY city ASC');

$city=array();

while($re1=mysql_fetch_array($sq)){
$city['city'] = $re1['city'];

$sql='select * from price where month="'.$month.'" and year="'.$year.'" and city="'.$id.'" ORDER BY         day ASC';
$sql2=mysql_query($sql);
while($re2=mysql_fetch_array($sql2)){

$city['city'] = array("date" => $re2["day"].'-'.$re2["month"].'-'.$re2["year"];

if($re2['price']==''){
$city['city'] = array('price'=>'--');
}else{
$city['city'] = array('price'=>$re2["price"]);
}
}
}
echo json_encode($city);
?>
0

Добро пожаловать в стек переполнения. Вместо того, чтобы ответить на ваш вопрос, что именно нужно изменить, чтобы исправить ваш код, вот реорганизованная версия вашего кода с примечаниями, которые мне бы очень хотелось иметь, когда я начинал программировать на PHP. Надеюсь, здесь что-то есть для вас:

$month = 10;
$year = date('Y');

// 1. You can get the data you're after in a single query using a LEFT JOIN.
//    In your original code you run one database query for every city, which
//    quickly slows down the program as you add more cities. This change is
//    mostly for keeping the code clean in this case, but in practice it's
//    good to avoid unnecessary back and forth with the database.
//
// 2. The MySQL DATE data type opens up a lot of functionality in your queries
//    that isn't available when storing day, month and year in separate columns.
//
// 3. The mysql_* functions are deprecated and no longer exist in PHP 5.5.0,
//    so you ideally shouldn't be using them (see the red box in the docs):
//
//        http://php.net/manual/en/function.mysql-query.php
//
//    I've opted to demo PDO with a parameterised query as I like it, but you
//    could use the mysqli_* functions instead. The following pretends that
//    $connection is an instance of PDO. The variable `$stmt` stands for
//    'statement'. Further info on PDO:
//
//        http://php.net/manual/en/class.pdo.php
//        http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
//
$stmt = $connection->prepare(
'SELECT
city.name AS city,
price.price,
DATE_FORMAT(price.date, '%d-%m-%Y') AS date
FROM city
LEFT JOIN price ON price.city_id = city.id
WHERE MONTH(price.date) = :month AND YEAR(price.date) = :year
ORDER BY DAY(price.date) ASC'
);

$stmt->bindValue(':month', $month);
$stmt->bindValue(':year', $year);

$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// This short array syntax is valid in PHP 5.4 and higher.
// If you're using 5.3 or lower, `[]` would be `array()`
$output = [];

foreach ($results as $row) {
$output[$row['city']] = [
'date' => $row['date'],
'price' => $row['price'] ?: '--'
];
}

json_encode($output);

Главные примечания:

  • База данных действительно мощная: во многих случаях проще и быстрее организовать данные в запросе, чем в коде PHP.
  • Будь проще: попытаться достичь вещей самым простым способом (например, json_encode вместо того, чтобы вручную создавать строку JSON). Если что-то, что вы пытаетесь сделать, кажется слишком сложным, возможно, есть лучший способ решить проблему.
  • Люблю твой код: Пробелы, отступы и присвоение значимых имен переменным значительно улучшат читабельность вашего кода. Вы будете благодарить себя (или кто-то, кто читает ваш код) через год или два.
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector