Throught an AJAX call I want to pick some data from DB and send back to client.
$result is return value of SELECT QUERY
Case1:This works fine
$str = "[";
while($row = mysqli_fetch_assoc($result)) {
$str = $str ."{".
'"Name":'. '"'. $row["Name"] . '"'
. "},";
}
}
$str = $str . "]";
echo str;
CASE2:This works fine too:
$str = "[";
while($row = mysqli_fetch_assoc($result)) {
$str = $str ."{".
'"ID":'. '"'. $row["ID"] //SEE HERE
. "},";
}
} else {
echo "0 results";
}
$str = $str . "]";
echo $str;
CASE3: BUT FOLLOWING GIVES error with 500()
$str = "[";
while($row = mysqli_fetch_assoc($result)) {
$str = $str ."{".
'"ID":'. '"'. $row["ID"] . '",' //SEE HERE
'"Name":'. '"'. $row["Name"] . '"'
. "},";
}
} else {
echo "0 results";
}
$str = $str . "]";
echo $str;
I want to send echo str after making it in JSON format and parse it at client side using `JSON.parse(). Case1 and 2 work fine when I have only one key-value pair. But as soon as I put 2 key-value pairs I get error:
POST https://******************.php 500 ()
You really need to use the appropriate functions.
Get into good programming habits.
$rtn = []; //create array
while($row = mysqli_fetch_assoc($result)){
//push result into array
$rtn[] = ['ID'=> $row["ID"], 'Name'=> $row['Name']];
}
if($rtn)//if array has entries
echo json_encode($rtn);//encodes result to json
else
echo "0 results";
It return 500, because you have error in your script. You can add below code and check where is the mistake.
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
Probably in your code is missing dot. Check this:
$str = $str . "{" .
'"ID":' . '"' . $row["ID"] . '",' .
'"Name":' . '"' . $row["Name"] . '"'
. "},";
Related
I have the following attempt at my function, but it's just printing out everything in the contacts.txt file on one line...
function contactsTable(){
$file = fopen("contacts.txt", "r") or die("Unable to open file!");
echo "<tr><th>";
while (!feof($file)){
echo "<tr><th>";
$data = fgets($file);
echo "<tr><td>" . str_replace(',','</td><td>',$data) . '</td></tr>';
}
echo "<tr><th>";
echo '</table>';
fclose($file);
}
contacts.txt example like this;
Row 1 is headers ---> [value1, value2, value3, value4]
Row 2 is data ---> [value5, value6, value7, value8]
Is it possible to change my function so that Row 1 is using <th> tags so they are formatted as headers and the rest of the rows go into <td> tags for table data? I've tried to amend the logic but can't seem to get it.
TIA
Here is your contactsTable() function that prints the first contacts.txt line as table header and some basic HTML formatting for easy reading/debugging.
function contactsTable() {
$file = fopen('contacts.txt', 'r') or die('Unable to open file!');
$row = 0;
echo '<table>' . PHP_EOL;
while (!feof($file)) {
$row++;
$data = fgets($file);
if ($row === 1) {
echo '<tr>' . PHP_EOL;
echo '<th>' . str_replace(',', '</th><th>', $data) . '</th>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
} else {
echo '<tr>' . PHP_EOL;
echo '<td>' . str_replace(',', '</td><td>', $data) . '</td>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
}
}
echo '</table>' . PHP_EOL;
fclose($file);
}
I am trying to compare two strings. When compared they are unequal to the computer. But to the human eye the strings appear to be the same.
When I run a test to check the bin2hex with php they are clearly unequal. Some how a set of double quotes is be read as html. Here are some examples:
$string1 = strlen(html_entity_decode($_SESSION['pageTitleArray'][$b]));
$string2 = strlen(html_entity_decode($value));
echo 'Checking: ' . $_SESSION['pageTitleArray'][$b] . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'testing ' . $string1 . " = "bin2hex($string1) . " " . bin2hex($string2);
echo '<br>';
echo 'With: ' . $value . " " . bin2hex($value);
The code above will out put the following information.
Checking: 1 PAIR OF BBC HEAD GASKET GASKETS MULTI LAYERED STEEL 4.585"
312050414952204f46204242432048454144204741534b4554204741534b455453204d554c5449204c41594552454420535445454c20342e35383522
testing 3630 3632 With: 1 PAIR OF BBC HEAD GASKET GASKETS MULTI
LAYERED STEEL 4.585″
312050414952204f46204242432048454144204741534b4554204741534b455453204d554c5449204c41594552454420535445454c20342e3538352623383234333b
false
I am kinda lost on what to do... Any help would be greatly appreciated. Below is the rest of the code so you can get a total feel for what I'm trying to accomplish.
for($b = 0; $b < count($_SESSION['pageTitleArray']); $b++)
{
foreach($_SESSION['pushIdArrayQuery'] as $key => $value)
{
$string1 = strlen(html_entity_decode($_SESSION['pageTitleArray'][$b]));
$string2 = strlen(html_entity_decode($value));
echo 'Checking: ' . $_SESSION['pageTitleArray'][$b] . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'testing ' . $string1 . " = "bin2hex($string1) . " " . bin2hex($string2);
echo '<br>';
echo 'With: ' . $value . " " . bin2hex($value);
if(trim($_SESSION['pageTitleArray'][$b]) == trim($value))
{
echo '<br>';
echo '<h1>Success</h1>';
echo '<br>';
echo '<b>Key: </b>' . $key;
echo '<br>';
echo 'Page Id: ' . $_SESSION['pushTitleArrayQuery'][$key];
echo '<br> ';
}
else {
echo '<br>';
echo 'false';
echo '<br>';
}
}
}
You have two different types of quotations mark (" on the first string and ″ on the second one).
To human eyes they seems similar but they are complete different characters to PHP.
This is how I fixed the problem. Notice, I removed any html attributes with the html_entity_decode() function. Then, from there I was able to strip away all other special characters by using preg_replace() and compare the results.
//Loop through all the page titles from the directories
for($b = 0; $b < count($_SESSION['pageTitleArray']); $b++)
{
//Loop through the page titles gathered from the database
foreach($_SESSION['pushTitleArrayQuery'] as $key => $value)
{
//use html decode to remove the quotes with ENT_NOQUOTES
$removeHtml = html_entity_decode($value, ENT_NOQUOTES);
//Test to make sure the encoding are the same for both variables.
$detectEncoding = mb_detect_encoding($value, "auto");
//remove all non alphanumeric variables in the first string.
$string1 = preg_replace("/[^a-zA-Z0-9]/", "", $_SESSION['pageTitleArray'][$b]);
//remove all non alphanumeric variables in the second string.
$string2 = preg_replace("/[^a-zA-Z0-9]/", "", $removeHtml);
//Print out to see what the results look like from decode and encoding functions
echo 'Testing the removal of html quotes: ' . $removeHtml . ' Encoding: ' . $detectEncoding;
echo '<br>';
//Show what variables are being compaired.
echo 'Checking: ' . $string1 . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'With: ' . $string2 . " " . bin2hex($value);
//If statement to check if the to strings match.
if(trim($string1) === trim($string2))
{
echo '<br>';
echo '<h1>Success</h1>';
echo '<br>';
echo '<b>Key: </b>' . $key;
echo '<br>';
echo 'Page Title: ' . $_SESSION['pushTitleArrayQuery'][$key];
echo '<br>';
echo 'Page Id: ' . $_SESSION['pushIdArrayQuery'][$key];
echo '<br> ';
}
else {
echo '<br>';
echo 'false';
echo '<br>';
}
echo '<br>';
}
}
I am trying to display each item in a JSON array of reviews. There are two reviews in the array, but instead of displaying both of them, this code displays same one twice.
Why is this happening?
$response = curl_exec($curl);
$data = json_decode($response, true);
// Setup the Review for posting to the Mysql Database
// Loop through Reviews
for ($i=0; $i<count($data['reviews']); $i++) {
$id = $data['reviews']['0']['id']; // good
$stars = $data['reviews']['0']['stars']; //good
$title = $data['reviews']['0']['title'];
$text = $data['reviews']['0']['text'];
$createdAt = $data['reviews']['0']['createdAt'];
$companyReply = $data['reviews']['0']['companyReply']['text'];
$companyReplyDate = $data['reviews']['0']['companyReply']['createdAt'];
// Do Mysql insert for each row
// show this
echo "id: " . $id . "</br>";
echo "stars: " . $stars . "</br>";
echo "title: " . $title . "</br>";
echo "text: " . $text . "</br>";
echo "Created: " . $createdAt . "</br>";
echo "Reply: " . $companyReply . "</br>";
echo "Reply Date: " . $companyReplyDate . "</br> </br>";
}
curl_close($curl);
It is because you aren't actually using your loop increment variable to get different array keys. You're just selecting the ['0'] index repeatedly. Instead, use $i as the array key like this:
for ($i=0; $i<count($data['reviews']); $i++) {
$id = $data['reviews'][$i]['id']; // good
$stars = $data['reviews'][$i]['stars']; //good
$title = $data['reviews'][$i]['title'];
$text = $data['reviews'][$i]['text'];
$createdAt = $data['reviews'][$i]['createdAt'];
$companyReply = $data['reviews'][$i]['companyReply']['text'];
$companyReplyDate = $data['reviews'][$i]['companyReply']['createdAt'];
// ... etc.
I'm trying to show a list of all nearby weather stations.
I have the code:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string);
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (count($station) > 1)
{
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
}
}
But currently it's not showing anything, i have searched for examples but i couldn't find any solution fot this problem.
Alternatively, you could use a simple foreach to iterate those values. Consider this example:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array
$desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station'];
foreach($desired_values as $key => $value) {
echo "<hr/>";
echo "City: " . $value['city'] . "<br/>";
echo "State: " . $value['state'] . "<br/>";
echo "Latitude: " . $value['lat'] . "<br/>";
echo "Longitude: " . $value['lon'] . "<br/>";
echo "<hr/>";
}
Sample Fiddle
I have a PHP while LOOP, and I want to remove last comma , from echo '],'; if it is last loop
while($ltr = mysql_fetch_array($lt)){
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo '],';
}
Create an array with the elements as you go along so that they look like array = ([ELEMENT INFO], [ELEMENT INFO], [ELEMENT INFO]) and then implode the array with a comma.
$str = '';
while($ltr = mysql_fetch_array($lt)){
$str .= '[';
$str .= $ltr['days']. ' ,'. $ltr['name'];
$str .= '],';
}
echo rtrim($str, ",");
this will remove the last , from string
I think the systemic solution is following:
$separator = '';
while($ltr = mysql_fetch_array($lt)){
echo $separator;
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if (!$separator) $separator = ', ';
}
No call for count(), no additional iteration of implode(), no additional string operations, ready for any (unpredictable) number of results.
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(!count($result)-1 == $i){
echo ',';
}
}
Check how many entries you have, make a "Counter" and a condition to only put the comma when its not the last loop.
$arr = array();
while($ltr = mysql_fetch_array($lt)){
$arr[] = '[' . $ltr['days'] . ' ,' . $ltr['name'] . ']';
}
echo implode(',', $arr);
$res_array = array();
while($ltr = mysql_fetch_array($lt)){
$res_array[] = '['.$ltr['days']. ' ,'. $ltr['name'].']';
}
$str = implode(",",$res_array);
echo $str;
Save the response as a var instead of echoing it and then remove the final character at the end using substr.
$response = "";
while($ltr = mysql_fetch_array($lt)){
$response .= '[';
$response .= $ltr['days']. ' ,'. $ltr['name'];
$response .= '],';
}
echo substr($response, 0, -1);
//this one works
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(count($result)-1 != $i){
echo ',';
}
}