My problem is in my code I'm having problems with it calculating something with a variable that does not exists some times and some times does.
I want it to give me back number of deaths if empty '0' if not prints me what is in the variable, but for some reason i get this:
E_NOTICE : type 8 -- Undefined property: stdClass::$numDeaths -- at
line 66 E_WARNING : type 2 -- Division by zero -- at line 71
here is my code:
<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'tamini';
$new = rawurlencode($summonerName);
$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);
// get the basic summoner info
$result = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id = $summoner->id;
// var_dump($summoner);
?>
<?php
$clawzz = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/' . $id . '/recent?api_key=' . $apiKey);
$gazazz = json_decode($clawzz);
?>
<?php
$entrieszz = $gazazz->games;
usort($entrieszz, function($ac,$bc){
return $bc->createDate-$ac->createDate;
});
foreach($entrieszz as $statSummaryzz){
$gamemodekillz = $statSummaryzz->stats->championsKilled;
$gamemodedeathz = $statSummaryzz->stats->numDeaths;
$gamemodeassistz = $statSummaryzz->stats->assists;
$kdamatchhistoryeach = ($gamemodekillz + $gamemodeassistz) / $gamemodedeathz;
echo ' <br>';
echo $gamemodekillz;
echo ' <br>';
if ($gamemodedeathz == 0){
echo '0';
}
else {
echo $gamemodedeathz ;
}
echo ' <br>';
echo $gamemodeassistz;
echo ' <br>';
if ($gamemodedeathz == 0){
echo 'Perfect Score';
}
else {
echo $kdamatchhistoryeach ;
}
?>
You need to check if the value exist:
if( isset($statSummaryzz->stats) && isset($statSummaryzz->stats->numDeaths) ) {
$gamemodedeathz = $statSummaryzz->stats->numDeaths;
}
Related
I am a beginner programmer. Only in php.
On php, am at procedural style. Not on oop or pdo yet. Hence, you see mysqli and procedural style.
I am building a SERP with pagination. Like google, when they show you your keywords search result.
Don't mistake my thread. Not trying to prevent Sql injection as I managed to do it using prepared statements.
Learning to use urlencode(), rawurlencode(), htmlentities() as I'm trying to use them to prevent user's injecting unwanted html tags to breakup the html of my SERPs.
On this occasion, I am having problem using urlencode() properly.
I get this error:
Warning: urlencode() expects parameter 1 to be string, array given in ... on line ...
Following are the concerned lines as I urlencode() their values so no user (keywords searcher) can inject html tags to breakup the html of my SERP:
$search = $_GET['search']; //Keyword(s) to search.
$col = $_GET['col']; //MySql Tbl Col to search.
$tbl = $_GET['tbl']; //MySql Tbl to search.
$max = $_GET['max']; //Max Result per page.
$page = $_GET['page']; //Serp Number.
The above vars contain one values each as each $_GET contains one value each, even though $_GET is a a global variable (array). So here, nothing to do with arrays or more than one value per each variable.
Issue is on this following line that comes just after the WHILE loop:
LINE 145
$query_string_1 = '?search=' .urlencode($search) .'&tbl=' .urlencode($tbl) .'&col=' .urlencode($col) .'&max=' .intval($max);
Here is the code context:
//ERROR REPORTING FOR DEVMODE ONLY.
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
//MYSQLI CONNECTION.
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
}
if(!mysqli_character_set_name($conn) == 'utf8mb4')
{
echo 'Initial Character Set: ' .mysqli_character_set_name($conn);
mysqli_set_charset("$conn",'utf8mb4');
echo 'Current Character Set: ' .mysqli_character_set_name($conn);
}
//PAGINATION SECTION.
$search = $_GET['search']; //Keyword(s) to search.
$col = $_GET['col']; //MySql Tbl Col to search.
$tbl = $_GET['tbl']; //MySql Tbl to search.
$max = $_GET['max']; //Max Result per page.
$page = $_GET['page']; //Serp Number.
//QUERY DATABASE FOR KEYWORD COUNT.
$query = "SELECT COUNT(id) From links WHERE keyword = ?";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$search);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$row_count);
if(mysqli_stmt_fetch($stmt))
{
echo 'Row Count: ' .$row_count; echo '<br>';
}
else
{
echo 'Record fetching failed!';
echo 'Error: ' .mysqli_stmt_error($conn);
echo 'Error: ' .mysqli_stmt_errno($conn);
}
mysqli_stmt_close($stmt);
}
else
{
echo 'Search Preparation Failed!';
}
//mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
//START KEYWORD SEARCH & OUTPUT RESULT
echo $offset = ($page*$max)-$max; echo '<br>';
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
$query = "SELECT id,date_and_time,domain,domain_email,ip,url,anchor,title,description,keyword,keyphrase From links WHERE keyword = ? LIMIT $offset,$max";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$search);
mysqli_stmt_execute($stmt);
if($result = mysqli_stmt_get_result($stmt))
{
/*
FOLLOWING BOTH ARE EQUAL:
$col = mysqli_fetch_array($result) //SHORT VERSION.
$col = mysqli_fetch_array($result,MYSQLI_BOTH) //LONG VERSION.
*/
$col = mysqli_fetch_array($result); //SHORT VERSION.
$id = $col['0']; //MYSQLI_NUM
$date_and_time = $col['date_and_time']; //MYSQLI_ASSOC
$domain = $col['2']; //MYSQLI_NUM
$domain_email = $col['domain_email']; //MYSQLI_ASSOC
$ip = $col['4']; //MYSQLI_NUM
$url = $col['url']; //MYSQLI_ASSOC
$anchor = $col['6']; //MYSQLI_NUM
$title = $col['title']; //MYSQLI_ASSOC
$description = $col['8']; //MYSQLI_NUM
$keyword = $col['keyword']; //MYSQLI_ASSOC
$keyphrase = $col['10']; //MYSQLI_NUM
echo 'Id: ' .$id; echo '<br>';
echo 'Date And Time: ' .$date_and_time; echo '<br>';
echo 'Domain: ' .$domain; echo '<br>';
echo 'Domain Email: ' .$domain_email; echo '<br>';
echo 'Ip: ' .$ip; echo '<br>';
echo 'Url: ' .$url; echo '<br>';
echo 'Anchor: ' .$anchor; echo '<br>';
echo 'Title: ' .$title; echo '<br>';
echo 'Description: ' .$description; echo '<br>';
echo 'Keyword: ' .$keyword; echo '<br>';
echo 'Keyphrase: ' .$keyphrase; echo '<br>';
}
else
{
echo 'Record fetching failed!';
echo 'Error: ' .mysqli_stmt_error($stmt);
echo 'Error: ' .mysqli_stmt_errno($stmt);
}
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
//PAGINATION SECTION TO NUMBER THE PAGES AND LINK THEM.
$total_pages = ceil($row_count/$max);
$i = '1';
//$selfpage = $_SERVER['PHP_SELF'];
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url $_GET params.
$path = rawurlencode($selfpage);
$query_string_1 = '?search=' .urlencode($search) .'&tbl=' .urlencode($tbl) .'&col=' .urlencode($col) .'&max=' .intval($max);
while($i<=$total_pages)
{
$query_string_2 = '&page=' .intval($i);
$url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_GET params: https://localhost/Templates/url_encode_Template.php?search=keyword&tbl=links&col=keyword&max=100&page=1
if($page == $i)
{
echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>';
}
$i++;
}
?>
Frankly, the pagination page is nearly finished, had it not been for this urlencode() issue!
If you spot any other errors which I have not asked about it's subject due to overlooking them then kindly show me a code sample by editing my code in order to show me how I really should've coded it. (I'm talking about my usage of urlencode(), rawurlencode(), htmlentities() as I'm trying to use them to prevent user's injecting unwanted html tags) to breakup my SERP.
I'd appreciate it if my code is edited by someone and the correction is displayed on this thread, wherever I went wrong.
Your problem is that you are overwriting the value of the $col variable that you initially populate with the 'col' parameter in the GET request with the result of your keyword search.
$col = $_GET['col']; //MySql Tbl Col to search.
...
$col = mysqli_fetch_array($result); //SHORT VERSION.
You do not seem to be using the col parameter for anything, you may be able to just remove it from the query string. If you do intend to use it, simply rename the variable you are using for the query result row.
For future reference, you can encode array values into a query string using the http_build_query function. This would simplify your code, and would have allowed you to see were the problem is in this case.
// Set some test values for the parameters
$search = 'my search term';
$tbl = 'my_table_name';
$col = 'column_1';
$max = 10;
// Simulate variable being overwritten with database result
$col = [
'id' => 123,
'date_and_time' => '2021-06-20 09:44:00',
'domain' => 'stackoverflow.com'
];
// Build an array of the parameters to be included in the query string
$queryParameters = [
'search' => $search,
'tbl' => $tbl,
'col' => $col,
'max' => $max
];
/*
* Build the query string using http_build_query
* Any array values will be represented appropriately
* Prepend the ? to the result
*/
$query_string_1 = '?'.http_build_query($queryParameters);
echo $query_string_1.PHP_EOL;
I'm writing a custom import script for SuiteCRM and I'm getting the error:
Warning: array_combine() expects parameter 2 to be array, boolean
given in /var/www/html/afscmedbv5test/custom/wimporter/newimporter.php
on line 162
My Script is as follows:
<?php
if (!defined('sugarEntry') || !sugarEntry) die ('Not a Valid Entry Point!');
$date = new DateTime();
echo '<H2>Wilderness Import Started</h2>';
echo $date->format('r').'<br>';
echo '-----------------------------------------------------------------------
--------------------------------------------------------------<br>';
require_once("include/utils/sugar_file_utils.php");
WildernessImportJob();
die();
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
function time_elapsed()
{
static $first = null;
static $previous = null;
$now = microtime(true);
if ($first == null) $first = $now;
if ($previous != null)
echo '--- Partial ' . round(($now - $previous), 2) . ', Total ' . round(($now
- $first), 2) . ' ---'; // 109s
$ret = round(($now - $previous), 2);
$previous = $now;
return $ret;
}
function myLog ($str2log)
{
file_put_contents('./zlog_'.date("j.n.Y").'.txt', date("H:i:s", time())."
".$str2log.PHP_EOL, FILE_APPEND);
}
function calcDelta($a1, $a2)
{
//combine into a nice associative array:
$delta=Array();
foreach ($a1 as $key=>$value)
{
if ($a1[$key] != $a2->$key)
$delta[] = array($key => ("Was ". $a1[$key]. ", became " . $a2->$key));
}
$num = count($data);
if (empty($a1)) $delta[] = array("a1" => ("Was empty"));
if (empty($a2)) $delta[] = array("a2" => ("Was empty"));
return $delta;
}
require_once("include/utils/sugar_file_utils.php");
function fillPerson($record, &$person)
{
// $record is what is being imported from CSV
// $person is the bean about to be filled and going into the SuitCRM DB. It
may be new or not, depending on whether it exists in the DB previously.
// name: only updates if not existant yet, because it's the key we use for
search, and because names are more complex with parts
if ($person->full_name_c == "") {
$recordname = $record["FULL NAME"]; // != "") ? $record["FULL NAME"] : "
[To-be-filled]");
//echo $prefix;
$recordname = str_replace(" ", " ", $recordname);
echo $recordname;
$parts = explode(" ", $recordname);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
$person->name = $person->first_name . " " . $person->last_name;
$person->full_name_c = $record["FULL NAME"]; // custom field created in
Studio
}
//$datanasc = DateTime::createFromFormat('!m/d/Y', $record["PPE"]);
// $datasnasc->setTime(0, 0);
// $person->ppe_date_c = ($datanasc == false) ? "" : $datanasc->format('m-d-
Y');
//$person->ppe_date_c = $record["PPE"];
//print_r($person);
var_dump($person);
}
// finish by making a complete analysis of what changed:
return calcDelta($person->fetched_row, $person);
function GetOrCreateMember ($the_name)
{
//Check if the fullname is null
if ($the_name != "")
{
$person = BeanFactory::getBean("locte_Members");
$person = $person->retrieve_by_string_fields(array('full_name_c' =>
$the_name));
if (is_null($person))
{
//get members bean
$person = BeanFactory::newBean("locte_Members");
//set full_name_c to the_name variable
$person->full_name_c = $the_name;
// $person->lcl_employee_id = $personEmployeeID;
$person_name = str_replace(" ", " ", $the_name);
$parts = explode(" ", $person_name);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
//combine first and last name to populate the fullname field
$person->name = $person->first_name . " " . $person->last_name;
$person_id = $person->save();
// add new duespayment to member record
// $rosterDuesPayments = BeanFactory::getBean('Dues Payments')-
>retrieve_by_string_fields(array('name'=> $duesEmployeeID));
// $person->load_relationship('locte_Members_adues_dues'); //confirm
relationship name in cache
// $person->dues_payments->add($rosterDuesPayments->id);
}
return $person;
}
return null;
}
function WildernessImportJob()
{
try
{
time_elapsed();
$GLOBALS['log']->info('Wilderness Import');
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/ToImport'; //$config->config['WildernessImporter_DataFilePath'];
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir...");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir...<br /></h3>");
$directoryContent = scandir($xmlDataDir);
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]</h3><br />");
foreach ($directoryContent as $itemFile)
{
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$GLOBALS['log']->info("Wilderness Import: Processing $itemFile file...");
myLog("---------------------------------------------------");
myLog("Wilderness Import: Processing $itemFile file...");
myLog("----------------------------------------------------");
echo("<h4>---------------------------------------------------------------</h4>");
echo("<h4>Wilderness Import: Processing $itemFile file...</h4>");
echo("<h4>---------------------------------------------------------------</h4>");
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
// read entire file at once:
// expected separator is ",", expected encoding is UTF-8 without BOM (BOM is 3 weird characters in beginning of file)
while (($data[] = fgetcsv($oFile, 0, ',')) !== FALSE) { }
echo('File opened..... <br /> <br />');
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
echo('Building CSV File Row Array <br /><br />');
$fields = array_shift($data);
echo('Building CSV Header Fields Array as shown below:<strong> <br /><br />');
echo implode(", ", $fields) . "</strong><br /><br />\n";
foreach ($data as $i=>$arow)
{
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
$data[$i] = array_combine($fields, $arow);
}
unset($arow); // **********************************************! ! ! !! ! ! ! ! ! !! !
$num = count($data);
echo('Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below <br /><br />');
for ($row=0; $row < $num - 1 ; $row++)
{ // normal bounds: from 0 to $num
//$num is the number of lines including header in csv file
echo "<strong>Filename: $itemFile | Roster Import, Row" . ($row + 1) . ":</strong><br />\n";
$GLOBALS['log']->info("Wilderness Import: Importing " . $data[$row]["FULL NAME"]);
// echo("<strong>Importing Roster Row #: ". ($row + 1) . "<br />" . "Local Number " . $data[$row]["AFFILIATE"] . "<br />" . "Employee: " . $data[$row]["FULL NAME"] . "</strong><br /><br />");
echo "<strong><table>\n";
foreach ($fields as $field) {
//echo "<tr><td>" . $field . "</td><td>" . $data[$row][$field] . "</td><td>" . $data[$row+1][$field] . "</td><td>" . $data[$row+2][$field] . "</td></tr>\n";
}
echo "</table>\n";
echo "File Row Data: ";
echo implode(", ", $data[$row]) . "</strong><br /><br />\n";
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member, ""); //->full_name_c, "FULL NAME");
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
$GLOBALS['log']->info('End: Wilderness Import');
myLog('End: Wilderness Import');
time_elapsed();
return true;
}
}
} catch (Exception $e)
{
$GLOBALS['log']->fatal("Wilderness Import: Exception " . $e->getMessage());
myLog("Wilderness Import: Exception " . $e->getMessage());
echo '\n\nCaught exception: ', $e->getMessage(), "\n";
return false;
}
}
It does return info from both the database and the csv file.
Image of error below.
Error - Capture from browser
Help always appreciated :)
This script is throwing error because the parameter $arow given to array_combine is not an array. So a check should be there to check whether $arow is an array or not.
Try code following:
foreach ($data as $i => $arow) {
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);
}
}
Read more about array_combine
Update
Code you are using to read csv need to be changed. Second parameter in fgetcsv must be greater than the longest line (in characters) to be found in the CSV file. So replace code
while (($data[] = fgetcsv($oFile, 0, ', ')) !== FALSE) {
}
with
while (($data[] = fgetcsv($oFile, 10, ', ')) !== FALSE) {
}
Read more about fgetcsv
This block is doing the saving of records using the beanfactory.... I think :|
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member->full_name_c, "FULL NAME");
var_dump($arow);
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
Here's the output of the script in the browser with field definition dump
Wilderness Import Started
Tue, 19 Jun 2018 02:05:56 -0400
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport...
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport... [Found 3 files]
Wilderness Import: Processing L1554v4.csv file...
File opened.....
Building CSV File Row Array
Building CSV Header Fields Array as shown below:
LAST NAME, FIRST NAME, FULL NAME
Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below
Filename: L1554v4.csv | Roster Import, Row1:
LAST NAME BUTLER
FIRST NAME BRIANA
FULL NAME BUTLER BRIANA
File Row Data: BUTLER, BRIANA, BUTLER BRIANA
-id
-name
-date_entered
-date_modified
-modified_user_id
-modified_by_name
-created_by
-created_by_name
-description
-deleted
-securitygroup
-securitygroup_display
-created_by_link
-modified_user_link
-assigned_user_id
-assigned_user_name
-assigned_user_link
-additionalusers
-additionalusers_listview
-salutation
-first_name
-last_name
-full_name
-title
-photo
-department
-do_not_call
-phone_home
-email
-phone_mobile
-phone_work
-phone_other
-phone_fax
-email1
-email2
-invalid_email
-email_opt_out
-primary_address_street
-primary_address_street_2
-primary_address_street_3
-primary_address_city
-primary_address_state
-primary_address_postalcode
-primary_address_country
-alt_address_street
-alt_address_street_2
-alt_address_street_3
-alt_address_city
-alt_address_state
-alt_address_postalcode
-alt_address_country
-assistant
-assistant_phone
-email_addresses_primary
-email_addresses
-email_addresses_non_primary
-lcl_birthdate
-lcl_affiliate_number
-member_signature
-ssn
-staff_rep
-mem_join_date
-class_title
-steward
-olo_code
-enterprise_id
-member_card
-address_map
-member_status
-primary_language
-english_speaking
-annual_salary
-currency_id
-state_hire_date
-dues_frequency
-card_sent_date
-gender
-disabilities
-marital_status
-executive_board
-affiliate_type
-middle_name
-name_suffix
-mailableflag
-no_mailflag
-apt_number
-zip4
-infosrc
-lcl_phone_collected
-lcl_hasmobile
-lcl_hasemail
-lcl_member_status
-backofficeassistants
-backoffice_assistant_phonoe
-backoffice_assistant_email
-lcl_employercontact
-lcl_work_dept
-lcl_work_location
-lcl_jobclasstitle
-lcl_employee_id
-lcl_join_date
-lcl_sig_auth
-lcl_dues_status
-lcl_on_probation
-lcl_prob_end_date
-lcl_prob_term
-afs_signed_by
-afs_region_number
-afemp_employers_id_c
-afs_employer
-primary_address_county
-locte_members_adues_dues
-full_name_c
-locte_members_afcbu_cbu
-locte_members_afcbu_cbu_name
-locte_members_afcbu_cbuafcbu_cbu_idb
-ppe_date_c
--- Partial 0.01, Total 0.01 ---
I have some code which uses odbc calls. I've had no problem with the pulling data from a MS SQL database until this bit of code. Instead of saving the string to a variable it outputs the string and saves an int 1 to the variable instead.
below is the relevant code:
$qry = 'SELECT * FROM cst_AdEssayDetails_vw WHERE AdEnrollSchedID = ?';
$essay = odbc_prepare($conn,$qry);
if(odbc_execute($essay,array($AdEnrollSchedID))){
if (odbc_num_rows($essay)>0){
while (odbc_fetch_row($essay)){
$setTopic = odbc_result($essay,'setTopic');
$essay_active = odbc_result($essay,'active');
$essay_date = date("m-d-y", strtotime(odbc_result($essay,'StartDate')));
$essayID = odbc_result($essay,'EssayID');
$EnrollSchedID = odbc_result($essay,'AdEnrollSchedID');
$intro = odbc_result($essay,'intro');
$support = odbc_result($essay,'support');
$conclusion = odbc_result($essay,'conclusion');
$essay_comment = odbc_result($essay,'comment');
$submitted = odbc_result($essay,'submitted');
$dateSubmitted = date("m-d-y", strtotime(odbc_result($essay,'dateSubmitted')));
$essay_grade = odbc_result($essay,'grade');
$AdStudentEssayID = odbc_result($essay,'AdStudentEssayID');
$topic = odbc_result($essay,'topic');
echo '<intro1>'.$intro.'</intro1>';
echo '<intro_len>'.strlen($intro).'</intro_len>';
if (1 > strlen($essay_comment)){
$essay_comment = ' ';
} else {
$essay_comment = urlencode($essay_comment);
}
if (1 > strlen($essay_grade)) {
$essay_grade = ' ';
}
if (2 < strlen($topic)){
$topic = urlencode($topic);
} else {
$topic = ' ';
}
if (2 < strlen($intro)){
$intro = urlencode($intro);
} else {
$intro = ' ';
}
if (2 < strlen($support)){
$support = urlencode($support);
} else {
$support = ' ';
}
if (2 < strlen($conclusion)){
$conclusion = urlencode($conclusion);
} else {
$conclusion = ' ';
}
echo '<setTopic>'.$setTopic.'</setTopic>';
echo '<essay_active>'.$essay_active.'</essay_active>';
echo '<essay_date>'.$essay_date.'</essay_date>';
echo '<essayID>'.$essayID.'</essayID>';
echo '<topic>'.$topic.'</topic>';
echo '<intro>'.$intro.'</intro>';
echo '<support>'.$support.'</support>';
echo '<conclusion>'.$conclusion.'</conclusion>';
echo '<essay_comment>'.$essay_comment.'</essay_comment>';
echo '<submitted>'.$submitted.'</submitted>';
echo '<dateSubmitted>'.$dateSubmitted.'</dateSubmitted>';
echo '<essay_grade>'.$essay_grade.'</essay_grade>';
echo '<AdStudentEssayID>'.$AdStudentEssayID.'</AdStudentEssayID>';
}
} else {
The output I get from this is:
'Test Introduction Paragraph
Test Supporting Paragraph
2nd test supporting paragraph
Test Conclusion Paragraph
Test Essay Topic
<intro1>1</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic></topic>
<intro></intro>
<support></support>
<conclusion></conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
The output I expect is:
'<intro1>Test Introduction Paragraph</intro1>
<intro_len>1</intro_len>
<setTopic>%3Cp%3ETest%20Topic%3C%2Fp%3E</setTopic>
<essay_active>1</essay_active>
<essay_date>01-01-70</essay_date>
<essayID>29</essayID>
<topic>Test Essay Topic</topic>
<intro>Test Introduction Paragraph</intro>
<support>Test Supporting Paragraph 2nd test supporting paragraph</support>
<conclusion>Test Conclusion Paragraph</conclusion>
<essay_comment>1</essay_comment>
<submitted>1</submitted>
<dateSubmitted>07-11-16</dateSubmitted>
<essay_grade></essay_grade>
<AdStudentEssayID>59</AdStudentEssayID>'
So the question is, Why is it doing this? Why does it output 'intro','support','conclusion', and 'topic' instead of saving them to the variable?
I do not understand fully why this PHP code is not saving the data in the arrays. when I echo out the array during the while loop, the values are set but after I exit the loop, the values in the array are missing. The other variables did contain their values after leaving the array.
<?php
class VIEWARRAY {
public $year;
public $month;
public $day = array();
public $views = array();
}
$viewdatabase = array();
$connection = MySQL_Connection($host, Session_Get("username"), Session_Get("password"), $database);
$dayviewindex = 0; $monthyearindex = 0; $previousmonth = "";
$information = MySQL_Script($connection, "SELECT * FROM viewdatabase");
while ($index = mysqli_fetch_array($information)) {
if ($index["month"] != $previousmonth) {
$viewdatabase[$monthyearindex] = new VIEWARRAY;
$viewdatabase[$monthyearindex]->year = $index["year"];
$viewdatabase[$monthyearindex]->month = $index["month"];
$dayviewindex = 0;
$monthyearindex++;
$previousmonth = $index["month"];
}
$viewdatabase[$monthyearindex]->day[$dayviewindex] = $index["day"];
$viewdatabase[$monthyearindex]->views[$dayviewindex] = $index["views"];
$dayviewindex++;
}
MySQL_Disconnect($connection);
//testing area
echo "->" . $viewdatabase[0]->year . " + " . $viewdatabase[0]->month . "<br />"; //prints out ->2013 + 8
echo "------>" . $viewdatabase[0]->day[2] . " + " . $viewdatabase[0]->views[2] . "<br />"; //prints out ------> +
echo count($viewdatabase[0]->views) . "<br />"; //prints out 0
echo count($viewdatabase[1]->views) . "<br />"; //prints out 0
?>
I made sure that I was able to connect to my database just fine and that my database did return information. This is how my database is setup
year month day views
2013 8 25 1
2013 8 26 1
2013 8 27 1
2013 9 3 1
At first run, after if ($index["month"] != $previousmonth), $monthyearindex will be 1.
That means you'll next try to access $viewdatabase[1] but it's NULL.
On the next iteration you won't enter the if, $monthyearindex will be 1, and $viewdatabase[1] will still be NULL.
So you never actually get to set anything in day and views.
Use
if ($index["month"] !== $previousmonth) {
instead of
if ($index["month"] != $previousmonth) {
, because
0 == ''
, but
0 !== ''
. Because,
$index['month'] != ''
is
false
, your if statement fails.
I have a form that when a url is placed in the form and the button is clicked the URL is process and based on the pregmatch it extracts a URL. When a match is found for one of them the others return an error Notice: Undefined offset: 1 how can i make it so that if a match is found for one the others are not giving an error?
if ( !isset( $_GET['go'] ) ) return;
$userLink = $_GET['go'] ;
if ( !$userLink ) return;
$data = file_get_contents($userLink);
preg_match("#^(?:\s)*var url = '(.*)';#mi",$data, $parsed1);
preg_match("#^(?:\s)*self.location = '(.*)';#mi",$data, $parsed2);
preg_match("#^(?:\s)*window.location = \"(.*)\";#mi",$data, $parsed3);
preg_match("#^(?:\s)*Lbjs.TargetUrl = '(.*)';#mi",$data, $parsed4);
preg_match("#^(?:\s)*linkDestUrl = '(.*)';#mi",$data, $parsed5);
echo 'var.url - ' . $parsed1[1] . '<br>';
echo 'self.location - ' . $parsed2[1] . '<br>';
echo 'window.location - ' . $parsed3[1] . '<br>';
echo 'Lbjs.TargetUrl - ' . $parsed4[1] . '<br>';
echo 'linkDestUrl - ' . $parsed5[1];
I'm presuming only one of the URL types is going to match, not two or more?
if ( !isset( $_GET['go'] ) ) return;
$userLink = $_GET['go'] ;
if ( !$userLink ) return;
$data = file_get_contents($userLink);
$array = array(
'var url',
'self.location',
'window.location',
'Lbjs.TargetUrl',
'linkDestUrl',
);
foreach ($array as $value)
{
if (preg_match("#^(?:\s)*($value) = '(.*)';#mi",$data, $parsed))
{
break;
}
}
echo $parsed[1] . ' - ' . $parsed[2] . '<br>';
All you need to do is check whether the element is set before printing:
echo 'var.url - ' . (isset($parsed1[1]) ? $parsed[1] : 'not found') . '<br>';
echo 'self.location - ' . (isset($parsed1[2]) ? $parsed[2] : 'not found') . '<br>';
echo 'window.location - ' . (isset($parsed1[3]) ? $parsed[3] : 'not found') . '<br>';
echo 'Lbjs.TargetUrl - ' . (isset($parsed1[4]) ? $parsed[4] : 'not found') . '<br>';
echo 'linkDestUrl - ' . (isset($parsed1[5]) ? $parsed[5] : 'not found');
You can try to catch the result of preg_match, which will return 0 if no matches are found. From the php docs:
preg_match() returns the number of times pattern matches. That will be
either 0 times (no match) or 1
Something like:
if(preg_match("#^(?:\s)*var url = '(.*)';#mi",$data, $parsed1)) {
if(!empty($parsed1[1])) { echo 'var.url - ' . $parsed1[1] . '<br>'; }
}
You can put a # before each of your preg_match statements. # suppresses error messages, so be careful where you use it.
#preg_match("#^(?:\s)*var url = '(.*)';#mi",$data, $parsed1);
if (preg_match("#^(?:\s)*(var url|self.location|window..location|Lbjs.TargetUrl|linkDestUrl) = ['\"](.*)[\"'];#mi", $data, $parsed)) {
echo $parsed[1], " - ", $parsed[2];
} else {
echo "no matches found at all";
}