- Php row from database to json php
- PHP & MYSQL: Convert rows and columns to json objects
- Data from database —> to json array in .php —> this array into table in .js and then visualise it in .html by calling .js file
- Php — query data to json response
- Format Database Query Results into a JSON Array and Read into Form
- json_encode
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- How to Convert MySQL Data to JSON using PHP
- PHP Script to convert MySQL to JSON
- Step 1: Create Table and Add Demo Data in Database
Php row from database to json php
Therefore please replace the getData function with: Then replace the addRow function with this version: Solution: The private properties of the Tweet class are not visible to and therefore not included in the json. And convert to array from json using function json_decode().
PHP & MYSQL: Convert rows and columns to json objects
What about doing it in two (I mean three!) lines?
$pdo = new PDO("mysql:host=localhost;dbname=myDB;charset=utf8",'myUserName','myPassword'); $stmt = $pdo->query('SELECT * FROM mytable'); echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
PS. Using SELECT * is considered bad practice.
For mysqli json response in PHP
$link = mysqli_connect($servername, "$username", "$password", "$db_name", $port); if (!$link) $query = "SELECT * FROM mytable"; $result = mysqli_query($link,$query); echo json_encode(mysqli_fetch_all($result,MYSQLI_ASSOC)); @mysql_close($link);
How to extract and access data from JSON with PHP?, This is intended to be a general reference question and answer covering many of the never-ending «How do I access data in my JSON?» questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.
Data from database —> to json array in .php —> this array into table in .js and then visualise it in .html by calling .js file
The remaining issues with the PHP are:
1) You’re not using your loop to create an array of rows, and instead you’re trying to encode the Mysqli result set. That doesn’t contain the row data directly, it has to be fetched (which is what the while loop is for).
2) You’re still outputting HTML as well, which will confuse the JavaScript code when it tries to read your response (and assumes — as it should — that it can treat it all as JSON)
3) You’re not echoing the encoded JSON — in fact you’re not doing anything with it at all.
$results = []; //new blank array ready for populating with row data while($res = mysqli_fetch_array($result_set)) < $results[] = array( "date" =>$res["date"], "temperature" => (int) $res["temperature"], "pressure" => (int) $res["pressure"], "rpm" => (int) $res["rpm"], ); //add the necessary fields from the newly fetched row data into the results array > echo json_encode($results); //encode the array, and then echo the result so that it goes into the response for the JavaScript to read.
Also I don’t know where you found the JavaScript, but it seems to be overcomplicating things, or is expecting a much more complex result set from the server, and it doesn’t entirely make sense anyway in some places — I don’t think it would work properly even with the dataset it’s anticipating.
Therefore please replace the getData function with:
async function getData() < let response = await fetch("http://localhost:8000/read.php"); let json = await response.json(); var data = new google.visualization.DataTable(); data.addColumn('string', 'date'); data.addColumn('number', 'temperature'); data.addColumn('number', 'pressure'); data.addColumn('number', 'rpm'); //loop through the data and add a table row and a chart row for each row received from the server for (var i = 0; i < json.length; i++) < addRow(json[i]); data.addRow(Object.values(json[i])); >var options = < chart: < title: 'Sensor Data', subtitle: '' >, width: 1045, height: 500 >; var chart = new google.charts.Line(document.getElementById('linechart_material')); chart.draw(data, google.charts.Line.convertOptions(options)); >
Then replace the addRow function with this version:
Php — How to build a JSON array from mysql database, Okay I have been racking my brain trying to build a JSON array from mysql. The array MUST be in the following format. I am using fullcalendar and want to make the events on the calendar dynamic. Be
Php — query data to json response
The private properties of the Tweet class are not visible to json_encode and therefore not included in the json. Make them public or implement \JsonSerializable with a custom jsonSerialize implementation, e.g.
class Tweet implements \JsonSerializable < // . public function jsonSerialize() < return [ 'foo' =>$this->foo, 'bar' => $this->bar ]; > >
More on visibility: http://docs.php.net/language.oop5.visibility The not so obvious thing is that your static method loadTweetData can indeed access the private props because the objects are of the same class.
Note off topic: Having your Tweet model extend User is a little awkward because the Tweet is not a User (violates Liskov substitution principle).
Read JSON Data Using PHP, Use $obj = json_decode ($yourJSONString); to convert it to an object. Then use foreach ($obj->response->docs as $doc) to iterate over the «docs». …
Format Database Query Results into a JSON Array and Read into Form
You can use function json_encode() to convert an array into json format. And convert to array from json using function json_decode().
you have to just pass one parameter in function that is the array you want to encode or decode.
header("HTTP/1.0 200 OK"); header('Content-type: text/json; charset=utf-8'); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Pragma: no-cache"); if (mysql_num_rows($result) > 0) < while($row = mysql_fetch_row($result)) < echo json_encode( $row ); >> else < // no // print status message echo json_encode( "No rows found!" ); >die();
Getting data from MYSQL into JSON using PHP, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams
json_encode
Возвращает строку, содержащую JSON-представление для указанного value . Если параметр является массивом ( array ) или объектом ( object ), он будет рекурсивно сериализован.
Если сериализуемое значение является объектом, то по умолчанию будут включены только публично видимые свойства. В качестве альтернативы класс может реализовать интерфейс JsonSerializable для управления тем, как его значения сериализуются в JSON .
На кодирование влияет параметр flags и, кроме того, кодирование значений типа float зависит от значения serialize_precision.
Список параметров
value — значение, которое будет закодировано. Может быть любого типа, кроме resource.
Функция работает только с кодировкой UTF-8.
Замечание:
PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.
Битовая маска, составляемая из значений JSON_FORCE_OBJECT , JSON_HEX_QUOT , JSON_HEX_TAG , JSON_HEX_AMP , JSON_HEX_APOS , JSON_INVALID_UTF8_IGNORE , JSON_INVALID_UTF8_SUBSTITUTE , JSON_NUMERIC_CHECK , JSON_PARTIAL_OUTPUT_ON_ERROR , JSON_PRESERVE_ZERO_FRACTION , JSON_PRETTY_PRINT , JSON_UNESCAPED_LINE_TERMINATORS , JSON_UNESCAPED_SLASHES , JSON_UNESCAPED_UNICODE , JSON_THROW_ON_ERROR . Смысл этих констант объясняется на странице JSON-констант.
Устанавливает максимальную глубину. Должен быть больше нуля.
Возвращаемые значения
Возвращает строку ( string ), закодированную JSON или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Добавлена константа JSON_THROW_ON_ERROR для параметра flags . |
7.2.0 | Добавлены константы JSON_INVALID_UTF8_IGNORE и JSON_INVALID_UTF8_SUBSTITUTE для параметра flags . |
7.1.0 | Добавлена константа JSON_UNESCAPED_LINE_TERMINATORS для параметра flags . |
7.1.0 | При кодировании чисел с плавающей точкой ( float ) используется serialize_precision вместо precision. |
Примеры
Пример #1 Пример использования json_encode()
$arr = array( ‘a’ => 1 , ‘b’ => 2 , ‘c’ => 3 , ‘d’ => 4 , ‘e’ => 5 );
?php
Результат выполнения данного примера:
Пример #2 Пример использования json_encode() с опциями
echo «Обычно: » , json_encode ( $a ), «\n» ;
echo «Теги: » , json_encode ( $a , JSON_HEX_TAG ), «\n» ;
echo «Апострофы: » , json_encode ( $a , JSON_HEX_APOS ), «\n» ;
echo «Кавычки: » , json_encode ( $a , JSON_HEX_QUOT ), «\n» ;
echo «Амперсанды: » , json_encode ( $a , JSON_HEX_AMP ), «\n» ;
echo «Юникод: » , json_encode ( $a , JSON_UNESCAPED_UNICODE ), «\n» ;
echo «Все: » , json_encode ( $a , JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE ), «\n\n» ;
echo «Отображение пустого массива как массива: » , json_encode ( $b ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $b , JSON_FORCE_OBJECT ), «\n\n» ;
echo «Отображение неассоциативного массива как массива: » , json_encode ( $c ), «\n» ;
echo «Отображение неассоциативного массива как объекта: » , json_encode ( $c , JSON_FORCE_OBJECT ), «\n\n» ;
$d = array( ‘foo’ => ‘bar’ , ‘baz’ => ‘long’ );
echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d ), «\n» ;
echo «Ассоциативный массив всегда отображается как объект: » , json_encode ( $d , JSON_FORCE_OBJECT ), «\n\n» ;
?>
Результат выполнения данного примера:
Обычно: [«»,»‘bar'»,»\»baz\»»,»&blong&»,»\u00e9″] Теги: [«\u003Cfoo\u003E»,»‘bar'»,»\»baz\»»,»&blong&»,»\u00e9″] Апострофы: [«»,»\u0027bar\u0027″,»\»baz\»»,»&blong&»,»\u00e9″] Кавычки: [«»,»‘bar'»,»\u0022baz\u0022″,»&blong&»,»\u00e9″] Амперсанды: [«»,»‘bar'»,»\»baz\»»,»\u0026blong\u0026″,»\u00e9″] Юникод: [«»,»‘bar'»,»\»baz\»»,»&blong&»,»é»] Все: [«\u003Cfoo\u003E»,»\u0027bar\u0027″,»\u0022baz\u0022″,»\u0026blong\u0026″,»é»] Отображение пустого массива как массива: [] Отображение неассоциативного массива как объекта: <> Отображение неассоциативного массива как массива: [[1,2,3]] Отображение неассоциативного массива как объекта: > Ассоциативный массив всегда отображается как объект: Ассоциативный массив всегда отображается как объект:
Пример #3 Пример использования опции JSON_NUMERIC_CHECK
echo «Строки, содержащие числа преобразуются в числа» . PHP_EOL ;
$numbers = array( ‘+123123’ , ‘-123123’ , ‘1.2e3’ , ‘0.00001’ );
var_dump (
$numbers ,
json_encode ( $numbers , JSON_NUMERIC_CHECK )
);
echo «Строки, содержащие некорректно заданные числа» . PHP_EOL ;
$strings = array( ‘+a33123456789’ , ‘a123’ );
var_dump (
$strings ,
json_encode ( $strings , JSON_NUMERIC_CHECK )
);
?>?php
Результатом выполнения данного примера будет что-то подобное:
Строки, содержащие числа преобразуются в числа array(4) < [0]=>string(7) "+123123" [1]=> string(7) "-123123" [2]=> string(5) "1.2e3" [3]=> string(7) "0.00001" > string(28) "[123123,-123123,1200,1.0e-5]" Строки, содержащие некорректно заданные числа array(2) < [0]=>string(13) "+a33123456789" [1]=> string(4) "a123" > string(24) "["+a33123456789","a123"]"
Пример #4 Пример с последовательными индексами, начинающимися с нуля, и непоследовательными индексами массивов
echo «Последовательный массив» . PHP_EOL ;
$sequential = array( «foo» , «bar» , «baz» , «blong» );
var_dump (
$sequential ,
json_encode ( $sequential )
);
?php
echo PHP_EOL . «Непоследовательный массив» . PHP_EOL ;
$nonsequential = array( 1 => «foo» , 2 => «bar» , 3 => «baz» , 4 => «blong» );
var_dump (
$nonsequential ,
json_encode ( $nonsequential )
);
echo PHP_EOL . «Последовательный массив с одним удалённым индексом» . PHP_EOL ;
unset( $sequential [ 1 ]);
var_dump (
$sequential ,
json_encode ( $sequential )
);
?>
Результат выполнения данного примера:
Последовательный массив array(4) < [0]=>string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" [3]=> string(5) "blong" > string(27) "["foo","bar","baz","blong"]" Непоследовательный массив array(4) < [1]=>string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" [4]=> string(5) "blong" > string(43) "" Последовательный массив с одним удалённым индексом array(3) < [0]=>string(3) "foo" [2]=> string(3) "baz" [3]=> string(5) "blong" > string(33) ""
Пример #5 Пример использования опции JSON_PRESERVE_ZERO_FRACTION
Результат выполнения данного примера:
How to Convert MySQL Data to JSON using PHP
One of the important responsibilities in web development for PHP is the conversion of data from MySQL to JSON format. JSON is favoured over XML as a data interchange format between web applications and has grown in popularity over time.
JSON has its own benefits, such as being lightweight, allowing for the storage of sophisticated data structures in plain text, and being extremely readable by humans. Here, we’ve already spoken about translating JSON data to MySQL. Let’s now examine how to use PHP to translate the MySQL result set to JSON.
PHP Script to convert MySQL to JSON
Step 1: Create Table and Add Demo Data in Database
If you do not have a database table ready, use the following SQL query to create a technologies table with id and tech_name table properties and add some data into the technologies table to check that data using the jQuery live search box in PHP.
CREATE TABLE technologies ( id INT NOT NULL AUTO_INCREMENT , tech_name VARCHAR(255) NOT NULL , PRIMARY KEY (id) ); INSERT INTO technologies VALUES(1,'HTML'); INSERT INTO technologies VALUES(2,'CSS'); INSERT INTO technologies VALUES(3,'JAVASCRIPT'); INSERT INTO technologies VALUES(4,'JQUERY'); INSERT INTO technologies VALUES(5,'PHP'); INSERT INTO technologies VALUES(6,'AJAX'); INSERT INTO technologies VALUES(7,'NODEJS'); INSERT INTO technologies VALUES(8,'EXPRESSJS'); INSERT INTO technologies VALUES(9,'ANGULARJS'); INSERT INTO technologies VALUES(10,'REACTJS');