I have a static code to update some select boxes.
The original structure code:
$result = "
({
'options': [
{'value': '','description': '(pick an item)'},
{'value': 'test','description': 'test'},
{'value': 'test_2','description': 'test_2'}
]
});
";
I'm trying to make this dynamic and connect to my table in Postgresql Database but my code don't works.
Here is My Code:
if($value=="asus"){
require("includes/connection.php");
$sth = $dbh->prepare( "SELECT * FROM mapa_ferias WHERE area = 'Asus' " );
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$result = "
({
'options': [";
while($row = $sth->fetch()) {
$result += "{'value': '" + $row['nome'] + "','description': '" + $row['nome'] + "'},";
}
$result +=
"]
});
";
}
I hope you can help me. Thanks in advance.
Please do not try to build JSON data yourself.. PHP has a function for it: json_encode()
if ($value=="asus"){
require("includes/connection.php");
$sth = $dbh->prepare( "SELECT * FROM mapa_ferias WHERE area = 'Asus' " );
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$options = array();
while($row = $sth->fetch()) {
$options[] = array(
'value' => $row['nome'],
'description' => $row['nome']
);
}
$sth->closeCursor();
$result = '('.json_encode(array(
'options' => $options
)).')';
}
Related
I have a problem getting the data in JSON format via the data.php file.
When I try see JSON I got this:
"{"draw":0,"recordsTotal":null,"recordsFiltered":120,"data":[]}"
but needs the php script to retrieve data from the table all entries for the column date, name, id like datatables AJAX instructions . When doing this using the local XAMPP server, the script retrieves the entries from the mysql table and the data is displayed as a table using datatables.
Here is my PHP code
$connect = new PDO("mysql:host=localhost;dbname=abc", "root", "PASSWORD");
$query = "SELECT * FROM abc_result ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE DATE LIKE "%'.$_POST["search"]["value"].'%"
OR NAME LIKE "%'.$_POST["search"]["value"].'%"
OR ID LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST['DATE']))
{
$query .= 'ORDER BY '.$column[$_POST['DATE']['0']['column']].' '.$_POST['DATE']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY ID DESC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$result = $connect->query($query . $query1);
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['DATE'];
$sub_array[] = $row['NAME'];
$sub_array[] = $row['ID'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT COUNT(*) FROM abc_result";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchColumn();
return $result;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => count_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
I'm trying to retrieve data from my mysql database and display it using datatables. locally I've been able to do it but I'd like to do it on a NAS (QNAP) so that when I go to a website the table would be visible by anyone who visits it. To do this, I installed MariaDB 5 and PHPmyAdmin. I was able to connect to the database but the php code does not display the data as I would like it to
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
I want to accept user data from a form, use AJAX to post the values to a PHP script, which will insert them into the database.
JQuery:
$(".add").click(function(){
var order = {
Name: $name.val(),
Drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/ajax/api/orders.php',
data: order,
success: function(newOrder){
$orders.append('<li>Name: ' + newOrder.Name +', Drink: '+ newOrder.Drink +'</li>')
}
})
});
Php:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","xxxxxxxxx","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from orders";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
can somebody help me with it?
i think you should insert before you get all orders
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
mysqli_query($connection, $sql) or
die("Error in Inserting" . mysqli_error($connection))
$id = mysqli_insert_id ($connection);
$sql = "select * from orders where Id = $id";
$result = mysqli_query($connection, $sql) or
die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
The javascript will be right this:
$(".add").click(function(){
var order = {
Name: $name.val(),
Drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/ajax/api/orders.php',
data: order,
success: function(newOrder) {
$.each(newOrder, function(order) {
//$order is a ul that have id = orders
$orders.append('<li>Name: ' + order.Name +', Drink: '+ order.Drink +'</li>');
});
}
});
});
and if you need anything ask :]
UPDATE
please update the success function you have to this
success: function(data) {
data.forEach(function(order) {
//$orders is a ul that have id = orders
$orders.append('<li>Name: ' + order.Name +', Drink: '+ order.Drink +'</li>');
});
}
UPDATE 2
success: function(data) {
var obj = JSON.parse(data);
var length = obj.length;
for (var i = 0; i < length; i++) {
$orders.append('<li>Name: ' + obj[i].Name +', Drink: '+ obj[i].Drink +'</li>');
}
}
UPDATE 3
$name = $_POST["Name"];
$drink = $_POST["Drink"];
$sql2 = "INSERT INTO orders (Id, Name, Drink) VALUES (NULL, '$name', '$drink')";
mysqli_query($connection, $sql2) or
die("Error in Inserting" . mysqli_error($connection))
$id = mysqli_insert_id($connection);
$sql = "select * from orders where Id = $id";
$result = mysqli_query($connection, $sql) or
die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
I am making a script which will load all categories from a database. I just don't know how I can do this in a way which is shorter.
I am trying to figure out a way in which I can theoretically load infinite levels of categories.
$stmt1 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row1 = $db->fetch($stmt1))
{
$stmt2 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row1['Rubrieknummer'] . "'");
while($row2 = $db->fetch($stmt2))
{
$stmt3 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row2['Rubrieknummer'] . "'");
while($row3 = $db->fetch($stmt3))
{
$stmt4 = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek = '" . $row3['Rubrieknummer'] . "'");
while($row4 = $db->fetch($stmt4))
{
$row3['CATEGORY3'][] = array(
'CATEGORY4_NAME' => ucfirst(strtolower($row4['Rubrieknaam'])),
);
}
$row2['CATEGORY3'][] = array(
'CATEGORY3_NAME' => ucfirst(strtolower($row3['Rubrieknaam'])),
'CATEGORY4' => $row2['CATEGORY4'],
);
}
$row1['CATEGORY2'][] = array(
'CATEGORY2_NAME' => ucfirst(strtolower($row2['Rubrieknaam'])),
'CATEGORY3' => $row2['CATEGORY3'],
);
}
$catagories[] = array(
'CATEGORY_NAME' => ucfirst(strtolower($row1['Rubrieknaam'])),
'CATEGORY2' => $row1['CATEGORY2'],
);
}
I would like to have some ideas on how to make this happen.
(I am using a little template system that processes the array that is being made)
EDIT:
Thanks to Ivijan Stefan Stipić I was able to solve this.
This is what I ended up doing
$categories = build_category(0);
And the function:
function build_category($parent, $row = NULL)
{
global $db;
// Initialise array
$data = array();
// Basic SQL statement
$sql = "SELECT * FROM Rubriek";
// Where condition based on $row
if(is_null($row))
{
$where = " WHERE Hoofdrubriek IS NULL";
}
else
{
$where = " WHERE Hoofdrubriek = '" . $row['Rubrieknummer'] . "'";
}
// Execute query
$stmt = $db->query($sql . $where);
// Next level parent
$next = $parent + 1;
// Fetch results
while($row = $db->fetch($stmt))
{
$data[] = array(
'CATEGORY' . $parent . '_NAME' => ucfirst(strtolower($row['Rubrieknaam'])),
'CATEGORY' . $next => build_category($next, $row),
);
}
// Return data
return $data;
}
What do you think about this solution?
function next_level($val)
{
global $db;
$stmt = $db->query("SELECT * FROM Rubriek WHERE Rubrieknummer != '" .$val. "' AND Hoofdrubriek = '" .$val. "'");
while($row = $db->fetch($stmt))
{
echo ucfirst(strtolower($row['Rubrieknaam']));
echo next_level($row['Rubrieknummer']);
}
}
$stmt = $db->query("SELECT * FROM Rubriek WHERE Hoofdrubriek IS NULL");
while($row = $db->fetch($stmt))
{
echo ucfirst(strtolower($row['Rubrieknaam']));
echo next_level($row['Rubrieknummer']);
}
If I understand correctly this is the number of categories with unlimited subcategories.
How can i select values from database
Here is my code:
$sql = 'SELECT * FROM ' . $wpdb->base_prefix . 'item WHERE uname = "'. $_POST['login_name'] . '" '; $result = $wpdb->get_results($sql) or die(mysql_error());
foreach($result as $results) {
$results->salt;
$results->password;
}
echo $sal->$results[0];
echo $pwd->$results[1];
Use Sql Query in Wordpress as below.
global $wpdb;
$results = $wpdb->get_results ( "SELECT * FROM TABLE" );
foreach ($results as $result)
{
$getdata[] = $result->$VALUE;
}
var_dump($getdata);