So i am very new to php and having problem with my array.
"Basically I have an array with 5 fields.
Now the data is partially in latin1-german. But this let's the php output "null". How do I decode the array, that makes the php return the right text?"
edit:
So I altered the code (JSON_PRETTY_PRINT made it return nothing).
But the problem still remains. The special characters like "ä" and "ü" still make it return ":null".
// get all products from products table
$result = mysql_query("SELECT *FROM silberhell_app") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["kategorie"] = $row["kategorie"];
$product["beschreibung"] = $row["beschreibung"];
$product["bild"] = $row["bild"];
$product["preis"] = $row["preis"];
array_map($product, "utf8_encode"); // encode array values
$products[] = $product; // insert product into array
}
$data = array(
//'success' => 1,
'products' => $products
);
}
echo json_encode($data); // make it slightly more readable
?>
Slightly cleaned up, should work now:
$products = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["pid"] = $row["pid"];
[...]
array_map("utf8_encode", $product); // encode array values
$products[] = $product; // insert product into array
}
$data = array(
'success' => 1,
'products' => $products
);
echo json_encode($data, JSON_PRETTY_PRINT); // make it slightly more readable
Related
date_default_timezone_set('Asia/Kolkata');
header('Access-Control-Allow-Origin: *');
include_once('conn.php');
$data2 = array();
$content = trim(file_get_contents("php://input"));
$data = json_decode($content);
$couplenumber = $data->contact_number;
$sql = "SELECT * from `users_table` where `phone` IN '$couplenumber'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($data2, $row);
}
echo json_encode($data2);
} else {
echo 0;
}
$conn->close();
$couplenumber is an array it has multiple contact numbers. I want to match my array value to the table column named the phone. The phone has a string value that means a single contact. How I can get data after match phone value to multiple contacts of $couplenumber value?
It will be better, if you show us your arrays content. But, if you have some things like one objects array and one array with ids only, let's try it:
//Arrays are like :
$tab1 = [3,4];
//Considering Object is a class which receive id in constrictor and has et getId method.
$obj1 = new Object(1);
$obj2 = new Object(2);
$items = [$obj1, $obj2];
$tab2 = [];
foreach ($items as $item) {
$tab2[] = $item->getId();
}
$diff = array_merge(array_diff($tab1, $tab2), array_diff($tab2, $tab1));
// True there are same, false there differents.
var_dump( empty($diff) && (count($tab1) === count($tab2)) );
I've been trying to return results from 2 queries as json. var_dump($data) works but can't json_encode returns empty/ not working.
$data = array();
$array_articles = array();
$sql_articles = $mysqli->query("select something something");
while ( $article = $sql_articles->fetch_assoc() ){
$array_articles[] = $article;
}
$array_posts = array();
$sql_posts = $mysqli->query("select something something");
while ( $post = $sql_posts->fetch_assoc() ){
$array_posts[] = $post;
}
$data = array(
'top_articles' => $array_articles,
'top_posts' => $array_posts
);
echo json_encode( $data );
All the things you put in json_encode must be UTF8. I think some of the content is not UTF-8 encoded.
You can add extra parameters to json_encode.
You could give it a try like this:
echo json_encode($data, JSON_INVALID_UTF8_IGNORE | JSON_PARTIAL_OUTPUT_ON_ERROR)
function practise()
{
$this->load->database();
$qry = mysql_query("select * from demmo");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$created = $row['created'];
//from here
$qry = mysql_query("select * from demmo where created = '$created'");
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
$users[] = array('user_id' => $user_id, 'name' => $name);
}
$dotts[] = array('created' => $created2);
//till here
}
return array ($dotts,$users);
}
}
in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:
For example, to get all of the dates:
$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
array_push($dotts, $created2);
$users[] = array('user_id' => $user_id, 'name' => $name);
array_push($allusers, $users);
}
//
return array ($dotts,$allusers);
You need to create an array and use array_push function , then only it will have more than one value.
example:
create an empty array as
$allUser = array();
then after this line
$users[] = array('user_id' => $user_id, 'name' => $name);
use array_push as
array_push($allUser, $users);
}
return array($dots, $allUser);
I want to acheive something simliar to this adding elements onto an array but when I use this methods two nodes get created in the json element. I only want one node with all the entires within that also can you name nodes ie Properties.
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
Try this code array_push is better option here,
<?php
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$temp = array();
$temp = array('name' => $row['name'], 'id' => $row['id']);
array_push($json, $temp);
}
$custom = array('name'=>'foo', 'id' => 'bar');
array_push($json,$custom);
?>
I have a method of creating JSON into an array that looks like this:
[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]
I first tried getting the data from a html page (not the database) like this:
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);
for ($i=0; $i<count($images); $i++) {
$arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}
echo json_encode($arr);
Where each linkExtractor looks a bit like this - where it grabs all the text within a class videocode.
function linkExtractor6($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' videocode ')]") as $node)
$result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)
// Now return the array, rather than extracting keys from it
return $result;
}
I now want to do this instead with a database.
So I have tried to replace each linkExtractor with this - and obviously the connection:
function linkExtractor6($html){
$genre = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
foreach ($genre as $node)
$result[] = $node;
return $result;
}
But I am getting the error:
Invalid argument supplied for foreach()
Avoid redundancy and run a single SELECT
function create_json_db($con){
$result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
FROM entries
ORDER BY date DESC");
$items= array();
while ($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
return $items ;
}
Try to use this. More info in the official PHP documentation:
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$items = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = $row;
}
return $items;
}
First, you are not iterating through your results via something like mysqli_fetch_array. So here is the function with mysqli_fetch_array in place. But there is a much larger issue. Read on.
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Okay, with that done, it still won’t work. Why? Look at your function. Specifically this line:
$result = mysqli_query($con,"SELECT genre
But where is $con coming from? Without a database connection mysqli_query will not work at all. So if you somehow have $con set outside your function, you need to pass it into your function like this:
function linkExtractor6($con, $html){
So your full function would be:
function linkExtractor6($con, $html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Remember, functions are self-contained & isolated from whatever happens outside of them unless you explicitly pass data into them.