Illegal offset with simple mysqli read query - php

This is driving me crazy. The page I'm trying to create is to read from a mysql DB and then create a JSON object to return to an Angular app. Please bear with the inserted code blocks, it's all pertinent.
The overall question is this: Why am I getting the offset warnings for 'definition' and 'type' from the $term array, but not the others?
$definition = $term['definition']; (line 31)
$type = $term['type']; (line 33)
I did notice that each time it loops through the array, the values it outputs for both definition and type are the first letter of the term. So if the term is "Third Party Charges", then the definition and type both still get warnings but are assigned the value equal to left($term, 1).
Since there is a lot down there, specifically these two lines cause the warnings:
But these work fine:
$caseName = $term['caseName'];
$caseNumber = $term['caseNumber'];
$term = $term['term'];
Thanks for all help. I'm sure it being so late/early has something to do with this not making sense to me.
Here is the PHP:
$mysqli = new mysqli("localhost", "user", "pw", "db")
or die('Error connecting to the db.');
//Check for connection to database
if ($mysqli->errno) {
printf("Unable to conect to the database: %s" ,$mysqli->error);
exit();
}
$query = "Select dd.caseName, dd.caseNumber, dd.term, dd.definition, dd.type
From `ddMain` dd";
$termlist = $mysqli->query($query, MYSQLI_STORE_RESULT)
or die("Uh oh.");
while($term = $termlist->fetch_array(MYSQL_ASSOC)) {
echo "<pre>";
var_dump($term);
echo "</pre>";
$caseName = $term['caseName'];
echo "CaseName: " . $caseName . "<br />";
$caseNumber = $term['caseNumber'];
echo "CaseNumber: " . $caseNumber . "<br />";
$term = $term['term'];
echo "Term: " . $term . "<br />";
$definition = $term['definition'];
echo "Definition: " . $definition . "<br />";
$type = $term['type'];
echo "Type: " . $type . "<br />";
printf("Nm: %s, #: %s, term: %s, def: %s, type: %s", $caseName, $caseNumber, $term, $definition, $type);
}
Here is the output from the var_dump of $term:
array(5) {
["caseName"]=>
string(10) "Case name here"
["caseNumber"]=>
string(6) "123456"
["term"]=>
string(13) "Doughnut Hole"
["definition"]=>
string(168) "Some text here."
["type"]=>
string(8) "Business"
}
And finally the output of the loop up there:
CaseName: Case name here
CaseNumber: 123456
Term: Doughnut Hole
Warning: Illegal string offset 'definition' in C:\xampp\htdocs\path\file.php on line 31
Definition: D
Warning: Illegal string offset 'type' in C:\xampp\htdocs\path\file.php on line 33
Type: D
Nm: Case name here, #: 123456, term: Doughnut Hole, def: D, type: D

$term = $term['term'];
It's because that particular line is changing $term to something other than the database row. You're using $term for both the returned array from the database and one of the values extracted from it. Use a different name for one of them and your problem will be solved.
One possibility is to change:
$term = $term['term'];
echo "Term: " . $term . "<br />";
to something like:
$term2 = $term['term'];
echo "Term: " . $term2 . "<br />";

Related

Grab text from multiple parts of a string which differs in size and convert them into variables

I'm trying to grab specific parts of a string to convert them into variables. I was able to use str_replace() to get the output I wanted but since it changes in length especially file paths it just wont cut it.
STRING TEMPLATE:
$issue->fields->description = "MSI: YES XPF: NO PKG TYPE: XYZ VENDOR: WXYZ USER CODE: AB APP NAME: ATBTOOL VERSION: 1.0 MEDIA ZIP FILE: \\123.456.78.9\Path\TO\MY\MSI\MSIHelpV1.0.zip INSTALL DIR: G:\MSI EXISTING: NO";
This template always stays the same and when this array is dumped there is always a space around the values. The values im trying to grab are:
YES
NO
XYZ
WXYZ
AB
ATBTOOL
1.0
\123.456.78.9\Path\TO\MY\MSI\MSIHelpV1.0.zip
G:\MSI
NO
So i'm wondering if there is any to maybe specify to grab everything inbetween MSI: & XPF:, PKG TYPE: & VENDOR:, and so forth just a thought any help would be appreciated!
This is the code I've been working with.
$stringPosPKG = strpos($issue->fields->description, 'TYPE');
$stringPosVENDOR = strpos($issue->fields->description, 'VENDOR');
$stringPosCODE = strpos($issue->fields->description, 'CODE');
$stringPosAPP = strpos($issue->fields->description, 'APP');
$stringPosVERSION = strpos($issue->fields->description, 'VERSION');
echo "</br>";
echo "PKG Begins At " . $stringPosPKG;
echo "</br>";
echo "VENDOR Begins At " . $stringPosVENDOR;
echo "</br>";
echo "CODE Begins At " . $stringPosCODE;
echo "</br>";
echo "APP NAME Begins At " . $stringPosAPP;
echo "</br>";
echo "VERSION Begins At " . $stringPosVERSION;
echo "</br>";
echo "</br>";
$pkgType = substr( $issue->fields->description, 33, -217 );
$vendorName = substr( $issue->fields->description, 48, -203 );
$userCODE = substr( $issue->fields->description, 67, -184 );
$appName = substr( $issue->fields->description, 83, -163 );
$versionNum = substr( $issue->fields->description, 103, -147 );
echo "</br>";
echo "PKG Title: " . $pkgType;
echo "</br>";
echo "VENDOR Title: " . $vendorName;
echo "</br>";
echo "CODE CODE: " . $userCODE;
echo "</br>";
echo "APP NAME: " . $appName;
echo "</br>";
echo "VERSION: " . $versionNum;
echo "</br>";
$versionNumStrRArray = ["."];
$versionNumStrR = str_replace($versionNumStrRArray, "_", $versionNum);
echo "MSI NAME: MSI_" . $pkgType . "_" . $vendorName . "_" . $userCODE . "_" . $appName . "_" . "$versionNumStrR";
OUTPUT:
PKG Begins At 27
VENDOR Begins At 40
CODE Begins At 61
APP NAME Begins At 73
VERSION Begins At 94
PKG Title: ABC
VENDOR Title: WXYZ
CODE CODE: AB
APP NAME: ATBTOOL
VERSION: 1.0
MSI NAME: MSI_ABC_WXYZ_AB_ATBTOOL_1_0
Guess you should be using regular expressions for this one. Something like that:
<?php
function parseFoo(string $foo): array
{
$splitInput = [];
preg_match_all(
'/(?<key>[^\s][A-Z\s]+): (?<value>[\pL\pP\d]+)/',
$foo,
$splitInput
);
return array_combine(
$splitInput['key'] ?? [],
$splitInput['value'] ?? []
);
};
$input = "MSI: YES XPF: NO PKG TYPE: XYZ VENDOR: WXYZ USER CODE: AB APP NAME: ATBTOOL VERSION: 1.0 MEDIA ZIP FILE: \\123.456.78.9\Path\TO\MY\MSI\MSIHelpV1.0.zip INSTALL DIR: G:\MSI EXISTING: NO";
echo json_encode(
parseFoo($input)
);

Get latest Tweets - What API

I know this has been discussed a lot here, but I still don't seem able to find aworking solution. Either it's out of date, it's the wrong programming-language or it's no longer supported.
All I want to do is: Get the last 'n' tweets from a public Twitter profile using PHP/JavaScript.
What API should I use best?
How do I keep it as lightweight as possible?
I can't use Node. js
I tried this, but I can't seem to get it to work, as simple as it may look like.
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1
I've already registered for a developer account and created a "Twitter-App".
You can use this API, which I have used once and it works perfectly.
Download the file TwitterApiExchange.php from the repository above and you may use the following sample code to fetch tweets of a user:
<?php
echo '<pre>';
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$user = "rootcss";
$count = 100;
if (isset($_GET['user'])) {
$user = $_GET['user'];
}
if (isset($_GET['count'])) {
$count = $_GET['count'];
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest(), $assoc = TRUE);
if (isset($string["errors"][0]["message"])) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>" . $string['errors'][0]["message"] . "</em></p>";
exit();
}
foreach ($string as $items) {
echo "Time and Date of Tweet: " . $items['created_at'] . "<br />";
echo "Tweet: " . $items['text'] . "<br />";
echo "Tweeted by: " . $items['user']['name'] . "<br />";
echo "Screen name: " . $items['user']['screen_name'] . "<br />";
echo "Followers: " . $items['user']['followers_count'] . "<br />";
echo "Friends: " . $items['user']['friends_count'] . "<br />";
echo "Listed: " . $items['user']['listed_count'] . "<br /><hr />";
}
echo '</pre>';
?>
It worked perfectly for me, Let me know if you face any issues.

How to get a value from wunderground .json

I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632

Echo in one line in PHP

I want to change the original code I have,
echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (";
echo metersToFeetInches($productarea) . " ft²)" . "</p>";
into a single echo line as shown here:
echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (" . metersToFeetInches($productarea) . " ft²)" . "</p>";
But I'm getting some strange line breaks in this second case for metersToFeetInches($productarea).
Generated HTML:
24,757
<p>
<strong>Area:</strong>
2,300 m² ( ft²)
</p>
Output:
24,757
Area:
2,300 m² ( ft²)
How can I solve it? Is there any documentation I could read to learn how to do it by myself in the future?
I'm pretty sure I know what's going on here, your function metersToFeetInches is echoing a value rather than returning it.
function metersToFeetInches() {
echo 'OUTPUT';
}
echo 'FIRST '.metersToFeetInches().' LAST';
// Outputs: OUTPUTFIRST LAST
echo metersToFeetInches() is actually redundant.
This is because the function runs before the string you built is actually output. Note that both examples you posted would have this problem. Change your function to return a value instead. Afterwards, any places where you have used it like so:
echo 'Something';
metersToFeetInches();
echo 'Something Else';
You'll have to use an echo:
echo 'Something';
echo metersToFeetInches();
echo 'Something Else';
Functions should pretty much always return a value. Lesson learned, perhaps?
If you are really in a bind and cannot change the function, you'll have to resort to output buffering:
ob_start();
metersToFeetInches($productarea);
$metersToFeetInches = ob_get_clean();
echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (" . $metersToFeetInches . " ft²)" . "</p>";
...which is rather silly to have to do.

PHP: $_POST["startId$i"]) != ""

I am trying to process a form that is dynamically created and therefore varies in length. The while loop seems to work fine. However, the 'if' statement is not; it should only print the startId$i and corId$i if and only if the form's particular text field was filled in. The code is printing a line for every text field on the form, regardless of if it was left empty or not.
$i = 0;
while(!is_null($_POST["startId$i"])){
if(($_POST["startId$i"]) != ""){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
$i = 0;
while(isset($_POST["startId$i"])){
if( !empty($_POST["startId$i"]) ){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
Can you manage with fields names ?
If yes, better way is to name inputs with name="startId[0]" and name="corId[0]" and so on...
Then in PHP you just do:
$startIds = $_POST['startId'];
$corIds = $_POST['corId'];
foreach ( $startIds as $k => $startId ) {
if ( !empty($startId) ) {
$corId = $corIds[$k];
echo "startId: " . $startId . " ---<br>";
echo "corId: " . $corId . " ---<br>";
}
}
You should use empty() in this case:
if(!empty($_POST["startId$i"])) {
...
}
I suggest to check the real content of $_POST. You can do that via var_dump($_POST);
You may find out, for example, that the empty fields contain whitespaces. In that case the trim() function may help.
For example:
while(isset($_POST["startId$i"])){
if(trim($_POST["startId$i"])){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}

Categories