I am trying to retrieve the data from mySQL and generate as JSON file.
But the output is just showing only 1 row.
There are many rows inside the database table.
What is wrong with this code?
$sql = "SELECT * FROM form_element";
$result = mysqli_query($conn, $sql);
$response = array();
$data_array = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($data = mysqli_fetch_assoc($result)) {
$id = $data['id'];
$name = $data['name'];
$email = $data['email'];
$phone = $data['phone'];
$address = $data['address'];
$data_array = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address
);
}
} else {
echo "0 results";
}
$response['data_array'] = $data_array;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
You're overwriting $data_array every time in the loop.
So, this part:
$data_array = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address
);
should be changed to:
$data_array[] = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address
);
Then each row is added to the $data_array.
Related
I want to create json which contains all orders from datebase. I tried to write this code but it returns only one order.
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders =[
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
Now the response looks like this:
But I want like this:
Append to the $orders array:
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders[] =[ // <--- The difference
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
As per title described, i have following code to fetch data in the table using datatables server side processing, but end up has no result is return:
include(mysqli_db.php);
$request = $_REQUEST;
$col = array(
0 => 'id',
1 => 'name',
2 => 'phone',
3 => 'ic_pp_no',
4 => 'passport_no',
5 => 'email',
6 => 'address1',
7 => 'address2',
8 => 'country',
9 => 'pp_expiry_date',
10 => 'created_date'
);
$q = "SELECT * FROM account";
$sql = $mysqli->query($q);
$totalData = $sql->num_rows;
$totalFilter = $totalData;
$data = array();
while($row = $sql->fetch_object()){
$subdata = array();
$subdata[] = $row->name;
$subdata[] = $row->phone;
$subdata[] = $row->ic_pp_no.$row->passport_no;
$subdata[] = $row->email;
$subdata[] = $row->address1.$row->address2;
$subdata[] = $row->country;
$subdata[] = $row->id;
$data[] = $subdata;
}
$json_data = array(
'draw' => intval($request['draw']),
'recordsTotal' => intval($totalData),
'recordsFiltered' => intval($totalFilter),
'data' => $data
);
echo json_encode($json_data);
I can see json output with exact num rows return but no data:
{"draw":0,"recordsTotal":81,"recordsFiltered":81,"data":[]}
thanks.
I have created a PHP CSV parser. My customer uploads a csv file there with data of his customers, the csv is exploded into rows and further into cells.
Finally the cells are uploaded to corresponding MySQL database, sent via XML SoapCall to an external database and in the end echoed onto documents body with statuses of every row sent.
It works perfectly fine for up to 28 rows in CSV, but whenever there are more rows to be added a
500 Internal Error
The server encountered an internal error and could not complete your request.
pops in and would stop the update/soapcall/echo loop.
Any ideas what may this be caused by?
Memory cache limit is set to 256mb while max uploaded file size is 64mb, dont think any of those have been exceeded.
EDIT1:
It actually seems like the problem were spaces in some of the cells. Now however it would stop at row 28 and bring error 500 Internal Error
The server encountered an internal error and could not complete your request..
Any ideas?
EDIT2 code:
<?php
if (isset($_POST['submit'])) {
if (isset($_FILES["filetoparse"]['tmp_name'])) {
} else {
die("Błąd wgrywania pliku");
}
$file = file_get_contents($_FILES["filetoparse"]['tmp_name']);
if (isset($file)) {
} else {
die("Błąd odczytu pliku.");
}
function array_to_xml($array, &$xml) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml->addChild("$key",'','');
array_to_xml($value, $subnode);
} else {
array_to_xml($value, $xml);
}
} else {
$xml->addChild("$key","$value",'');
}
}
};
$echo = "";
$rows = explode("\n", $file);
array_shift($rows);
foreach($rows as $row => $data) {
$row_data = explode(';', $data);
$info[$row]['name'] = $row_data[0];
$info[$row]['city'] = $row_data[1];
$info[$row]['postalcode'] = $row_data[2];
$info[$row]['pesel'] = $row_data[3];
$info[$row]['phone'] = $row_data[4];
$info[$row]['amount'] = $row_data[5];
$info[$row]['sex'] = $row_data[6];
$name = $info[$row]['name'];
$city = $info[$row]['city'];
$postcode = $info[$row]['postalcode'];
$pesel = $info[$row]['pesel'];
$phone = $info[$row]['phone'];
$price = $info[$row]['amount'];
$xmlsex = $info[$row]['sex'];
$xmlsexx = preg_replace('/\s+/', '', $xmlsex);
$names = explode(' ', $name);
$firstname = $names[0];
$lastname = $names[1];
if (empty($pesel)) {
continue;
}
// Api Fines.pl module
$client = new SoapClient("SOME_API");
$contract = array(
'product' => array(
'prefix' => 'MOP',
),
'participants' => array(
'customers' => array(
'main_borrower' => array(
'personal_data' => array(
'pesel' => $pesel,
'firstname' => $firstname,
'lastname' => $lastname,
'sex' => $xmlsexx,
),
'contact_data' => array(
'addresses' => array(
'address' => array(
'type' => 'registered',
'street_name' => $city,
'block_number' => '1',
'flat_number' => '1',
'postal_code' => $postcode,
'city' => $city,
),
),
'phones_mobile' => array(
'phone_mobile' => array(
'type' => 'personal',
'number' => $phone,
),
),
),
'incomes' => array(
'income' => array(
'type' => 'employment',
'main_income' => 'true',
'fixed_term_contract' => 'false',
'paychecks' => array(
'paycheck' => array(
'amount_net' => array(
'amount' => $price,
'currency' => 'PLN',
),
'type' => 'base',
),
),
),
),
),
),
),
);
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\"?><sof:Contract xmlns:s=\"http://www.fines.pl/simple\" xmlns:sof=\"http://www.fines.pl/sof\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.fines.pl/sof model.xsd \"></sof:Contract>");
array_to_xml($contract, $xml);
$parameters = array(
'user_login' => 'XXX',
'user_password' => 'XXX',
'contract' => $xml->asXML(),
);
$response = $client->newApplication($parameters);
$responsearray = get_object_vars($response);
if ($response->success) {
$finesaccepted = "Tak - " . $response->number_sof;
} else {
$finesaccepted = "Nie - " . $response->messages->message->text;
}
$finesaccepted = str_replace("'", "", $finesaccepted);
//into database
$mysqli = new mysqli('XXX', 'XXX', 'XXX', 'XXX');
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("U");
if ($xmlsexx == 'male') {
$querysex = "Mężczyzna";
} else {
$querysex = "Kobieta";
}
$insertquery = "INSERT INTO x_form (ref_id, date, firstname, lastname, check_rules, ip_adres, email, phone, type, company, nip, postcode, city, amount, income, pesel, sex, isfb, finesaccepted) VALUES ('$date', '$date', '$firstname', '$lastname', '1', '$ip', 'brak', '$phone', '4', NULL, NULL, '$postcode', '$city', NULL, '$price', '$pesel', '$querysex', '2', '$finesaccepted')";
$echo .= $firstname . " " . $lastname . " - Dodano do bazy. Przyjęto w Fines: " . $finesaccepted . "<br>";
$mysqli->query($insertquery);
sleep(1);
}
}
?>
I try to make my custom code to update data to my custom database table
after I send the data I get:
Warning: mysqli_real_escape_string() expects parameter 2 to be string,
array given in .../wp-includes/wp-db.php on line 1156
My table structure is:
table name: wp_wlm_user_options
column names: ID, user_id, option_name, option_value
My code is:
if (isset($_POST['submit'])) {
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$meta = array();
foreach ($wlm_user_info as $key => $value) {
$get_meta = $value['option_name'];
array_push($meta, $get_meta);
}
//var_dump($meta);
$value = array(
'custom_firstname' => $_POST['first_name'],
'custom_lastname' => $_POST['last_name'],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender'],
'custom_landlinephone' => $_POST['landlinephone'],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array(
'%s',
'%s'
);
//print_r($meta,$value);
$data = array(
'user_id' => $user_id,
'option_name' => $meta,
'option_value' => maybe_serialize($value)
);
$format = array('%d','%s','%s');
$where = array(
'user_id' => $user_id,
'option_name' => $meta
);
$x = $wpdb->update($table, $data, $where, $format);
//$x = $wpdb->update($table, $data, $where);
if($x){
echo '<h1>data has been save</h1>' ;
}
Can anyone tell me what is wrong with this?
Due to your poor information we can only guess.
You might want something like this:
if (isset($_POST['submit']))
{
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$values = array(
'custom_firstname' => $_POST['first_name' ],
'custom_lastname' => $_POST['last_name' ],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender' ],
'custom_landlinephone' => $_POST['landlinephone' ],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array('%s');
$whereformat = array('%d','%s');
foreach($values as $key => $val)
{
$data = array(
'option_value' => maybe_serialize($val)
);
$where = array(
'user_id' => $user_id,
'option_name' => $key
);
$num_rows = $wpdb->update($table, $data, $where, $format, $whereformat);
if($num_rows !== false){
echo "<h1>$key has been saved</h1>" ;
}
}
};
The code above does multiple updates mapping the data to option_name and option_value for each update() invocation. You don't need to update fields of the WHERE clause with unchanged values.
You can find the official documentation on wordpress.org
I was searching for a solution for my problem.
I have the code below:
while($row = mysql_fetch_array($resultQuery)){
$response = array(
'name' => $row['name'],
'data' => $row['data']
);
$responses[] = $response;
}
echo json_encode($responses);
The code will bring this result:
[{"name":"Name001","data":"1"},
{"name":"Name001","data":"2"},
{"name":"Name001","data":"3"},
{"name":"Name002","data":"4"},
{"name":"Name002","data":"5"},
{"name":"Name002","data":"6"}]
But I would like to have the result below:
[{"name":"Name001","data":[1,2,3]},
{"name":"Name002","data":[4,5,5]}
Each "Name" has its own ID, I would like in the "while" put each id with its own data.
Thank you for your help.
1. Update:
$id_name = "xx";
while($row = mysql_fetch_array($resultQuery)){
if($id !== $row['id']){
$response = array(
'name' => $row['name'],
'data' => array($row['data'])
);
$responses[] = $response;
}
$id_name = $row['id'];
}
echo json_encode($responses);
I am trying to check the ID first and if is different will bring to me:
[{"name":"Name001","data":["1"]},{"name":"Name002","data":["4"]}]
while($row = mysql_fetch_array($resultQuery))
$tmp[$row['name']][] = $row['data'];
foreach($tmp as $key => $item)
$responses[] = array('name' => $key, 'data' => $item);
echo json_encode($responses);
result
[{"name":"Name001","data":["1","2","3"]},{"name":"Name002","data":["4","5","6"]}]
I made a test here, hope you like.
$arr = array();
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
echo json_encode($arr);
Output:
[{"name":"val","data":[1,2,3]},{"name":"val","data":[1,2,3]}]