I have problem fetching my result from db and convert to json. In my API call, It gives me empty content(total blank) of returned body with status 200.
This is my code:
$weekAndYear = $year."/".$week; // incoming params as e.g "2016/19"
$stmt = $this->db->prepare("SELECT r.*, p.code FROM report r, product p WHERE "
. "r.pid=p.pid AND r.product=:productCode "
. "AND r.status='Published' AND r.pid=25 AND r.week=:weekAndYear");
$stmt->bindparam(":productCode", $productCode);
$stmt->bindparam(":weekAndYear", $weekAndYear);
$stmt->execute();
while($price=$stmt->fetch(PDO::FETCH_ASSOC)) {
//echo $price;
$arr_price[] = $price;
}
$data['priceReport'] = $arr_price;
//echo $weekAndYear;
$data['status'] = "OK";
return json_encode($data);
When I tested the query in my phpmyadmin mysql server and it works fine.
On my php side, different $weekAndYear params will have some working well and some are not. Anything wrong on array part?
My API response headers:
Cache-Control →no-store, no-cache, must-revalidate, post-check=0, pre-
check=0
Connection →Keep-Alive
Content-Length →0
Content-Type →application/json
Date →Thu, 05 May 2016 06:49:28 GMT
Expires →Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive →timeout=5, max=100
Pragma →no-cache
Server →Apache/2.4.18 (Unix) LibreSSL/2.2.6 PHP/5.5.31
X-Powered-By →PHP/5.5.31
I've been scratching my head for few days and now I just have few hairs left.
Please help. Thank you.
I'm assuming (maybe wrongly) that your code snippet isn't a function.
Change the last line from return to echo as follows:
echo json_encode($data);
Unless the first code snippet is a function, you need to use json_encode not a return statement.
What happens is that Fetch can fetch any type of content, even HTML. What PHP does is it generates content writes it to a file and sends it to the browser. When you generate HTML with PHP you do not return it, you echo it to the page.
The same thing happens with AJAX. You use PHP to write data to a file and serve it.
So replace this:
return json_encode($data);
with this:
echo json_encode($data);
Related
OMG I AM SOO SORRY I HAVE WRONG CODE TYPE :D HERE IS AN EDIT
OK I somehow figured out how to import UTF8 characters in MYSQL but when I load them they are not UTF8. And YES I have
<meta charset="UTF-8"/>
Look At this http://prntscr.com/b13xel . First post is OK but its not UTF8 it is from normal chars latin i think. But 2ND post isnt working :/ I have stored with UTF8 Charset in mysql http://prntscr.com/b13y2n (2ND is Test and Test2 if you dont get it xD) . I think I spelled it wrong xD but NVM I think you will understand me.
This is the code:
<div class = "tablatekst">
<?php
$novostid = 1;
while($novostid < 500)
{
$sqlnovosti = mysql_query("SELECT * FROM novosti WHERE ID = $novostid");
if(mysql_num_rows($sqlnovosti) > 0)
{
while($red = mysql_fetch_assoc($sqlnovosti))
{
$nnaslov = $red['Naslov'];
$ntekst = $red['Tekst'];
}
echo "<h2> $nnaslov </h2>";
echo $ntekst;
echo "<br><hr><br>";
}
$novostid = $novostid + 1;
}
?>
</div>
Put this before your while:
mysql_query('SET NAMES utf8');
However, I strongly recommend you to migrate to mysqli
What are the content-type headers set to in your PHP script?
https://stackoverflow.com/a/4279294/6275228
Use header to modify the HTTP header:
header('Content-Type: text/html; charset=utf-8');
Note to call this function before any output has been sent to the
client. Otherwise the header has been sent too and you obviously can’t
change it any more. You can check that with
headers_sent. See the manual page of
header for more information.
I need to create and delete cookies.
The issue is that I can create, then delete cookie, but after previously deleted cookie I am not able to create a new one. Why?
It works once more after I clear the cache of the browser.
Creating cookie and redirecting to test page:
<?php
$cookie_name = 'name';
$cookie_time = 2000000000;
$cookie_path = '/';
$cookie_value = uniqid();
setcookie($cookie_name, $cookie_value, $cookie_time, $cookie_path);
echo '<script> window.location.assign("test.php"); </script>';
?>
Deleting a cookie and redirecting to test page:
<?php
$cookie_name = 'name';
$cookie_path = '/';
setcookie($cookie_name, '', time() - 3600, $cookie_path);
echo '<script> window.location.assign("test.php"); </script>';
?>
The test page just has print_r($_COOKIE); in it.
What am I doing wrong here? Is the name of the cookie an issue? Is it browsers limitation?
I need to be able to create and delete the cookie whenever I need to.
I tried to avoid the cache by using this code:
<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
The problem may be the browser is caching the page request independently of what the server is telling it to do.
There is a simple trick to get around this. Adding a changing variable to the query string will make the page request unique each time. This will also force the browser to re-load the page even when cached.
For example, add the following to the address bar / page request:
?abc=123
And change the number value each time. Alternatively you can even use a timestamp like so:
?<timestamp>
This will force a standards compliant browser to fetch the page each time.
I'm setting a cookie on one page and trying to unset on the next page, which I reach via a link. However, the cookie only gets unset when I refresh the second page, F5.
For testing, I have the link and some cookie setting on the first page like this:
<?php
include("connect-db.php");
$id = "newuser";
setcookie("user_id", $id, time() + 31536000);
if (isset($_COOKIE["user_id"]))
echo "Welcome " . $_COOKIE["user_id"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
<br>
<a href='next.php'>Next</a>
On the next page I have this php code:
<?php
header("Cache-Control: no-cache, must-revalidate, max-age=0"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header('Pragma: no-cache');
setcookie("user_id", "", time()-(60*60*24), "/");
echo "<br /> Welcome " . $_COOKIE["user_id"] . "!<br>";
?>
How can I make sure the cookie is unset on the second page, or the page is fetched anew?
This depends on what you are trying to do. If you have a dependency on the cookie on the client, then you may want to unset it using the client (JavaScript). If the dependency is on the server, then it'd be tough to know what your problem is since you can just write the second part of the code to not depend on the cookie after you "unset" it.
I don't fully recommend this as it's an extra page load that's probably not necessary, but you could also force the sending of headers.
if (isset($_COOKIE['user_id'])) {
setcookie(/* your params */);
header('Refresh: ' . $_SERVER['REQUEST_URI']);
exit;
}
you can try using the following code in second page
setcookie("user_id", "");
I hope you can solve your problem.
I'm trying to make a PHP script that sets cookies to the browser by reading them from a file first. In the file is the piece of HTTP header "Cookie: x=foo; y=bar; etc". The script does a cleanup of the string so we end up with only the variable name (x) and the value of the variable (foo). The problem is when I set the cookies from the file, using Wireshark I see the exact values of the variables being sent to the broser. When I see what cookies the browser sends to the page, they are different, i.e I set cookie x=foo;, then the browser sends it back to the page as Cookie: x=bar. Do you know what may be causing this? When I use the Greasemonkey script for injecting cookies everything works fine tough.
Here is my code:
<?php
function inject($what)
{
for($i=0;$i<count($what);$i++)
{
$name = $what[$i][0];
echo "injecting cookie named \"$name\" .... <br> ";
setrawcookie($what[$i][0], $what[$i][1]);
}
echo 'all cookies injected properly, ready';
}
$newcook=file("/home/todor/cook.txt");
echo '<pre>';
for ($i=0; $i<count($newcook); $i++)
$newcook[$i] = str_replace('Cookie: ', '', $newcook[$i]);
$newcook = explode('; ', $newcook[0]);
for($i=0;$i<count($newcook);$i++)
$newcook[$i] = explode('=', $newcook[$i]);
for($i=0;$i<count($newcook);$i++)
echo 'cookie variable name "'.$newcook[$i][0].'" with value of "'.$newcook[$i][1].'"<br>';
echo '</pre>';
inject($newcook);
?>
---------------Cookies being set----------------------
Set-Cookie: MoodleSession=h0j51hvrkvu30mdeu3d9321thit8c8pdkle66llr2lipj80chjb0
Set-Cookie: __utma=16796069.1074685784.1352477410.1352477410.1352477410.1
Set-Cookie: __utmc=16796069
Set-Cookie: __utmz=16796069.1352477410.1.1.utmcsr
---------------Cookies being sent to the server -----------
Cookie: MoodleSession=hn92mn8vhl6kvg7f8qogpgm8reeisnoope27o7q3ivrecnr84gb1; __utma=16796069.1720416199.1352484234.1352484234.1352484234.1; __utmb=16796069.1.10.1352484234; __utmc=16796069; __utmz=16796069.1352484234.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
I have the following code in index.php (simplified):
<?php
print_r($_GET);
if ($_GET['f'] == "activate") {
//do stuff
}
if ($_GET['f'] == "disable") {
//do stuff
}
?>
and further down the page, some HTML:
<tr>
<td style='font-size: 0.9em;'>email#address.ac.uk</td>
<td style='font-size: 0.75em;'><span style="color: #00AF28;">Active</span></td><td style='font-size: 0.75em;'>Disable</td>
</tr>
The two hyperlinks will point the browser to the URL index.php?f=disable&id=email#address.ac.uk and index.php?f=disable&id=email#address.ac.uk, respectively.
Upon clicking the hyperlink (and directing the browser to index.php?f=disable&id=email#address.ac.uk), the result of print_r($_GET) is:
Array ( [f] => disable [id] => email#address.ac.uk )
However, the 'if' statement:
if ($_GET['f'] == "disable") {
//do stuff
}
Does not execute until I refresh the page, or press the enter key on the address bar.
I'm using Chrome 16 on OSX for this, with PHP5.
Many thanks
Try to disable the cache. You can do this by sending some http headers to the browser. Here are an example from php.net
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>